-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai.service.ts
51 lines (45 loc) · 1.42 KB
/
openai.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import OpenAI from 'openai';
@Injectable()
export class OpenAiService {
private readonly logger = new Logger(OpenAiService.name);
private openai: OpenAI;
constructor(private configService: ConfigService) {
this.openai = new OpenAI({
apiKey: this.configService.get<string>('OPENAI_API_KEY'),
baseURL:
this.configService.get<string>('OPENAI_API_BASE_URL') ||
'https://api.openai.com',
});
}
async createChatCompletion(
messages: OpenAI.Chat.ChatCompletionMessageParam[],
) {
try {
const response = await this.openai.chat.completions.create({
model: this.configService.get<string>('AI_MODEL') || 'gpt-4',
messages,
});
return response;
} catch (error) {
this.logger.error('AI API error:', error);
throw error instanceof Error ? error : new Error('AI API error');
}
}
async createChatCompletionStream(
messages: OpenAI.Chat.ChatCompletionMessageParam[],
) {
try {
const stream = await this.openai.chat.completions.create({
model: this.configService.get<string>('AI_MODEL') || 'gpt-4',
messages,
stream: true,
});
return stream;
} catch (error) {
this.logger.error('AI API error:', error);
throw error instanceof Error ? error : new Error('AI API error');
}
}
}