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