ai 0.0.0-e27b4ed4-20240419203611

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