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