ai 0.0.0-85f9a635-20240518005312 → 0.0.0-9477ebb9-20250403064906

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 (70) hide show
  1. package/CHANGELOG.md +3521 -0
  2. package/README.md +112 -22
  3. package/dist/index.d.mts +3697 -1642
  4. package/dist/index.d.ts +3697 -1642
  5. package/dist/index.js +7201 -2942
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7249 -2963
  8. package/dist/index.mjs.map +1 -1
  9. package/mcp-stdio/create-child-process.test.ts +92 -0
  10. package/mcp-stdio/create-child-process.ts +21 -0
  11. package/mcp-stdio/dist/index.d.mts +169 -0
  12. package/mcp-stdio/dist/index.d.ts +169 -0
  13. package/mcp-stdio/dist/index.js +352 -0
  14. package/mcp-stdio/dist/index.js.map +1 -0
  15. package/mcp-stdio/dist/index.mjs +337 -0
  16. package/mcp-stdio/dist/index.mjs.map +1 -0
  17. package/mcp-stdio/get-environment.ts +43 -0
  18. package/mcp-stdio/index.ts +4 -0
  19. package/mcp-stdio/mcp-stdio-transport.test.ts +262 -0
  20. package/mcp-stdio/mcp-stdio-transport.ts +157 -0
  21. package/package.json +46 -103
  22. package/react/dist/index.d.mts +10 -557
  23. package/react/dist/index.d.ts +10 -574
  24. package/react/dist/index.js +6 -1397
  25. package/react/dist/index.js.map +1 -1
  26. package/react/dist/index.mjs +10 -1384
  27. package/react/dist/index.mjs.map +1 -1
  28. package/rsc/dist/index.d.ts +432 -199
  29. package/rsc/dist/rsc-server.d.mts +431 -199
  30. package/rsc/dist/rsc-server.mjs +1599 -1357
  31. package/rsc/dist/rsc-server.mjs.map +1 -1
  32. package/rsc/dist/rsc-shared.d.mts +30 -23
  33. package/rsc/dist/rsc-shared.mjs +70 -108
  34. package/rsc/dist/rsc-shared.mjs.map +1 -1
  35. package/test/dist/index.d.mts +65 -0
  36. package/test/dist/index.d.ts +65 -0
  37. package/test/dist/index.js +121 -0
  38. package/test/dist/index.js.map +1 -0
  39. package/test/dist/index.mjs +94 -0
  40. package/test/dist/index.mjs.map +1 -0
  41. package/prompts/dist/index.d.mts +0 -324
  42. package/prompts/dist/index.d.ts +0 -324
  43. package/prompts/dist/index.js +0 -178
  44. package/prompts/dist/index.js.map +0 -1
  45. package/prompts/dist/index.mjs +0 -146
  46. package/prompts/dist/index.mjs.map +0 -1
  47. package/react/dist/index.server.d.mts +0 -17
  48. package/react/dist/index.server.d.ts +0 -17
  49. package/react/dist/index.server.js +0 -50
  50. package/react/dist/index.server.js.map +0 -1
  51. package/react/dist/index.server.mjs +0 -23
  52. package/react/dist/index.server.mjs.map +0 -1
  53. package/solid/dist/index.d.mts +0 -408
  54. package/solid/dist/index.d.ts +0 -408
  55. package/solid/dist/index.js +0 -1072
  56. package/solid/dist/index.js.map +0 -1
  57. package/solid/dist/index.mjs +0 -1044
  58. package/solid/dist/index.mjs.map +0 -1
  59. package/svelte/dist/index.d.mts +0 -484
  60. package/svelte/dist/index.d.ts +0 -484
  61. package/svelte/dist/index.js +0 -1778
  62. package/svelte/dist/index.js.map +0 -1
  63. package/svelte/dist/index.mjs +0 -1749
  64. package/svelte/dist/index.mjs.map +0 -1
  65. package/vue/dist/index.d.mts +0 -402
  66. package/vue/dist/index.d.ts +0 -402
  67. package/vue/dist/index.js +0 -1072
  68. package/vue/dist/index.js.map +0 -1
  69. package/vue/dist/index.mjs +0 -1034
  70. package/vue/dist/index.mjs.map +0 -1
package/vue/dist/index.js DELETED
@@ -1,1072 +0,0 @@
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/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
- onFinish,
311
- generateId: generateId2 = generateId,
312
- getCurrentDate = () => /* @__PURE__ */ new Date()
313
- }) {
314
- const createdAt = getCurrentDate();
315
- const prefixMap = {
316
- data: []
317
- };
318
- let message_annotations = void 0;
319
- for await (const { type, value } of readDataStream(reader, {
320
- isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
321
- })) {
322
- if (type === "text") {
323
- if (prefixMap["text"]) {
324
- prefixMap["text"] = {
325
- ...prefixMap["text"],
326
- content: (prefixMap["text"].content || "") + value
327
- };
328
- } else {
329
- prefixMap["text"] = {
330
- id: generateId2(),
331
- role: "assistant",
332
- content: value,
333
- createdAt
334
- };
335
- }
336
- }
337
- if (type === "tool_call") {
338
- if (prefixMap.text == null) {
339
- prefixMap.text = {
340
- id: generateId2(),
341
- role: "assistant",
342
- content: "",
343
- createdAt
344
- };
345
- }
346
- if (prefixMap.text.toolInvocations == null) {
347
- prefixMap.text.toolInvocations = [];
348
- }
349
- prefixMap.text.toolInvocations.push(value);
350
- } else if (type === "tool_result") {
351
- if (prefixMap.text == null) {
352
- prefixMap.text = {
353
- id: generateId2(),
354
- role: "assistant",
355
- content: "",
356
- createdAt
357
- };
358
- }
359
- if (prefixMap.text.toolInvocations == null) {
360
- prefixMap.text.toolInvocations = [];
361
- }
362
- const toolInvocationIndex = prefixMap.text.toolInvocations.findIndex(
363
- (invocation) => invocation.toolCallId === value.toolCallId
364
- );
365
- if (toolInvocationIndex !== -1) {
366
- prefixMap.text.toolInvocations[toolInvocationIndex] = value;
367
- } else {
368
- prefixMap.text.toolInvocations.push(value);
369
- }
370
- }
371
- let functionCallMessage = null;
372
- if (type === "function_call") {
373
- prefixMap["function_call"] = {
374
- id: generateId2(),
375
- role: "assistant",
376
- content: "",
377
- function_call: value.function_call,
378
- name: value.function_call.name,
379
- createdAt
380
- };
381
- functionCallMessage = prefixMap["function_call"];
382
- }
383
- let toolCallMessage = null;
384
- if (type === "tool_calls") {
385
- prefixMap["tool_calls"] = {
386
- id: generateId2(),
387
- role: "assistant",
388
- content: "",
389
- tool_calls: value.tool_calls,
390
- createdAt
391
- };
392
- toolCallMessage = prefixMap["tool_calls"];
393
- }
394
- if (type === "data") {
395
- prefixMap["data"].push(...value);
396
- }
397
- let responseMessage = prefixMap["text"];
398
- if (type === "message_annotations") {
399
- if (!message_annotations) {
400
- message_annotations = [...value];
401
- } else {
402
- message_annotations.push(...value);
403
- }
404
- functionCallMessage = assignAnnotationsToMessage(
405
- prefixMap["function_call"],
406
- message_annotations
407
- );
408
- toolCallMessage = assignAnnotationsToMessage(
409
- prefixMap["tool_calls"],
410
- message_annotations
411
- );
412
- responseMessage = assignAnnotationsToMessage(
413
- prefixMap["text"],
414
- message_annotations
415
- );
416
- }
417
- if (message_annotations == null ? void 0 : message_annotations.length) {
418
- const messagePrefixKeys = [
419
- "text",
420
- "function_call",
421
- "tool_calls"
422
- ];
423
- messagePrefixKeys.forEach((key) => {
424
- if (prefixMap[key]) {
425
- prefixMap[key].annotations = [...message_annotations];
426
- }
427
- });
428
- }
429
- const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
430
- ...assignAnnotationsToMessage(message, message_annotations)
431
- }));
432
- update(merged, [...prefixMap["data"]]);
433
- }
434
- onFinish == null ? void 0 : onFinish(prefixMap);
435
- return {
436
- messages: [
437
- prefixMap.text,
438
- prefixMap.function_call,
439
- prefixMap.tool_calls
440
- ].filter(Boolean),
441
- data: prefixMap.data
442
- };
443
- }
444
-
445
- // shared/utils.ts
446
- function createChunkDecoder(complex) {
447
- const decoder = new TextDecoder();
448
- if (!complex) {
449
- return function(chunk) {
450
- if (!chunk)
451
- return "";
452
- return decoder.decode(chunk, { stream: true });
453
- };
454
- }
455
- return function(chunk) {
456
- const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
457
- return decoded.map(parseStreamPart).filter(Boolean);
458
- };
459
- }
460
-
461
- // shared/call-chat-api.ts
462
- async function callChatApi({
463
- api,
464
- messages,
465
- body,
466
- streamMode = "stream-data",
467
- credentials,
468
- headers,
469
- abortController,
470
- restoreMessagesOnFailure,
471
- onResponse,
472
- onUpdate,
473
- onFinish,
474
- generateId: generateId2
475
- }) {
476
- var _a;
477
- const response = await fetch(api, {
478
- method: "POST",
479
- body: JSON.stringify({
480
- messages,
481
- ...body
482
- }),
483
- headers: {
484
- "Content-Type": "application/json",
485
- ...headers
486
- },
487
- signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
488
- credentials
489
- }).catch((err) => {
490
- restoreMessagesOnFailure();
491
- throw err;
492
- });
493
- if (onResponse) {
494
- try {
495
- await onResponse(response);
496
- } catch (err) {
497
- throw err;
498
- }
499
- }
500
- if (!response.ok) {
501
- restoreMessagesOnFailure();
502
- throw new Error(
503
- await response.text() || "Failed to fetch the chat response."
504
- );
505
- }
506
- if (!response.body) {
507
- throw new Error("The response body is empty.");
508
- }
509
- const reader = response.body.getReader();
510
- switch (streamMode) {
511
- case "text": {
512
- const decoder = createChunkDecoder();
513
- const resultMessage = {
514
- id: generateId2(),
515
- createdAt: /* @__PURE__ */ new Date(),
516
- role: "assistant",
517
- content: ""
518
- };
519
- while (true) {
520
- const { done, value } = await reader.read();
521
- if (done) {
522
- break;
523
- }
524
- resultMessage.content += decoder(value);
525
- resultMessage.id = generateId2();
526
- onUpdate([{ ...resultMessage }], []);
527
- if ((abortController == null ? void 0 : abortController()) === null) {
528
- reader.cancel();
529
- break;
530
- }
531
- }
532
- onFinish == null ? void 0 : onFinish(resultMessage);
533
- return {
534
- messages: [resultMessage],
535
- data: []
536
- };
537
- }
538
- case "stream-data": {
539
- return await parseComplexResponse({
540
- reader,
541
- abortControllerRef: abortController != null ? { current: abortController() } : void 0,
542
- update: onUpdate,
543
- onFinish(prefixMap) {
544
- if (onFinish && prefixMap.text != null) {
545
- onFinish(prefixMap.text);
546
- }
547
- },
548
- generateId: generateId2
549
- });
550
- }
551
- default: {
552
- const exhaustiveCheck = streamMode;
553
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
554
- }
555
- }
556
- }
557
-
558
- // shared/process-chat-stream.ts
559
- async function processChatStream({
560
- getStreamedResponse,
561
- experimental_onFunctionCall,
562
- experimental_onToolCall,
563
- updateChatRequest,
564
- getCurrentMessages
565
- }) {
566
- while (true) {
567
- const messagesAndDataOrJustMessage = await getStreamedResponse();
568
- if ("messages" in messagesAndDataOrJustMessage) {
569
- let hasFollowingResponse = false;
570
- for (const message of messagesAndDataOrJustMessage.messages) {
571
- if ((message.function_call === void 0 || typeof message.function_call === "string") && (message.tool_calls === void 0 || typeof message.tool_calls === "string")) {
572
- continue;
573
- }
574
- hasFollowingResponse = true;
575
- if (experimental_onFunctionCall) {
576
- const functionCall = message.function_call;
577
- if (typeof functionCall !== "object") {
578
- console.warn(
579
- "experimental_onFunctionCall should not be defined when using tools"
580
- );
581
- continue;
582
- }
583
- const functionCallResponse = await experimental_onFunctionCall(
584
- getCurrentMessages(),
585
- functionCall
586
- );
587
- if (functionCallResponse === void 0) {
588
- hasFollowingResponse = false;
589
- break;
590
- }
591
- updateChatRequest(functionCallResponse);
592
- }
593
- if (experimental_onToolCall) {
594
- const toolCalls = message.tool_calls;
595
- if (!Array.isArray(toolCalls) || toolCalls.some((toolCall) => typeof toolCall !== "object")) {
596
- console.warn(
597
- "experimental_onToolCall should not be defined when using tools"
598
- );
599
- continue;
600
- }
601
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
602
- if (toolCallResponse === void 0) {
603
- hasFollowingResponse = false;
604
- break;
605
- }
606
- updateChatRequest(toolCallResponse);
607
- }
608
- }
609
- if (!hasFollowingResponse) {
610
- break;
611
- }
612
- } else {
613
- let fixFunctionCallArguments2 = function(response) {
614
- for (const message of response.messages) {
615
- if (message.tool_calls !== void 0) {
616
- for (const toolCall of message.tool_calls) {
617
- if (typeof toolCall === "object") {
618
- if (toolCall.function.arguments && typeof toolCall.function.arguments !== "string") {
619
- toolCall.function.arguments = JSON.stringify(
620
- toolCall.function.arguments
621
- );
622
- }
623
- }
624
- }
625
- }
626
- if (message.function_call !== void 0) {
627
- if (typeof message.function_call === "object") {
628
- if (message.function_call.arguments && typeof message.function_call.arguments !== "string") {
629
- message.function_call.arguments = JSON.stringify(
630
- message.function_call.arguments
631
- );
632
- }
633
- }
634
- }
635
- }
636
- };
637
- var fixFunctionCallArguments = fixFunctionCallArguments2;
638
- const streamedResponseMessage = messagesAndDataOrJustMessage;
639
- if ((streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") && (streamedResponseMessage.tool_calls === void 0 || typeof streamedResponseMessage.tool_calls === "string")) {
640
- break;
641
- }
642
- if (experimental_onFunctionCall) {
643
- const functionCall = streamedResponseMessage.function_call;
644
- if (!(typeof functionCall === "object")) {
645
- console.warn(
646
- "experimental_onFunctionCall should not be defined when using tools"
647
- );
648
- continue;
649
- }
650
- const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
651
- if (functionCallResponse === void 0)
652
- break;
653
- fixFunctionCallArguments2(functionCallResponse);
654
- updateChatRequest(functionCallResponse);
655
- }
656
- if (experimental_onToolCall) {
657
- const toolCalls = streamedResponseMessage.tool_calls;
658
- if (!(typeof toolCalls === "object")) {
659
- console.warn(
660
- "experimental_onToolCall should not be defined when using functions"
661
- );
662
- continue;
663
- }
664
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
665
- if (toolCallResponse === void 0)
666
- break;
667
- fixFunctionCallArguments2(toolCallResponse);
668
- updateChatRequest(toolCallResponse);
669
- }
670
- }
671
- }
672
- }
673
-
674
- // vue/use-chat.ts
675
- var uniqueId = 0;
676
- var useSWRV = import_swrv.default.default || import_swrv.default;
677
- var store = {};
678
- function useChat({
679
- api = "/api/chat",
680
- id,
681
- initialMessages = [],
682
- initialInput = "",
683
- sendExtraMessageFields,
684
- experimental_onFunctionCall,
685
- streamMode,
686
- onResponse,
687
- onFinish,
688
- onError,
689
- credentials,
690
- headers,
691
- body,
692
- generateId: generateId2 = generateId
693
- } = {}) {
694
- var _a, _b;
695
- const chatId = id || `chat-${uniqueId++}`;
696
- const key = `${api}|${chatId}`;
697
- const { data: messagesData, mutate: originalMutate } = useSWRV(
698
- key,
699
- () => store[key] || initialMessages
700
- );
701
- const { data: isLoading, mutate: mutateLoading } = useSWRV(
702
- `${chatId}-loading`,
703
- null
704
- );
705
- (_a = isLoading.value) != null ? _a : isLoading.value = false;
706
- (_b = messagesData.value) != null ? _b : messagesData.value = initialMessages;
707
- const mutate = (data) => {
708
- store[key] = data;
709
- return originalMutate();
710
- };
711
- const messages = messagesData;
712
- const error = (0, import_vue.ref)(void 0);
713
- const streamData = (0, import_vue.ref)(void 0);
714
- let abortController = null;
715
- async function triggerRequest(messagesSnapshot, { options, data } = {}) {
716
- try {
717
- error.value = void 0;
718
- mutateLoading(() => true);
719
- abortController = new AbortController();
720
- const previousMessages = messagesData.value;
721
- mutate(messagesSnapshot);
722
- let chatRequest = {
723
- messages: messagesSnapshot,
724
- options,
725
- data
726
- };
727
- await processChatStream({
728
- getStreamedResponse: async () => {
729
- var _a2;
730
- const existingData = (_a2 = streamData.value) != null ? _a2 : [];
731
- return await callChatApi({
732
- api,
733
- messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
734
- ({ role, content, name, function_call }) => ({
735
- role,
736
- content,
737
- ...name !== void 0 && { name },
738
- ...function_call !== void 0 && {
739
- function_call
740
- }
741
- })
742
- ),
743
- body: {
744
- data: chatRequest.data,
745
- ...(0, import_vue.unref)(body),
746
- // Use unref to unwrap the ref value
747
- ...options == null ? void 0 : options.body
748
- },
749
- streamMode,
750
- headers: {
751
- ...headers,
752
- ...options == null ? void 0 : options.headers
753
- },
754
- abortController: () => abortController,
755
- credentials,
756
- onResponse,
757
- onUpdate(merged, data2) {
758
- mutate([...chatRequest.messages, ...merged]);
759
- streamData.value = [...existingData, ...data2 != null ? data2 : []];
760
- },
761
- onFinish(message) {
762
- mutate([...chatRequest.messages, message]);
763
- onFinish == null ? void 0 : onFinish(message);
764
- },
765
- restoreMessagesOnFailure() {
766
- mutate(previousMessages);
767
- },
768
- generateId: generateId2
769
- });
770
- },
771
- experimental_onFunctionCall,
772
- updateChatRequest(newChatRequest) {
773
- chatRequest = newChatRequest;
774
- },
775
- getCurrentMessages: () => messages.value
776
- });
777
- abortController = null;
778
- } catch (err) {
779
- if (err.name === "AbortError") {
780
- abortController = null;
781
- return null;
782
- }
783
- if (onError && err instanceof Error) {
784
- onError(err);
785
- }
786
- error.value = err;
787
- } finally {
788
- mutateLoading(() => false);
789
- }
790
- }
791
- const append = async (message, options) => {
792
- if (!message.id) {
793
- message.id = generateId2();
794
- }
795
- return triggerRequest(messages.value.concat(message), options);
796
- };
797
- const reload = async (options) => {
798
- const messagesSnapshot = messages.value;
799
- if (messagesSnapshot.length === 0)
800
- return null;
801
- const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
802
- if (lastMessage.role === "assistant") {
803
- return triggerRequest(messagesSnapshot.slice(0, -1), options);
804
- }
805
- return triggerRequest(messagesSnapshot, options);
806
- };
807
- const stop = () => {
808
- if (abortController) {
809
- abortController.abort();
810
- abortController = null;
811
- }
812
- };
813
- const setMessages = (messages2) => {
814
- mutate(messages2);
815
- };
816
- const input = (0, import_vue.ref)(initialInput);
817
- const handleSubmit = (e, options = {}) => {
818
- e.preventDefault();
819
- const inputValue = input.value;
820
- if (!inputValue)
821
- return;
822
- append(
823
- {
824
- content: inputValue,
825
- role: "user"
826
- },
827
- options
828
- );
829
- input.value = "";
830
- };
831
- return {
832
- messages,
833
- append,
834
- error,
835
- reload,
836
- stop,
837
- setMessages,
838
- input,
839
- handleSubmit,
840
- isLoading,
841
- data: streamData
842
- };
843
- }
844
-
845
- // vue/use-completion.ts
846
- var import_swrv2 = __toESM(require("swrv"));
847
- var import_vue2 = require("vue");
848
-
849
- // shared/call-completion-api.ts
850
- async function callCompletionApi({
851
- api,
852
- prompt,
853
- credentials,
854
- headers,
855
- body,
856
- streamMode = "stream-data",
857
- setCompletion,
858
- setLoading,
859
- setError,
860
- setAbortController,
861
- onResponse,
862
- onFinish,
863
- onError,
864
- onData
865
- }) {
866
- try {
867
- setLoading(true);
868
- setError(void 0);
869
- const abortController = new AbortController();
870
- setAbortController(abortController);
871
- setCompletion("");
872
- const res = await fetch(api, {
873
- method: "POST",
874
- body: JSON.stringify({
875
- prompt,
876
- ...body
877
- }),
878
- credentials,
879
- headers: {
880
- "Content-Type": "application/json",
881
- ...headers
882
- },
883
- signal: abortController.signal
884
- }).catch((err) => {
885
- throw err;
886
- });
887
- if (onResponse) {
888
- try {
889
- await onResponse(res);
890
- } catch (err) {
891
- throw err;
892
- }
893
- }
894
- if (!res.ok) {
895
- throw new Error(
896
- await res.text() || "Failed to fetch the chat response."
897
- );
898
- }
899
- if (!res.body) {
900
- throw new Error("The response body is empty.");
901
- }
902
- let result = "";
903
- const reader = res.body.getReader();
904
- switch (streamMode) {
905
- case "text": {
906
- const decoder = createChunkDecoder();
907
- while (true) {
908
- const { done, value } = await reader.read();
909
- if (done) {
910
- break;
911
- }
912
- result += decoder(value);
913
- setCompletion(result);
914
- if (abortController === null) {
915
- reader.cancel();
916
- break;
917
- }
918
- }
919
- break;
920
- }
921
- case "stream-data": {
922
- for await (const { type, value } of readDataStream(reader, {
923
- isAborted: () => abortController === null
924
- })) {
925
- switch (type) {
926
- case "text": {
927
- result += value;
928
- setCompletion(result);
929
- break;
930
- }
931
- case "data": {
932
- onData == null ? void 0 : onData(value);
933
- break;
934
- }
935
- }
936
- }
937
- break;
938
- }
939
- default: {
940
- const exhaustiveCheck = streamMode;
941
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
942
- }
943
- }
944
- if (onFinish) {
945
- onFinish(prompt, result);
946
- }
947
- setAbortController(null);
948
- return result;
949
- } catch (err) {
950
- if (err.name === "AbortError") {
951
- setAbortController(null);
952
- return null;
953
- }
954
- if (err instanceof Error) {
955
- if (onError) {
956
- onError(err);
957
- }
958
- }
959
- setError(err);
960
- } finally {
961
- setLoading(false);
962
- }
963
- }
964
-
965
- // vue/use-completion.ts
966
- var uniqueId2 = 0;
967
- var useSWRV2 = import_swrv2.default.default || import_swrv2.default;
968
- var store2 = {};
969
- function useCompletion({
970
- api = "/api/completion",
971
- id,
972
- initialCompletion = "",
973
- initialInput = "",
974
- credentials,
975
- headers,
976
- body,
977
- streamMode,
978
- onResponse,
979
- onFinish,
980
- onError
981
- } = {}) {
982
- var _a;
983
- const completionId = id || `completion-${uniqueId2++}`;
984
- const key = `${api}|${completionId}`;
985
- const { data, mutate: originalMutate } = useSWRV2(
986
- key,
987
- () => store2[key] || initialCompletion
988
- );
989
- const { data: isLoading, mutate: mutateLoading } = useSWRV2(
990
- `${completionId}-loading`,
991
- null
992
- );
993
- (_a = isLoading.value) != null ? _a : isLoading.value = false;
994
- const { data: streamData, mutate: mutateStreamData } = useSWRV2(`${completionId}-data`, null);
995
- data.value || (data.value = initialCompletion);
996
- const mutate = (data2) => {
997
- store2[key] = data2;
998
- return originalMutate();
999
- };
1000
- const completion = data;
1001
- const error = (0, import_vue2.ref)(void 0);
1002
- let abortController = null;
1003
- async function triggerRequest(prompt, options) {
1004
- var _a2;
1005
- const existingData = (_a2 = streamData.value) != null ? _a2 : [];
1006
- return callCompletionApi({
1007
- api,
1008
- prompt,
1009
- credentials,
1010
- headers: {
1011
- ...headers,
1012
- ...options == null ? void 0 : options.headers
1013
- },
1014
- body: {
1015
- ...(0, import_vue2.unref)(body),
1016
- ...options == null ? void 0 : options.body
1017
- },
1018
- streamMode,
1019
- setCompletion: mutate,
1020
- setLoading: (loading) => mutateLoading(() => loading),
1021
- setError: (err) => {
1022
- error.value = err;
1023
- },
1024
- setAbortController: (controller) => {
1025
- abortController = controller;
1026
- },
1027
- onResponse,
1028
- onFinish,
1029
- onError,
1030
- onData: (data2) => {
1031
- mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
1032
- }
1033
- });
1034
- }
1035
- const complete = async (prompt, options) => {
1036
- return triggerRequest(prompt, options);
1037
- };
1038
- const stop = () => {
1039
- if (abortController) {
1040
- abortController.abort();
1041
- abortController = null;
1042
- }
1043
- };
1044
- const setCompletion = (completion2) => {
1045
- mutate(completion2);
1046
- };
1047
- const input = (0, import_vue2.ref)(initialInput);
1048
- const handleSubmit = (e) => {
1049
- e.preventDefault();
1050
- const inputValue = input.value;
1051
- if (!inputValue)
1052
- return;
1053
- return complete(inputValue);
1054
- };
1055
- return {
1056
- completion,
1057
- complete,
1058
- error,
1059
- stop,
1060
- setCompletion,
1061
- input,
1062
- handleSubmit,
1063
- isLoading,
1064
- data: streamData
1065
- };
1066
- }
1067
- // Annotate the CommonJS export names for ESM import in node:
1068
- 0 && (module.exports = {
1069
- useChat,
1070
- useCompletion
1071
- });
1072
- //# sourceMappingURL=index.js.map