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