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