-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathchat.ts
More file actions
57 lines (48 loc) · 1.42 KB
/
chat.ts
File metadata and controls
57 lines (48 loc) · 1.42 KB
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
import axios from "axios";
import axiosRetry from "axios-retry";
import { logger } from "../utils/logger.js";
export const openai = axios.create({
baseURL: "https://api.openai.com/v1",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
});
axiosRetry(openai, {
retries: 3,
retryCondition: (error) => {
logger(`네트워크 요청 불량으로 재시도 중입니다. (에러코드 ${error.code}}`);
return true;
},
});
export interface ChatMessage {
role: "user" | "assistant" | "system";
content: string;
}
export const chat = async (option: {
messages: ChatMessage[];
nested?: number;
}) => {
const { messages, nested } = option;
if (nested) {
logger(`현재 ${nested}번째 ChatGPT 로 이어지는 호출 중 입니다.`);
if (nested > 10) {
logger("debug", { messages });
throw new Error("ChatGPT 호출이 너무 많습니다.");
}
}
const { data } = await openai.post("/chat/completions", {
model: "gpt-3.5-turbo",
messages,
});
const answer = `${data.choices?.[0].message?.content ?? ""}`;
const finishReason = data.choices?.[0].finish_reason as string;
if (finishReason === "length") {
const addedChat = await chat({
messages: [...messages, { role: "assistant", content: answer }],
nested: nested ? nested + 1 : 1,
});
return answer + addedChat;
}
return answer;
};