-
Notifications
You must be signed in to change notification settings - Fork 299
Expand file tree
/
Copy pathconvert-to-workersai-chat-messages.ts
More file actions
109 lines (100 loc) · 2.48 KB
/
convert-to-workersai-chat-messages.ts
File metadata and controls
109 lines (100 loc) · 2.48 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { type LanguageModelV1Prompt, UnsupportedFunctionalityError } from "@ai-sdk/provider";
import type { WorkersAIChatPrompt } from "./workersai-chat-prompt";
export function convertToWorkersAIChatMessages(
prompt: LanguageModelV1Prompt,
excludeContentWithToolCalls = false
): WorkersAIChatPrompt {
const messages: WorkersAIChatPrompt = [];
for (const { role, content } of prompt) {
switch (role) {
case "system": {
messages.push({ role: "system", content });
break;
}
case "user": {
messages.push({
role: "user",
content: content
.map((part) => {
switch (part.type) {
case "text": {
return part.text;
}
case "image": {
throw new UnsupportedFunctionalityError({
functionality: "image-part",
});
}
}
})
.join(""),
});
break;
}
case "assistant": {
let text = "";
const toolCalls: Array<{
id: string;
type: "function";
function: { name: string; arguments: string };
}> = [];
for (const part of content) {
switch (part.type) {
case "text": {
text += part.text;
break;
}
case "tool-call": {
text = JSON.stringify({
name: part.toolName,
parameters: part.args,
});
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.args),
},
});
break;
}
default: {
const exhaustiveCheck = part;
throw new Error(`Unsupported part: ${exhaustiveCheck}`);
}
}
}
messages.push({
role: "assistant",
content: excludeContentWithToolCalls && toolCalls.length > 0 ? undefined : text, // fix for mistral
tool_calls:
toolCalls.length > 0
? toolCalls.map(({ function: { name, arguments: args } }) => ({
id: "null",
type: "function",
function: { name, arguments: args },
}))
: undefined,
});
break;
}
case "tool": {
for (const toolResponse of content) {
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId, // required by mistral
name: toolResponse.toolName,
content: JSON.stringify(toolResponse.result),
});
}
break;
}
default: {
const exhaustiveCheck = role satisfies never;
throw new Error(`Unsupported role: ${exhaustiveCheck}`);
}
}
}
return messages;
}