Spaces:
Running
Running
import OpenAI from 'openai'; | |
interface ChatMessage { | |
role: 'system' | 'user' | 'assistant'; | |
content: string; | |
} | |
class OpenAIService { | |
private openai: OpenAI; | |
private model: string = 'gpt-4'; | |
constructor() { | |
const apiKey = import.meta.env.VITE_OPENAI_API_KEY; | |
if (!apiKey) { | |
throw new Error('OpenAI API key is required. Please add your API key to the .env file as VITE_OPENAI_API_KEY.'); | |
} | |
this.openai = new OpenAI({ | |
apiKey, | |
dangerouslyAllowBrowser: true // Note: In production, API calls should be made from a backend | |
}); | |
} | |
async sendChatCompletion(messages: ChatMessage[]) { | |
try { | |
const completion = await this.openai.chat.completions.create({ | |
model: this.model, | |
messages, | |
temperature: 0.7, | |
max_tokens: 1000, | |
frequency_penalty: 0, | |
presence_penalty: 0 | |
}); | |
return completion.choices[0].message; | |
} catch (error) { | |
console.error('Error in chat completion:', error); | |
throw error; | |
} | |
} | |
} | |
export default OpenAIService; |