forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-chat-completion.ts
More file actions
95 lines (86 loc) · 2.55 KB
/
Copy pathfetch-chat-completion.ts
File metadata and controls
95 lines (86 loc) · 2.55 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
Message,
Function,
ChatCompletionEvent,
decodeChatCompletion,
parseChatCompletion,
decodeChatCompletionAsText,
} from "@copilotkit/shared";
import { CopilotApiConfig } from "../context";
export interface FetchChatCompletionParams {
copilotConfig: CopilotApiConfig;
model?: string;
messages: Message[];
functions?: Function[];
temperature?: number;
maxTokens?: number;
headers?: Record<string, string> | Headers;
body?: object;
signal?: AbortSignal;
}
export async function fetchChatCompletion({
copilotConfig,
model,
messages,
functions,
temperature,
headers,
body,
signal,
}: FetchChatCompletionParams): Promise<Response> {
temperature ||= 0.5;
functions ||= [];
// clean up any extra properties from messages
const cleanedMessages = messages.map((message) => {
const { content, role, name, function_call } = message;
return { content, role, name, function_call };
});
const response = await fetch(copilotConfig.chatApiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
...copilotConfig.headers,
...(headers ? { ...headers } : {}),
},
body: JSON.stringify({
model,
messages: cleanedMessages,
stream: true,
...(functions.length ? { functions } : {}),
...(temperature ? { temperature } : {}),
...(functions.length != 0 ? { function_call: "auto" } : {}),
...copilotConfig.body,
...(body ? { ...body } : {}),
}),
signal,
});
return response;
}
export interface DecodedChatCompletionResponse extends Response {
events: ReadableStream<ChatCompletionEvent> | null;
}
export async function fetchAndDecodeChatCompletion(
params: FetchChatCompletionParams,
): Promise<DecodedChatCompletionResponse> {
const response = await fetchChatCompletion(params);
if (!response.ok || !response.body) {
return { ...response, events: null };
}
const events = await decodeChatCompletion(parseChatCompletion(response.body));
return { ...response, events };
}
export interface DecodedChatCompletionResponseAsText extends Response {
events: ReadableStream<string> | null;
}
export async function fetchAndDecodeChatCompletionAsText(
params: FetchChatCompletionParams,
): Promise<DecodedChatCompletionResponseAsText> {
const response = await fetchChatCompletion(params);
if (!response.ok || !response.body) {
return { ...response, events: null };
}
const events = await decodeChatCompletionAsText(
decodeChatCompletion(parseChatCompletion(response.body)),
);
return { ...response, events };
}