-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathllmChat.ts
58 lines (49 loc) · 1.41 KB
/
llmChat.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
import { FunctionFailure, log } from "@restackio/ai/function";
import {
ChatCompletionCreateParamsNonStreaming,
ChatCompletionMessage,
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionTool,
ChatCompletionToolMessageParam,
ChatCompletionUserMessageParam,
} from "openai/resources/chat/completions";
import { openaiClient } from "../utils/client";
export type Message =
| ChatCompletionSystemMessageParam
| ChatCompletionUserMessageParam
| ChatCompletionToolMessageParam;
export type OpenAIChatInput = {
systemContent?: string;
model?: string;
messages: Message[];
tools?: ChatCompletionTool[];
};
export const llmChat = async ({
systemContent = "",
model = "gpt-4o-mini",
messages,
tools,
}: OpenAIChatInput): Promise<ChatCompletionMessage> => {
try {
const openai = openaiClient({});
const chatParams: ChatCompletionCreateParamsNonStreaming = {
messages: [
...(systemContent
? [{ role: "system" as const, content: systemContent }]
: []),
...(messages ?? []),
],
model,
tools,
};
log.debug("OpenAI chat completion params", {
chatParams,
});
const completion = await openai.chat.completions.create(chatParams);
const message = completion.choices[0].message;
return message;
} catch (error) {
throw FunctionFailure.nonRetryable(`Error OpenAI chat: ${error}`);
}
};