ai 3.1.29 → 3.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -563
- package/dist/index.d.ts +4 -563
- package/dist/index.js +38 -509
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +40 -497
- package/dist/index.mjs.map +1 -1
- package/package.json +17 -33
- package/prompts/dist/index.d.mts +2 -129
- package/prompts/dist/index.d.ts +2 -129
- package/prompts/dist/index.js.map +1 -1
- package/prompts/dist/index.mjs.map +1 -1
- package/react/dist/index.d.mts +9 -648
- package/react/dist/index.d.ts +9 -648
- package/react/dist/index.js +4 -1441
- package/react/dist/index.js.map +1 -1
- package/react/dist/index.mjs +9 -1429
- package/react/dist/index.mjs.map +1 -1
- package/rsc/dist/rsc-server.mjs +15 -236
- package/rsc/dist/rsc-server.mjs.map +1 -1
- package/solid/dist/index.d.mts +7 -465
- package/solid/dist/index.d.ts +7 -465
- package/solid/dist/index.js +3 -1057
- package/solid/dist/index.js.map +1 -1
- package/solid/dist/index.mjs +7 -1056
- package/solid/dist/index.mjs.map +1 -1
- package/svelte/dist/index.d.mts +12 -422
- package/svelte/dist/index.d.ts +12 -422
- package/svelte/dist/index.js +12 -768
- package/svelte/dist/index.js.map +1 -1
- package/svelte/dist/index.mjs +10 -762
- package/svelte/dist/index.mjs.map +1 -1
- package/vue/dist/index.d.mts +7 -459
- package/vue/dist/index.d.ts +7 -459
- package/vue/dist/index.js +3 -1057
- package/vue/dist/index.js.map +1 -1
- package/vue/dist/index.mjs +7 -1046
- package/vue/dist/index.mjs.map +1 -1
package/solid/dist/index.mjs
CHANGED
@@ -1,1059 +1,10 @@
|
|
1
|
-
// solid/
|
2
|
-
import {
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
var generateId = customAlphabet(
|
9
|
-
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
10
|
-
7
|
11
|
-
);
|
12
|
-
|
13
|
-
// shared/stream-parts.ts
|
14
|
-
var textStreamPart = {
|
15
|
-
code: "0",
|
16
|
-
name: "text",
|
17
|
-
parse: (value) => {
|
18
|
-
if (typeof value !== "string") {
|
19
|
-
throw new Error('"text" parts expect a string value.');
|
20
|
-
}
|
21
|
-
return { type: "text", value };
|
22
|
-
}
|
23
|
-
};
|
24
|
-
var functionCallStreamPart = {
|
25
|
-
code: "1",
|
26
|
-
name: "function_call",
|
27
|
-
parse: (value) => {
|
28
|
-
if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
|
29
|
-
throw new Error(
|
30
|
-
'"function_call" parts expect an object with a "function_call" property.'
|
31
|
-
);
|
32
|
-
}
|
33
|
-
return {
|
34
|
-
type: "function_call",
|
35
|
-
value
|
36
|
-
};
|
37
|
-
}
|
38
|
-
};
|
39
|
-
var dataStreamPart = {
|
40
|
-
code: "2",
|
41
|
-
name: "data",
|
42
|
-
parse: (value) => {
|
43
|
-
if (!Array.isArray(value)) {
|
44
|
-
throw new Error('"data" parts expect an array value.');
|
45
|
-
}
|
46
|
-
return { type: "data", value };
|
47
|
-
}
|
48
|
-
};
|
49
|
-
var errorStreamPart = {
|
50
|
-
code: "3",
|
51
|
-
name: "error",
|
52
|
-
parse: (value) => {
|
53
|
-
if (typeof value !== "string") {
|
54
|
-
throw new Error('"error" parts expect a string value.');
|
55
|
-
}
|
56
|
-
return { type: "error", value };
|
57
|
-
}
|
58
|
-
};
|
59
|
-
var assistantMessageStreamPart = {
|
60
|
-
code: "4",
|
61
|
-
name: "assistant_message",
|
62
|
-
parse: (value) => {
|
63
|
-
if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
|
64
|
-
(item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
|
65
|
-
)) {
|
66
|
-
throw new Error(
|
67
|
-
'"assistant_message" parts expect an object with an "id", "role", and "content" property.'
|
68
|
-
);
|
69
|
-
}
|
70
|
-
return {
|
71
|
-
type: "assistant_message",
|
72
|
-
value
|
73
|
-
};
|
74
|
-
}
|
75
|
-
};
|
76
|
-
var assistantControlDataStreamPart = {
|
77
|
-
code: "5",
|
78
|
-
name: "assistant_control_data",
|
79
|
-
parse: (value) => {
|
80
|
-
if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
|
81
|
-
throw new Error(
|
82
|
-
'"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
|
83
|
-
);
|
84
|
-
}
|
85
|
-
return {
|
86
|
-
type: "assistant_control_data",
|
87
|
-
value: {
|
88
|
-
threadId: value.threadId,
|
89
|
-
messageId: value.messageId
|
90
|
-
}
|
91
|
-
};
|
92
|
-
}
|
93
|
-
};
|
94
|
-
var dataMessageStreamPart = {
|
95
|
-
code: "6",
|
96
|
-
name: "data_message",
|
97
|
-
parse: (value) => {
|
98
|
-
if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
|
99
|
-
throw new Error(
|
100
|
-
'"data_message" parts expect an object with a "role" and "data" property.'
|
101
|
-
);
|
102
|
-
}
|
103
|
-
return {
|
104
|
-
type: "data_message",
|
105
|
-
value
|
106
|
-
};
|
107
|
-
}
|
108
|
-
};
|
109
|
-
var toolCallsStreamPart = {
|
110
|
-
code: "7",
|
111
|
-
name: "tool_calls",
|
112
|
-
parse: (value) => {
|
113
|
-
if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some(
|
114
|
-
(tc) => tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string"
|
115
|
-
)) {
|
116
|
-
throw new Error(
|
117
|
-
'"tool_calls" parts expect an object with a ToolCallPayload.'
|
118
|
-
);
|
119
|
-
}
|
120
|
-
return {
|
121
|
-
type: "tool_calls",
|
122
|
-
value
|
123
|
-
};
|
124
|
-
}
|
125
|
-
};
|
126
|
-
var messageAnnotationsStreamPart = {
|
127
|
-
code: "8",
|
128
|
-
name: "message_annotations",
|
129
|
-
parse: (value) => {
|
130
|
-
if (!Array.isArray(value)) {
|
131
|
-
throw new Error('"message_annotations" parts expect an array value.');
|
132
|
-
}
|
133
|
-
return { type: "message_annotations", value };
|
134
|
-
}
|
135
|
-
};
|
136
|
-
var toolCallStreamPart = {
|
137
|
-
code: "9",
|
138
|
-
name: "tool_call",
|
139
|
-
parse: (value) => {
|
140
|
-
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
|
141
|
-
throw new Error(
|
142
|
-
'"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
|
143
|
-
);
|
144
|
-
}
|
145
|
-
return {
|
146
|
-
type: "tool_call",
|
147
|
-
value
|
148
|
-
};
|
149
|
-
}
|
150
|
-
};
|
151
|
-
var toolResultStreamPart = {
|
152
|
-
code: "a",
|
153
|
-
name: "tool_result",
|
154
|
-
parse: (value) => {
|
155
|
-
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object" || !("result" in value)) {
|
156
|
-
throw new Error(
|
157
|
-
'"tool_result" parts expect an object with a "toolCallId", "toolName", "args", and "result" property.'
|
158
|
-
);
|
159
|
-
}
|
160
|
-
return {
|
161
|
-
type: "tool_result",
|
162
|
-
value
|
163
|
-
};
|
164
|
-
}
|
165
|
-
};
|
166
|
-
var streamParts = [
|
167
|
-
textStreamPart,
|
168
|
-
functionCallStreamPart,
|
169
|
-
dataStreamPart,
|
170
|
-
errorStreamPart,
|
171
|
-
assistantMessageStreamPart,
|
172
|
-
assistantControlDataStreamPart,
|
173
|
-
dataMessageStreamPart,
|
174
|
-
toolCallsStreamPart,
|
175
|
-
messageAnnotationsStreamPart,
|
176
|
-
toolCallStreamPart,
|
177
|
-
toolResultStreamPart
|
178
|
-
];
|
179
|
-
var streamPartsByCode = {
|
180
|
-
[textStreamPart.code]: textStreamPart,
|
181
|
-
[functionCallStreamPart.code]: functionCallStreamPart,
|
182
|
-
[dataStreamPart.code]: dataStreamPart,
|
183
|
-
[errorStreamPart.code]: errorStreamPart,
|
184
|
-
[assistantMessageStreamPart.code]: assistantMessageStreamPart,
|
185
|
-
[assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
|
186
|
-
[dataMessageStreamPart.code]: dataMessageStreamPart,
|
187
|
-
[toolCallsStreamPart.code]: toolCallsStreamPart,
|
188
|
-
[messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart,
|
189
|
-
[toolCallStreamPart.code]: toolCallStreamPart,
|
190
|
-
[toolResultStreamPart.code]: toolResultStreamPart
|
191
|
-
};
|
192
|
-
var StreamStringPrefixes = {
|
193
|
-
[textStreamPart.name]: textStreamPart.code,
|
194
|
-
[functionCallStreamPart.name]: functionCallStreamPart.code,
|
195
|
-
[dataStreamPart.name]: dataStreamPart.code,
|
196
|
-
[errorStreamPart.name]: errorStreamPart.code,
|
197
|
-
[assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
|
198
|
-
[assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
|
199
|
-
[dataMessageStreamPart.name]: dataMessageStreamPart.code,
|
200
|
-
[toolCallsStreamPart.name]: toolCallsStreamPart.code,
|
201
|
-
[messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code,
|
202
|
-
[toolCallStreamPart.name]: toolCallStreamPart.code,
|
203
|
-
[toolResultStreamPart.name]: toolResultStreamPart.code
|
204
|
-
};
|
205
|
-
var validCodes = streamParts.map((part) => part.code);
|
206
|
-
var parseStreamPart = (line) => {
|
207
|
-
const firstSeparatorIndex = line.indexOf(":");
|
208
|
-
if (firstSeparatorIndex === -1) {
|
209
|
-
throw new Error("Failed to parse stream string. No separator found.");
|
210
|
-
}
|
211
|
-
const prefix = line.slice(0, firstSeparatorIndex);
|
212
|
-
if (!validCodes.includes(prefix)) {
|
213
|
-
throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
|
214
|
-
}
|
215
|
-
const code = prefix;
|
216
|
-
const textValue = line.slice(firstSeparatorIndex + 1);
|
217
|
-
const jsonValue = JSON.parse(textValue);
|
218
|
-
return streamPartsByCode[code].parse(jsonValue);
|
219
|
-
};
|
220
|
-
|
221
|
-
// shared/read-data-stream.ts
|
222
|
-
var NEWLINE = "\n".charCodeAt(0);
|
223
|
-
function concatChunks(chunks, totalLength) {
|
224
|
-
const concatenatedChunks = new Uint8Array(totalLength);
|
225
|
-
let offset = 0;
|
226
|
-
for (const chunk of chunks) {
|
227
|
-
concatenatedChunks.set(chunk, offset);
|
228
|
-
offset += chunk.length;
|
229
|
-
}
|
230
|
-
chunks.length = 0;
|
231
|
-
return concatenatedChunks;
|
232
|
-
}
|
233
|
-
async function* readDataStream(reader, {
|
234
|
-
isAborted
|
235
|
-
} = {}) {
|
236
|
-
const decoder = new TextDecoder();
|
237
|
-
const chunks = [];
|
238
|
-
let totalLength = 0;
|
239
|
-
while (true) {
|
240
|
-
const { value } = await reader.read();
|
241
|
-
if (value) {
|
242
|
-
chunks.push(value);
|
243
|
-
totalLength += value.length;
|
244
|
-
if (value[value.length - 1] !== NEWLINE) {
|
245
|
-
continue;
|
246
|
-
}
|
247
|
-
}
|
248
|
-
if (chunks.length === 0) {
|
249
|
-
break;
|
250
|
-
}
|
251
|
-
const concatenatedChunks = concatChunks(chunks, totalLength);
|
252
|
-
totalLength = 0;
|
253
|
-
const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
|
254
|
-
for (const streamPart of streamParts2) {
|
255
|
-
yield streamPart;
|
256
|
-
}
|
257
|
-
if (isAborted == null ? void 0 : isAborted()) {
|
258
|
-
reader.cancel();
|
259
|
-
break;
|
260
|
-
}
|
261
|
-
}
|
262
|
-
}
|
263
|
-
|
264
|
-
// shared/parse-complex-response.ts
|
265
|
-
function assignAnnotationsToMessage(message, annotations) {
|
266
|
-
if (!message || !annotations || !annotations.length)
|
267
|
-
return message;
|
268
|
-
return { ...message, annotations: [...annotations] };
|
269
|
-
}
|
270
|
-
async function parseComplexResponse({
|
271
|
-
reader,
|
272
|
-
abortControllerRef,
|
273
|
-
update,
|
274
|
-
onToolCall,
|
275
|
-
onFinish,
|
276
|
-
generateId: generateId2 = generateId,
|
277
|
-
getCurrentDate = () => /* @__PURE__ */ new Date()
|
278
|
-
}) {
|
279
|
-
const createdAt = getCurrentDate();
|
280
|
-
const prefixMap = {
|
281
|
-
data: []
|
282
|
-
};
|
283
|
-
let message_annotations = void 0;
|
284
|
-
for await (const { type, value } of readDataStream(reader, {
|
285
|
-
isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
|
286
|
-
})) {
|
287
|
-
if (type === "text") {
|
288
|
-
if (prefixMap["text"]) {
|
289
|
-
prefixMap["text"] = {
|
290
|
-
...prefixMap["text"],
|
291
|
-
content: (prefixMap["text"].content || "") + value
|
292
|
-
};
|
293
|
-
} else {
|
294
|
-
prefixMap["text"] = {
|
295
|
-
id: generateId2(),
|
296
|
-
role: "assistant",
|
297
|
-
content: value,
|
298
|
-
createdAt
|
299
|
-
};
|
300
|
-
}
|
301
|
-
}
|
302
|
-
if (type === "tool_call") {
|
303
|
-
if (prefixMap.text == null) {
|
304
|
-
prefixMap.text = {
|
305
|
-
id: generateId2(),
|
306
|
-
role: "assistant",
|
307
|
-
content: "",
|
308
|
-
createdAt
|
309
|
-
};
|
310
|
-
}
|
311
|
-
if (prefixMap.text.toolInvocations == null) {
|
312
|
-
prefixMap.text.toolInvocations = [];
|
313
|
-
}
|
314
|
-
prefixMap.text.toolInvocations.push(value);
|
315
|
-
if (onToolCall) {
|
316
|
-
const result = await onToolCall({ toolCall: value });
|
317
|
-
if (result != null) {
|
318
|
-
prefixMap.text.toolInvocations[prefixMap.text.toolInvocations.length - 1] = { ...value, result };
|
319
|
-
}
|
320
|
-
}
|
321
|
-
} else if (type === "tool_result") {
|
322
|
-
if (prefixMap.text == null) {
|
323
|
-
prefixMap.text = {
|
324
|
-
id: generateId2(),
|
325
|
-
role: "assistant",
|
326
|
-
content: "",
|
327
|
-
createdAt
|
328
|
-
};
|
329
|
-
}
|
330
|
-
if (prefixMap.text.toolInvocations == null) {
|
331
|
-
prefixMap.text.toolInvocations = [];
|
332
|
-
}
|
333
|
-
const toolInvocationIndex = prefixMap.text.toolInvocations.findIndex(
|
334
|
-
(invocation) => invocation.toolCallId === value.toolCallId
|
335
|
-
);
|
336
|
-
if (toolInvocationIndex !== -1) {
|
337
|
-
prefixMap.text.toolInvocations[toolInvocationIndex] = value;
|
338
|
-
} else {
|
339
|
-
prefixMap.text.toolInvocations.push(value);
|
340
|
-
}
|
341
|
-
}
|
342
|
-
let functionCallMessage = null;
|
343
|
-
if (type === "function_call") {
|
344
|
-
prefixMap["function_call"] = {
|
345
|
-
id: generateId2(),
|
346
|
-
role: "assistant",
|
347
|
-
content: "",
|
348
|
-
function_call: value.function_call,
|
349
|
-
name: value.function_call.name,
|
350
|
-
createdAt
|
351
|
-
};
|
352
|
-
functionCallMessage = prefixMap["function_call"];
|
353
|
-
}
|
354
|
-
let toolCallMessage = null;
|
355
|
-
if (type === "tool_calls") {
|
356
|
-
prefixMap["tool_calls"] = {
|
357
|
-
id: generateId2(),
|
358
|
-
role: "assistant",
|
359
|
-
content: "",
|
360
|
-
tool_calls: value.tool_calls,
|
361
|
-
createdAt
|
362
|
-
};
|
363
|
-
toolCallMessage = prefixMap["tool_calls"];
|
364
|
-
}
|
365
|
-
if (type === "data") {
|
366
|
-
prefixMap["data"].push(...value);
|
367
|
-
}
|
368
|
-
let responseMessage = prefixMap["text"];
|
369
|
-
if (type === "message_annotations") {
|
370
|
-
if (!message_annotations) {
|
371
|
-
message_annotations = [...value];
|
372
|
-
} else {
|
373
|
-
message_annotations.push(...value);
|
374
|
-
}
|
375
|
-
functionCallMessage = assignAnnotationsToMessage(
|
376
|
-
prefixMap["function_call"],
|
377
|
-
message_annotations
|
378
|
-
);
|
379
|
-
toolCallMessage = assignAnnotationsToMessage(
|
380
|
-
prefixMap["tool_calls"],
|
381
|
-
message_annotations
|
382
|
-
);
|
383
|
-
responseMessage = assignAnnotationsToMessage(
|
384
|
-
prefixMap["text"],
|
385
|
-
message_annotations
|
386
|
-
);
|
387
|
-
}
|
388
|
-
if (message_annotations == null ? void 0 : message_annotations.length) {
|
389
|
-
const messagePrefixKeys = [
|
390
|
-
"text",
|
391
|
-
"function_call",
|
392
|
-
"tool_calls"
|
393
|
-
];
|
394
|
-
messagePrefixKeys.forEach((key) => {
|
395
|
-
if (prefixMap[key]) {
|
396
|
-
prefixMap[key].annotations = [...message_annotations];
|
397
|
-
}
|
398
|
-
});
|
399
|
-
}
|
400
|
-
const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
|
401
|
-
...assignAnnotationsToMessage(message, message_annotations)
|
402
|
-
}));
|
403
|
-
update(merged, [...prefixMap["data"]]);
|
404
|
-
}
|
405
|
-
onFinish == null ? void 0 : onFinish(prefixMap);
|
406
|
-
return {
|
407
|
-
messages: [
|
408
|
-
prefixMap.text,
|
409
|
-
prefixMap.function_call,
|
410
|
-
prefixMap.tool_calls
|
411
|
-
].filter(Boolean),
|
412
|
-
data: prefixMap.data
|
413
|
-
};
|
414
|
-
}
|
415
|
-
|
416
|
-
// shared/utils.ts
|
417
|
-
function createChunkDecoder(complex) {
|
418
|
-
const decoder = new TextDecoder();
|
419
|
-
if (!complex) {
|
420
|
-
return function(chunk) {
|
421
|
-
if (!chunk)
|
422
|
-
return "";
|
423
|
-
return decoder.decode(chunk, { stream: true });
|
424
|
-
};
|
425
|
-
}
|
426
|
-
return function(chunk) {
|
427
|
-
const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
|
428
|
-
return decoded.map(parseStreamPart).filter(Boolean);
|
429
|
-
};
|
430
|
-
}
|
431
|
-
|
432
|
-
// shared/call-chat-api.ts
|
433
|
-
async function callChatApi({
|
434
|
-
api,
|
435
|
-
messages,
|
436
|
-
body,
|
437
|
-
streamMode = "stream-data",
|
438
|
-
credentials,
|
439
|
-
headers,
|
440
|
-
abortController,
|
441
|
-
restoreMessagesOnFailure,
|
442
|
-
onResponse,
|
443
|
-
onUpdate,
|
444
|
-
onFinish,
|
445
|
-
onToolCall,
|
446
|
-
generateId: generateId2
|
447
|
-
}) {
|
448
|
-
var _a;
|
449
|
-
const response = await fetch(api, {
|
450
|
-
method: "POST",
|
451
|
-
body: JSON.stringify({
|
452
|
-
messages,
|
453
|
-
...body
|
454
|
-
}),
|
455
|
-
headers: {
|
456
|
-
"Content-Type": "application/json",
|
457
|
-
...headers
|
458
|
-
},
|
459
|
-
signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
|
460
|
-
credentials
|
461
|
-
}).catch((err) => {
|
462
|
-
restoreMessagesOnFailure();
|
463
|
-
throw err;
|
464
|
-
});
|
465
|
-
if (onResponse) {
|
466
|
-
try {
|
467
|
-
await onResponse(response);
|
468
|
-
} catch (err) {
|
469
|
-
throw err;
|
470
|
-
}
|
471
|
-
}
|
472
|
-
if (!response.ok) {
|
473
|
-
restoreMessagesOnFailure();
|
474
|
-
throw new Error(
|
475
|
-
await response.text() || "Failed to fetch the chat response."
|
476
|
-
);
|
477
|
-
}
|
478
|
-
if (!response.body) {
|
479
|
-
throw new Error("The response body is empty.");
|
480
|
-
}
|
481
|
-
const reader = response.body.getReader();
|
482
|
-
switch (streamMode) {
|
483
|
-
case "text": {
|
484
|
-
const decoder = createChunkDecoder();
|
485
|
-
const resultMessage = {
|
486
|
-
id: generateId2(),
|
487
|
-
createdAt: /* @__PURE__ */ new Date(),
|
488
|
-
role: "assistant",
|
489
|
-
content: ""
|
490
|
-
};
|
491
|
-
while (true) {
|
492
|
-
const { done, value } = await reader.read();
|
493
|
-
if (done) {
|
494
|
-
break;
|
495
|
-
}
|
496
|
-
resultMessage.content += decoder(value);
|
497
|
-
resultMessage.id = generateId2();
|
498
|
-
onUpdate([{ ...resultMessage }], []);
|
499
|
-
if ((abortController == null ? void 0 : abortController()) === null) {
|
500
|
-
reader.cancel();
|
501
|
-
break;
|
502
|
-
}
|
503
|
-
}
|
504
|
-
onFinish == null ? void 0 : onFinish(resultMessage);
|
505
|
-
return {
|
506
|
-
messages: [resultMessage],
|
507
|
-
data: []
|
508
|
-
};
|
509
|
-
}
|
510
|
-
case "stream-data": {
|
511
|
-
return await parseComplexResponse({
|
512
|
-
reader,
|
513
|
-
abortControllerRef: abortController != null ? { current: abortController() } : void 0,
|
514
|
-
update: onUpdate,
|
515
|
-
onToolCall,
|
516
|
-
onFinish(prefixMap) {
|
517
|
-
if (onFinish && prefixMap.text != null) {
|
518
|
-
onFinish(prefixMap.text);
|
519
|
-
}
|
520
|
-
},
|
521
|
-
generateId: generateId2
|
522
|
-
});
|
523
|
-
}
|
524
|
-
default: {
|
525
|
-
const exhaustiveCheck = streamMode;
|
526
|
-
throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
|
527
|
-
}
|
528
|
-
}
|
529
|
-
}
|
530
|
-
|
531
|
-
// shared/process-chat-stream.ts
|
532
|
-
async function processChatStream({
|
533
|
-
getStreamedResponse,
|
534
|
-
experimental_onFunctionCall,
|
535
|
-
experimental_onToolCall,
|
536
|
-
updateChatRequest,
|
537
|
-
getCurrentMessages
|
538
|
-
}) {
|
539
|
-
while (true) {
|
540
|
-
const messagesAndDataOrJustMessage = await getStreamedResponse();
|
541
|
-
if ("messages" in messagesAndDataOrJustMessage) {
|
542
|
-
let hasFollowingResponse = false;
|
543
|
-
for (const message of messagesAndDataOrJustMessage.messages) {
|
544
|
-
if ((message.function_call === void 0 || typeof message.function_call === "string") && (message.tool_calls === void 0 || typeof message.tool_calls === "string")) {
|
545
|
-
continue;
|
546
|
-
}
|
547
|
-
hasFollowingResponse = true;
|
548
|
-
if (experimental_onFunctionCall) {
|
549
|
-
const functionCall = message.function_call;
|
550
|
-
if (typeof functionCall !== "object") {
|
551
|
-
console.warn(
|
552
|
-
"experimental_onFunctionCall should not be defined when using tools"
|
553
|
-
);
|
554
|
-
continue;
|
555
|
-
}
|
556
|
-
const functionCallResponse = await experimental_onFunctionCall(
|
557
|
-
getCurrentMessages(),
|
558
|
-
functionCall
|
559
|
-
);
|
560
|
-
if (functionCallResponse === void 0) {
|
561
|
-
hasFollowingResponse = false;
|
562
|
-
break;
|
563
|
-
}
|
564
|
-
updateChatRequest(functionCallResponse);
|
565
|
-
}
|
566
|
-
if (experimental_onToolCall) {
|
567
|
-
const toolCalls = message.tool_calls;
|
568
|
-
if (!Array.isArray(toolCalls) || toolCalls.some((toolCall) => typeof toolCall !== "object")) {
|
569
|
-
console.warn(
|
570
|
-
"experimental_onToolCall should not be defined when using tools"
|
571
|
-
);
|
572
|
-
continue;
|
573
|
-
}
|
574
|
-
const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
|
575
|
-
if (toolCallResponse === void 0) {
|
576
|
-
hasFollowingResponse = false;
|
577
|
-
break;
|
578
|
-
}
|
579
|
-
updateChatRequest(toolCallResponse);
|
580
|
-
}
|
581
|
-
}
|
582
|
-
if (!hasFollowingResponse) {
|
583
|
-
break;
|
584
|
-
}
|
585
|
-
} else {
|
586
|
-
let fixFunctionCallArguments2 = function(response) {
|
587
|
-
for (const message of response.messages) {
|
588
|
-
if (message.tool_calls !== void 0) {
|
589
|
-
for (const toolCall of message.tool_calls) {
|
590
|
-
if (typeof toolCall === "object") {
|
591
|
-
if (toolCall.function.arguments && typeof toolCall.function.arguments !== "string") {
|
592
|
-
toolCall.function.arguments = JSON.stringify(
|
593
|
-
toolCall.function.arguments
|
594
|
-
);
|
595
|
-
}
|
596
|
-
}
|
597
|
-
}
|
598
|
-
}
|
599
|
-
if (message.function_call !== void 0) {
|
600
|
-
if (typeof message.function_call === "object") {
|
601
|
-
if (message.function_call.arguments && typeof message.function_call.arguments !== "string") {
|
602
|
-
message.function_call.arguments = JSON.stringify(
|
603
|
-
message.function_call.arguments
|
604
|
-
);
|
605
|
-
}
|
606
|
-
}
|
607
|
-
}
|
608
|
-
}
|
609
|
-
};
|
610
|
-
var fixFunctionCallArguments = fixFunctionCallArguments2;
|
611
|
-
const streamedResponseMessage = messagesAndDataOrJustMessage;
|
612
|
-
if ((streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") && (streamedResponseMessage.tool_calls === void 0 || typeof streamedResponseMessage.tool_calls === "string")) {
|
613
|
-
break;
|
614
|
-
}
|
615
|
-
if (experimental_onFunctionCall) {
|
616
|
-
const functionCall = streamedResponseMessage.function_call;
|
617
|
-
if (!(typeof functionCall === "object")) {
|
618
|
-
console.warn(
|
619
|
-
"experimental_onFunctionCall should not be defined when using tools"
|
620
|
-
);
|
621
|
-
continue;
|
622
|
-
}
|
623
|
-
const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
|
624
|
-
if (functionCallResponse === void 0)
|
625
|
-
break;
|
626
|
-
fixFunctionCallArguments2(functionCallResponse);
|
627
|
-
updateChatRequest(functionCallResponse);
|
628
|
-
}
|
629
|
-
if (experimental_onToolCall) {
|
630
|
-
const toolCalls = streamedResponseMessage.tool_calls;
|
631
|
-
if (!(typeof toolCalls === "object")) {
|
632
|
-
console.warn(
|
633
|
-
"experimental_onToolCall should not be defined when using functions"
|
634
|
-
);
|
635
|
-
continue;
|
636
|
-
}
|
637
|
-
const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
|
638
|
-
if (toolCallResponse === void 0)
|
639
|
-
break;
|
640
|
-
fixFunctionCallArguments2(toolCallResponse);
|
641
|
-
updateChatRequest(toolCallResponse);
|
642
|
-
}
|
643
|
-
}
|
644
|
-
}
|
645
|
-
}
|
646
|
-
|
647
|
-
// solid/use-chat.ts
|
648
|
-
var uniqueId = 0;
|
649
|
-
var store = {};
|
650
|
-
var chatApiStore = createSWRStore({
|
651
|
-
get: async (key) => {
|
652
|
-
var _a;
|
653
|
-
return (_a = store[key]) != null ? _a : [];
|
654
|
-
}
|
655
|
-
});
|
656
|
-
function useChat({
|
657
|
-
api = "/api/chat",
|
658
|
-
id,
|
659
|
-
initialMessages = [],
|
660
|
-
initialInput = "",
|
661
|
-
sendExtraMessageFields,
|
662
|
-
experimental_onFunctionCall,
|
663
|
-
onResponse,
|
664
|
-
onFinish,
|
665
|
-
onError,
|
666
|
-
credentials,
|
667
|
-
headers,
|
668
|
-
body,
|
669
|
-
streamMode,
|
670
|
-
generateId: generateId2 = generateId
|
671
|
-
} = {}) {
|
672
|
-
const chatId = id || `chat-${uniqueId++}`;
|
673
|
-
const key = `${api}|${chatId}`;
|
674
|
-
const messages = useSWRStore(chatApiStore, () => [key], {
|
675
|
-
initialData: initialMessages
|
676
|
-
});
|
677
|
-
const mutate = (data) => {
|
678
|
-
store[key] = data;
|
679
|
-
return chatApiStore.mutate([key], {
|
680
|
-
status: "success",
|
681
|
-
data
|
682
|
-
});
|
683
|
-
};
|
684
|
-
const [error, setError] = createSignal(void 0);
|
685
|
-
const [streamData, setStreamData] = createSignal(
|
686
|
-
void 0
|
687
|
-
);
|
688
|
-
const [isLoading, setIsLoading] = createSignal(false);
|
689
|
-
let abortController = null;
|
690
|
-
async function triggerRequest(messagesSnapshot, { options, data } = {}) {
|
691
|
-
try {
|
692
|
-
setError(void 0);
|
693
|
-
setIsLoading(true);
|
694
|
-
abortController = new AbortController();
|
695
|
-
const getCurrentMessages = () => chatApiStore.get([key], {
|
696
|
-
shouldRevalidate: false
|
697
|
-
});
|
698
|
-
const previousMessages = getCurrentMessages();
|
699
|
-
mutate(messagesSnapshot);
|
700
|
-
let chatRequest = {
|
701
|
-
messages: messagesSnapshot,
|
702
|
-
options,
|
703
|
-
data
|
704
|
-
};
|
705
|
-
await processChatStream({
|
706
|
-
getStreamedResponse: async () => {
|
707
|
-
var _a;
|
708
|
-
const existingData = (_a = streamData()) != null ? _a : [];
|
709
|
-
return await callChatApi({
|
710
|
-
api,
|
711
|
-
messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
|
712
|
-
({
|
713
|
-
role,
|
714
|
-
content,
|
715
|
-
name,
|
716
|
-
data: data2,
|
717
|
-
annotations,
|
718
|
-
function_call
|
719
|
-
}) => ({
|
720
|
-
role,
|
721
|
-
content,
|
722
|
-
...name !== void 0 && { name },
|
723
|
-
...data2 !== void 0 && { data: data2 },
|
724
|
-
...annotations !== void 0 && { annotations },
|
725
|
-
// outdated function/tool call handling (TODO deprecate):
|
726
|
-
...function_call !== void 0 && { function_call }
|
727
|
-
})
|
728
|
-
),
|
729
|
-
body: {
|
730
|
-
data: chatRequest.data,
|
731
|
-
...body,
|
732
|
-
...options == null ? void 0 : options.body
|
733
|
-
},
|
734
|
-
streamMode,
|
735
|
-
headers: {
|
736
|
-
...headers,
|
737
|
-
...options == null ? void 0 : options.headers
|
738
|
-
},
|
739
|
-
abortController: () => abortController,
|
740
|
-
credentials,
|
741
|
-
onResponse,
|
742
|
-
onUpdate(merged, data2) {
|
743
|
-
mutate([...chatRequest.messages, ...merged]);
|
744
|
-
setStreamData([...existingData, ...data2 != null ? data2 : []]);
|
745
|
-
},
|
746
|
-
onFinish,
|
747
|
-
restoreMessagesOnFailure() {
|
748
|
-
if (previousMessages.status === "success") {
|
749
|
-
mutate(previousMessages.data);
|
750
|
-
}
|
751
|
-
},
|
752
|
-
generateId: generateId2
|
753
|
-
});
|
754
|
-
},
|
755
|
-
experimental_onFunctionCall,
|
756
|
-
updateChatRequest(newChatRequest) {
|
757
|
-
chatRequest = newChatRequest;
|
758
|
-
},
|
759
|
-
getCurrentMessages: () => getCurrentMessages().data
|
760
|
-
});
|
761
|
-
abortController = null;
|
762
|
-
} catch (err) {
|
763
|
-
if (err.name === "AbortError") {
|
764
|
-
abortController = null;
|
765
|
-
return null;
|
766
|
-
}
|
767
|
-
if (onError && err instanceof Error) {
|
768
|
-
onError(err);
|
769
|
-
}
|
770
|
-
setError(err);
|
771
|
-
} finally {
|
772
|
-
setIsLoading(false);
|
773
|
-
}
|
774
|
-
}
|
775
|
-
const append = async (message, options) => {
|
776
|
-
var _a;
|
777
|
-
if (!message.id) {
|
778
|
-
message.id = generateId2();
|
779
|
-
}
|
780
|
-
return triggerRequest(
|
781
|
-
((_a = messages()) != null ? _a : []).concat(message),
|
782
|
-
options
|
783
|
-
);
|
784
|
-
};
|
785
|
-
const reload = async (options) => {
|
786
|
-
const messagesSnapshot = messages();
|
787
|
-
if (!messagesSnapshot || messagesSnapshot.length === 0)
|
788
|
-
return null;
|
789
|
-
const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
|
790
|
-
if (lastMessage.role === "assistant") {
|
791
|
-
return triggerRequest(messagesSnapshot.slice(0, -1), options);
|
792
|
-
}
|
793
|
-
return triggerRequest(messagesSnapshot, options);
|
794
|
-
};
|
795
|
-
const stop = () => {
|
796
|
-
if (abortController) {
|
797
|
-
abortController.abort();
|
798
|
-
abortController = null;
|
799
|
-
}
|
800
|
-
};
|
801
|
-
const setMessages = (messages2) => {
|
802
|
-
mutate(messages2);
|
803
|
-
};
|
804
|
-
const [input, setInput] = createSignal(initialInput);
|
805
|
-
const handleSubmit = (e, options = {}) => {
|
806
|
-
e.preventDefault();
|
807
|
-
const inputValue = input();
|
808
|
-
if (!inputValue)
|
809
|
-
return;
|
810
|
-
append(
|
811
|
-
{
|
812
|
-
content: inputValue,
|
813
|
-
role: "user",
|
814
|
-
createdAt: /* @__PURE__ */ new Date()
|
815
|
-
},
|
816
|
-
options
|
817
|
-
);
|
818
|
-
setInput("");
|
819
|
-
};
|
820
|
-
return {
|
821
|
-
messages,
|
822
|
-
append,
|
823
|
-
error,
|
824
|
-
reload,
|
825
|
-
stop,
|
826
|
-
setMessages,
|
827
|
-
input,
|
828
|
-
setInput,
|
829
|
-
handleSubmit,
|
830
|
-
isLoading,
|
831
|
-
data: streamData
|
832
|
-
};
|
833
|
-
}
|
834
|
-
|
835
|
-
// solid/use-completion.ts
|
836
|
-
import { createSignal as createSignal2 } from "solid-js";
|
837
|
-
import { useSWRStore as useSWRStore2 } from "solid-swr-store";
|
838
|
-
import { createSWRStore as createSWRStore2 } from "swr-store";
|
839
|
-
|
840
|
-
// shared/call-completion-api.ts
|
841
|
-
async function callCompletionApi({
|
842
|
-
api,
|
843
|
-
prompt,
|
844
|
-
credentials,
|
845
|
-
headers,
|
846
|
-
body,
|
847
|
-
streamMode = "stream-data",
|
848
|
-
setCompletion,
|
849
|
-
setLoading,
|
850
|
-
setError,
|
851
|
-
setAbortController,
|
852
|
-
onResponse,
|
853
|
-
onFinish,
|
854
|
-
onError,
|
855
|
-
onData
|
856
|
-
}) {
|
857
|
-
try {
|
858
|
-
setLoading(true);
|
859
|
-
setError(void 0);
|
860
|
-
const abortController = new AbortController();
|
861
|
-
setAbortController(abortController);
|
862
|
-
setCompletion("");
|
863
|
-
const res = await fetch(api, {
|
864
|
-
method: "POST",
|
865
|
-
body: JSON.stringify({
|
866
|
-
prompt,
|
867
|
-
...body
|
868
|
-
}),
|
869
|
-
credentials,
|
870
|
-
headers: {
|
871
|
-
"Content-Type": "application/json",
|
872
|
-
...headers
|
873
|
-
},
|
874
|
-
signal: abortController.signal
|
875
|
-
}).catch((err) => {
|
876
|
-
throw err;
|
877
|
-
});
|
878
|
-
if (onResponse) {
|
879
|
-
try {
|
880
|
-
await onResponse(res);
|
881
|
-
} catch (err) {
|
882
|
-
throw err;
|
883
|
-
}
|
884
|
-
}
|
885
|
-
if (!res.ok) {
|
886
|
-
throw new Error(
|
887
|
-
await res.text() || "Failed to fetch the chat response."
|
888
|
-
);
|
889
|
-
}
|
890
|
-
if (!res.body) {
|
891
|
-
throw new Error("The response body is empty.");
|
892
|
-
}
|
893
|
-
let result = "";
|
894
|
-
const reader = res.body.getReader();
|
895
|
-
switch (streamMode) {
|
896
|
-
case "text": {
|
897
|
-
const decoder = createChunkDecoder();
|
898
|
-
while (true) {
|
899
|
-
const { done, value } = await reader.read();
|
900
|
-
if (done) {
|
901
|
-
break;
|
902
|
-
}
|
903
|
-
result += decoder(value);
|
904
|
-
setCompletion(result);
|
905
|
-
if (abortController === null) {
|
906
|
-
reader.cancel();
|
907
|
-
break;
|
908
|
-
}
|
909
|
-
}
|
910
|
-
break;
|
911
|
-
}
|
912
|
-
case "stream-data": {
|
913
|
-
for await (const { type, value } of readDataStream(reader, {
|
914
|
-
isAborted: () => abortController === null
|
915
|
-
})) {
|
916
|
-
switch (type) {
|
917
|
-
case "text": {
|
918
|
-
result += value;
|
919
|
-
setCompletion(result);
|
920
|
-
break;
|
921
|
-
}
|
922
|
-
case "data": {
|
923
|
-
onData == null ? void 0 : onData(value);
|
924
|
-
break;
|
925
|
-
}
|
926
|
-
}
|
927
|
-
}
|
928
|
-
break;
|
929
|
-
}
|
930
|
-
default: {
|
931
|
-
const exhaustiveCheck = streamMode;
|
932
|
-
throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
|
933
|
-
}
|
934
|
-
}
|
935
|
-
if (onFinish) {
|
936
|
-
onFinish(prompt, result);
|
937
|
-
}
|
938
|
-
setAbortController(null);
|
939
|
-
return result;
|
940
|
-
} catch (err) {
|
941
|
-
if (err.name === "AbortError") {
|
942
|
-
setAbortController(null);
|
943
|
-
return null;
|
944
|
-
}
|
945
|
-
if (err instanceof Error) {
|
946
|
-
if (onError) {
|
947
|
-
onError(err);
|
948
|
-
}
|
949
|
-
}
|
950
|
-
setError(err);
|
951
|
-
} finally {
|
952
|
-
setLoading(false);
|
953
|
-
}
|
954
|
-
}
|
955
|
-
|
956
|
-
// solid/use-completion.ts
|
957
|
-
var uniqueId2 = 0;
|
958
|
-
var store2 = {};
|
959
|
-
var completionApiStore = createSWRStore2({
|
960
|
-
get: async (key) => {
|
961
|
-
var _a;
|
962
|
-
return (_a = store2[key]) != null ? _a : [];
|
963
|
-
}
|
964
|
-
});
|
965
|
-
function useCompletion({
|
966
|
-
api = "/api/completion",
|
967
|
-
id,
|
968
|
-
initialCompletion = "",
|
969
|
-
initialInput = "",
|
970
|
-
credentials,
|
971
|
-
headers,
|
972
|
-
body,
|
973
|
-
streamMode,
|
974
|
-
onResponse,
|
975
|
-
onFinish,
|
976
|
-
onError
|
977
|
-
} = {}) {
|
978
|
-
const completionId = id || `completion-${uniqueId2++}`;
|
979
|
-
const key = `${api}|${completionId}`;
|
980
|
-
const data = useSWRStore2(completionApiStore, () => [key], {
|
981
|
-
initialData: initialCompletion
|
982
|
-
});
|
983
|
-
const mutate = (data2) => {
|
984
|
-
store2[key] = data2;
|
985
|
-
return completionApiStore.mutate([key], {
|
986
|
-
data: data2,
|
987
|
-
status: "success"
|
988
|
-
});
|
989
|
-
};
|
990
|
-
const completion = data;
|
991
|
-
const [error, setError] = createSignal2(void 0);
|
992
|
-
const [streamData, setStreamData] = createSignal2(
|
993
|
-
void 0
|
994
|
-
);
|
995
|
-
const [isLoading, setIsLoading] = createSignal2(false);
|
996
|
-
let abortController = null;
|
997
|
-
const complete = async (prompt, options) => {
|
998
|
-
var _a;
|
999
|
-
const existingData = (_a = streamData()) != null ? _a : [];
|
1000
|
-
return callCompletionApi({
|
1001
|
-
api,
|
1002
|
-
prompt,
|
1003
|
-
credentials,
|
1004
|
-
headers: {
|
1005
|
-
...headers,
|
1006
|
-
...options == null ? void 0 : options.headers
|
1007
|
-
},
|
1008
|
-
body: {
|
1009
|
-
...body,
|
1010
|
-
...options == null ? void 0 : options.body
|
1011
|
-
},
|
1012
|
-
streamMode,
|
1013
|
-
setCompletion: mutate,
|
1014
|
-
setLoading: setIsLoading,
|
1015
|
-
setError,
|
1016
|
-
setAbortController: (controller) => {
|
1017
|
-
abortController = controller;
|
1018
|
-
},
|
1019
|
-
onResponse,
|
1020
|
-
onFinish,
|
1021
|
-
onError,
|
1022
|
-
onData: (data2) => {
|
1023
|
-
setStreamData([...existingData, ...data2 != null ? data2 : []]);
|
1024
|
-
}
|
1025
|
-
});
|
1026
|
-
};
|
1027
|
-
const stop = () => {
|
1028
|
-
if (abortController) {
|
1029
|
-
abortController.abort();
|
1030
|
-
abortController = null;
|
1031
|
-
}
|
1032
|
-
};
|
1033
|
-
const setCompletion = (completion2) => {
|
1034
|
-
mutate(completion2);
|
1035
|
-
};
|
1036
|
-
const [input, setInput] = createSignal2(initialInput);
|
1037
|
-
const handleSubmit = (e) => {
|
1038
|
-
e.preventDefault();
|
1039
|
-
const inputValue = input();
|
1040
|
-
if (!inputValue)
|
1041
|
-
return;
|
1042
|
-
return complete(inputValue);
|
1043
|
-
};
|
1044
|
-
return {
|
1045
|
-
completion,
|
1046
|
-
complete,
|
1047
|
-
error,
|
1048
|
-
stop,
|
1049
|
-
setCompletion,
|
1050
|
-
input,
|
1051
|
-
setInput,
|
1052
|
-
handleSubmit,
|
1053
|
-
isLoading,
|
1054
|
-
data: streamData
|
1055
|
-
};
|
1056
|
-
}
|
1
|
+
// solid/index.ts
|
2
|
+
import {
|
3
|
+
useChat as useChatSolid,
|
4
|
+
useCompletion as useCompletionSolid
|
5
|
+
} from "@ai-sdk/solid";
|
6
|
+
var useChat = useChatSolid;
|
7
|
+
var useCompletion = useCompletionSolid;
|
1057
8
|
export {
|
1058
9
|
useChat,
|
1059
10
|
useCompletion
|