forked from NeuraLegion/brokencrystals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.service.ts
61 lines (51 loc) · 1.57 KB
/
chat.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
52
53
54
55
56
57
58
59
60
61
import { Injectable, Logger } from '@nestjs/common';
import { HttpClientService } from '../httpclient/httpclient.service';
import { ChatMessage } from './api/ChatMessage';
const DEFAULT_CHAT_API_MAX_TOKENS = 1000;
interface ChatRequest {
readonly model: string;
readonly messages: ChatMessage[];
readonly stream: boolean;
readonly max_tokens?: number;
readonly temperature?: number;
}
interface ChatResponse {
readonly choices: {
readonly message: ChatMessage;
}[];
}
@Injectable()
export class ChatService {
private readonly logger = new Logger(ChatService.name);
constructor(private readonly httpClient: HttpClientService) {}
async query(messages: ChatMessage[]): Promise<string> {
this.logger.debug(`Chat query: ${JSON.stringify(messages)}`);
if (
!process.env.CHAT_API_URL ||
!process.env.CHAT_API_MODEL ||
!process.env.CHAT_API_TOKEN
) {
throw new Error(
'Chat API environment variables are missing. CHAT_API_URL, CHAT_API_MODEL, CHAT_API_TOKEN are mandatory.',
);
}
const chatRequest: ChatRequest = {
model: process.env.CHAT_API_MODEL,
messages,
max_tokens:
+process.env.CHAT_API_MAX_TOKENS || DEFAULT_CHAT_API_MAX_TOKENS,
stream: false,
};
const res = await this.httpClient.post<ChatResponse>(
process.env.CHAT_API_URL,
chatRequest,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.CHAT_API_TOKEN}`,
},
},
);
return res?.choices?.[0]?.message?.content;
}
}