ai 3.1.29 → 3.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,1063 +24,9 @@ __export(solid_exports, {
24
24
  useCompletion: () => useCompletion
25
25
  });
26
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
- onToolCall,
302
- onFinish,
303
- generateId: generateId2 = generateId,
304
- getCurrentDate = () => /* @__PURE__ */ new Date()
305
- }) {
306
- const createdAt = getCurrentDate();
307
- const prefixMap = {
308
- data: []
309
- };
310
- let message_annotations = void 0;
311
- for await (const { type, value } of readDataStream(reader, {
312
- isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
313
- })) {
314
- if (type === "text") {
315
- if (prefixMap["text"]) {
316
- prefixMap["text"] = {
317
- ...prefixMap["text"],
318
- content: (prefixMap["text"].content || "") + value
319
- };
320
- } else {
321
- prefixMap["text"] = {
322
- id: generateId2(),
323
- role: "assistant",
324
- content: value,
325
- createdAt
326
- };
327
- }
328
- }
329
- if (type === "tool_call") {
330
- if (prefixMap.text == null) {
331
- prefixMap.text = {
332
- id: generateId2(),
333
- role: "assistant",
334
- content: "",
335
- createdAt
336
- };
337
- }
338
- if (prefixMap.text.toolInvocations == null) {
339
- prefixMap.text.toolInvocations = [];
340
- }
341
- prefixMap.text.toolInvocations.push(value);
342
- if (onToolCall) {
343
- const result = await onToolCall({ toolCall: value });
344
- if (result != null) {
345
- prefixMap.text.toolInvocations[prefixMap.text.toolInvocations.length - 1] = { ...value, result };
346
- }
347
- }
348
- } else if (type === "tool_result") {
349
- if (prefixMap.text == null) {
350
- prefixMap.text = {
351
- id: generateId2(),
352
- role: "assistant",
353
- content: "",
354
- createdAt
355
- };
356
- }
357
- if (prefixMap.text.toolInvocations == null) {
358
- prefixMap.text.toolInvocations = [];
359
- }
360
- const toolInvocationIndex = prefixMap.text.toolInvocations.findIndex(
361
- (invocation) => invocation.toolCallId === value.toolCallId
362
- );
363
- if (toolInvocationIndex !== -1) {
364
- prefixMap.text.toolInvocations[toolInvocationIndex] = value;
365
- } else {
366
- prefixMap.text.toolInvocations.push(value);
367
- }
368
- }
369
- let functionCallMessage = null;
370
- if (type === "function_call") {
371
- prefixMap["function_call"] = {
372
- id: generateId2(),
373
- role: "assistant",
374
- content: "",
375
- function_call: value.function_call,
376
- name: value.function_call.name,
377
- createdAt
378
- };
379
- functionCallMessage = prefixMap["function_call"];
380
- }
381
- let toolCallMessage = null;
382
- if (type === "tool_calls") {
383
- prefixMap["tool_calls"] = {
384
- id: generateId2(),
385
- role: "assistant",
386
- content: "",
387
- tool_calls: value.tool_calls,
388
- createdAt
389
- };
390
- toolCallMessage = prefixMap["tool_calls"];
391
- }
392
- if (type === "data") {
393
- prefixMap["data"].push(...value);
394
- }
395
- let responseMessage = prefixMap["text"];
396
- if (type === "message_annotations") {
397
- if (!message_annotations) {
398
- message_annotations = [...value];
399
- } else {
400
- message_annotations.push(...value);
401
- }
402
- functionCallMessage = assignAnnotationsToMessage(
403
- prefixMap["function_call"],
404
- message_annotations
405
- );
406
- toolCallMessage = assignAnnotationsToMessage(
407
- prefixMap["tool_calls"],
408
- message_annotations
409
- );
410
- responseMessage = assignAnnotationsToMessage(
411
- prefixMap["text"],
412
- message_annotations
413
- );
414
- }
415
- if (message_annotations == null ? void 0 : message_annotations.length) {
416
- const messagePrefixKeys = [
417
- "text",
418
- "function_call",
419
- "tool_calls"
420
- ];
421
- messagePrefixKeys.forEach((key) => {
422
- if (prefixMap[key]) {
423
- prefixMap[key].annotations = [...message_annotations];
424
- }
425
- });
426
- }
427
- const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
428
- ...assignAnnotationsToMessage(message, message_annotations)
429
- }));
430
- update(merged, [...prefixMap["data"]]);
431
- }
432
- onFinish == null ? void 0 : onFinish(prefixMap);
433
- return {
434
- messages: [
435
- prefixMap.text,
436
- prefixMap.function_call,
437
- prefixMap.tool_calls
438
- ].filter(Boolean),
439
- data: prefixMap.data
440
- };
441
- }
442
-
443
- // shared/utils.ts
444
- function createChunkDecoder(complex) {
445
- const decoder = new TextDecoder();
446
- if (!complex) {
447
- return function(chunk) {
448
- if (!chunk)
449
- return "";
450
- return decoder.decode(chunk, { stream: true });
451
- };
452
- }
453
- return function(chunk) {
454
- const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
455
- return decoded.map(parseStreamPart).filter(Boolean);
456
- };
457
- }
458
-
459
- // shared/call-chat-api.ts
460
- async function callChatApi({
461
- api,
462
- messages,
463
- body,
464
- streamMode = "stream-data",
465
- credentials,
466
- headers,
467
- abortController,
468
- restoreMessagesOnFailure,
469
- onResponse,
470
- onUpdate,
471
- onFinish,
472
- onToolCall,
473
- generateId: generateId2
474
- }) {
475
- var _a;
476
- const response = await fetch(api, {
477
- method: "POST",
478
- body: JSON.stringify({
479
- messages,
480
- ...body
481
- }),
482
- headers: {
483
- "Content-Type": "application/json",
484
- ...headers
485
- },
486
- signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
487
- credentials
488
- }).catch((err) => {
489
- restoreMessagesOnFailure();
490
- throw err;
491
- });
492
- if (onResponse) {
493
- try {
494
- await onResponse(response);
495
- } catch (err) {
496
- throw err;
497
- }
498
- }
499
- if (!response.ok) {
500
- restoreMessagesOnFailure();
501
- throw new Error(
502
- await response.text() || "Failed to fetch the chat response."
503
- );
504
- }
505
- if (!response.body) {
506
- throw new Error("The response body is empty.");
507
- }
508
- const reader = response.body.getReader();
509
- switch (streamMode) {
510
- case "text": {
511
- const decoder = createChunkDecoder();
512
- const resultMessage = {
513
- id: generateId2(),
514
- createdAt: /* @__PURE__ */ new Date(),
515
- role: "assistant",
516
- content: ""
517
- };
518
- while (true) {
519
- const { done, value } = await reader.read();
520
- if (done) {
521
- break;
522
- }
523
- resultMessage.content += decoder(value);
524
- resultMessage.id = generateId2();
525
- onUpdate([{ ...resultMessage }], []);
526
- if ((abortController == null ? void 0 : abortController()) === null) {
527
- reader.cancel();
528
- break;
529
- }
530
- }
531
- onFinish == null ? void 0 : onFinish(resultMessage);
532
- return {
533
- messages: [resultMessage],
534
- data: []
535
- };
536
- }
537
- case "stream-data": {
538
- return await parseComplexResponse({
539
- reader,
540
- abortControllerRef: abortController != null ? { current: abortController() } : void 0,
541
- update: onUpdate,
542
- onToolCall,
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
- // solid/use-chat.ts
675
- var uniqueId = 0;
676
- var store = {};
677
- var chatApiStore = (0, import_swr_store.createSWRStore)({
678
- get: async (key) => {
679
- var _a;
680
- return (_a = store[key]) != null ? _a : [];
681
- }
682
- });
683
- function useChat({
684
- api = "/api/chat",
685
- id,
686
- initialMessages = [],
687
- initialInput = "",
688
- sendExtraMessageFields,
689
- experimental_onFunctionCall,
690
- onResponse,
691
- onFinish,
692
- onError,
693
- credentials,
694
- headers,
695
- body,
696
- streamMode,
697
- generateId: generateId2 = generateId
698
- } = {}) {
699
- const chatId = id || `chat-${uniqueId++}`;
700
- const key = `${api}|${chatId}`;
701
- const messages = (0, import_solid_swr_store.useSWRStore)(chatApiStore, () => [key], {
702
- initialData: initialMessages
703
- });
704
- const mutate = (data) => {
705
- store[key] = data;
706
- return chatApiStore.mutate([key], {
707
- status: "success",
708
- data
709
- });
710
- };
711
- const [error, setError] = (0, import_solid_js.createSignal)(void 0);
712
- const [streamData, setStreamData] = (0, import_solid_js.createSignal)(
713
- void 0
714
- );
715
- const [isLoading, setIsLoading] = (0, import_solid_js.createSignal)(false);
716
- let abortController = null;
717
- async function triggerRequest(messagesSnapshot, { options, data } = {}) {
718
- try {
719
- setError(void 0);
720
- setIsLoading(true);
721
- abortController = new AbortController();
722
- const getCurrentMessages = () => chatApiStore.get([key], {
723
- shouldRevalidate: false
724
- });
725
- const previousMessages = getCurrentMessages();
726
- mutate(messagesSnapshot);
727
- let chatRequest = {
728
- messages: messagesSnapshot,
729
- options,
730
- data
731
- };
732
- await processChatStream({
733
- getStreamedResponse: async () => {
734
- var _a;
735
- const existingData = (_a = streamData()) != null ? _a : [];
736
- return await callChatApi({
737
- api,
738
- messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
739
- ({
740
- role,
741
- content,
742
- name,
743
- data: data2,
744
- annotations,
745
- function_call
746
- }) => ({
747
- role,
748
- content,
749
- ...name !== void 0 && { name },
750
- ...data2 !== void 0 && { data: data2 },
751
- ...annotations !== void 0 && { annotations },
752
- // outdated function/tool call handling (TODO deprecate):
753
- ...function_call !== void 0 && { function_call }
754
- })
755
- ),
756
- body: {
757
- data: chatRequest.data,
758
- ...body,
759
- ...options == null ? void 0 : options.body
760
- },
761
- streamMode,
762
- headers: {
763
- ...headers,
764
- ...options == null ? void 0 : options.headers
765
- },
766
- abortController: () => abortController,
767
- credentials,
768
- onResponse,
769
- onUpdate(merged, data2) {
770
- mutate([...chatRequest.messages, ...merged]);
771
- setStreamData([...existingData, ...data2 != null ? data2 : []]);
772
- },
773
- onFinish,
774
- restoreMessagesOnFailure() {
775
- if (previousMessages.status === "success") {
776
- mutate(previousMessages.data);
777
- }
778
- },
779
- generateId: generateId2
780
- });
781
- },
782
- experimental_onFunctionCall,
783
- updateChatRequest(newChatRequest) {
784
- chatRequest = newChatRequest;
785
- },
786
- getCurrentMessages: () => getCurrentMessages().data
787
- });
788
- abortController = null;
789
- } catch (err) {
790
- if (err.name === "AbortError") {
791
- abortController = null;
792
- return null;
793
- }
794
- if (onError && err instanceof Error) {
795
- onError(err);
796
- }
797
- setError(err);
798
- } finally {
799
- setIsLoading(false);
800
- }
801
- }
802
- const append = async (message, options) => {
803
- var _a;
804
- if (!message.id) {
805
- message.id = generateId2();
806
- }
807
- return triggerRequest(
808
- ((_a = messages()) != null ? _a : []).concat(message),
809
- options
810
- );
811
- };
812
- const reload = async (options) => {
813
- const messagesSnapshot = messages();
814
- if (!messagesSnapshot || messagesSnapshot.length === 0)
815
- return null;
816
- const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
817
- if (lastMessage.role === "assistant") {
818
- return triggerRequest(messagesSnapshot.slice(0, -1), options);
819
- }
820
- return triggerRequest(messagesSnapshot, options);
821
- };
822
- const stop = () => {
823
- if (abortController) {
824
- abortController.abort();
825
- abortController = null;
826
- }
827
- };
828
- const setMessages = (messages2) => {
829
- mutate(messages2);
830
- };
831
- const [input, setInput] = (0, import_solid_js.createSignal)(initialInput);
832
- const handleSubmit = (e, options = {}) => {
833
- e.preventDefault();
834
- const inputValue = input();
835
- if (!inputValue)
836
- return;
837
- append(
838
- {
839
- content: inputValue,
840
- role: "user",
841
- createdAt: /* @__PURE__ */ new Date()
842
- },
843
- options
844
- );
845
- setInput("");
846
- };
847
- return {
848
- messages,
849
- append,
850
- error,
851
- reload,
852
- stop,
853
- setMessages,
854
- input,
855
- setInput,
856
- handleSubmit,
857
- isLoading,
858
- data: streamData
859
- };
860
- }
861
-
862
- // solid/use-completion.ts
863
- var import_solid_js2 = require("solid-js");
864
- var import_solid_swr_store2 = require("solid-swr-store");
865
- var import_swr_store2 = require("swr-store");
866
-
867
- // shared/call-completion-api.ts
868
- async function callCompletionApi({
869
- api,
870
- prompt,
871
- credentials,
872
- headers,
873
- body,
874
- streamMode = "stream-data",
875
- setCompletion,
876
- setLoading,
877
- setError,
878
- setAbortController,
879
- onResponse,
880
- onFinish,
881
- onError,
882
- onData
883
- }) {
884
- try {
885
- setLoading(true);
886
- setError(void 0);
887
- const abortController = new AbortController();
888
- setAbortController(abortController);
889
- setCompletion("");
890
- const res = await fetch(api, {
891
- method: "POST",
892
- body: JSON.stringify({
893
- prompt,
894
- ...body
895
- }),
896
- credentials,
897
- headers: {
898
- "Content-Type": "application/json",
899
- ...headers
900
- },
901
- signal: abortController.signal
902
- }).catch((err) => {
903
- throw err;
904
- });
905
- if (onResponse) {
906
- try {
907
- await onResponse(res);
908
- } catch (err) {
909
- throw err;
910
- }
911
- }
912
- if (!res.ok) {
913
- throw new Error(
914
- await res.text() || "Failed to fetch the chat response."
915
- );
916
- }
917
- if (!res.body) {
918
- throw new Error("The response body is empty.");
919
- }
920
- let result = "";
921
- const reader = res.body.getReader();
922
- switch (streamMode) {
923
- case "text": {
924
- const decoder = createChunkDecoder();
925
- while (true) {
926
- const { done, value } = await reader.read();
927
- if (done) {
928
- break;
929
- }
930
- result += decoder(value);
931
- setCompletion(result);
932
- if (abortController === null) {
933
- reader.cancel();
934
- break;
935
- }
936
- }
937
- break;
938
- }
939
- case "stream-data": {
940
- for await (const { type, value } of readDataStream(reader, {
941
- isAborted: () => abortController === null
942
- })) {
943
- switch (type) {
944
- case "text": {
945
- result += value;
946
- setCompletion(result);
947
- break;
948
- }
949
- case "data": {
950
- onData == null ? void 0 : onData(value);
951
- break;
952
- }
953
- }
954
- }
955
- break;
956
- }
957
- default: {
958
- const exhaustiveCheck = streamMode;
959
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
960
- }
961
- }
962
- if (onFinish) {
963
- onFinish(prompt, result);
964
- }
965
- setAbortController(null);
966
- return result;
967
- } catch (err) {
968
- if (err.name === "AbortError") {
969
- setAbortController(null);
970
- return null;
971
- }
972
- if (err instanceof Error) {
973
- if (onError) {
974
- onError(err);
975
- }
976
- }
977
- setError(err);
978
- } finally {
979
- setLoading(false);
980
- }
981
- }
982
-
983
- // solid/use-completion.ts
984
- var uniqueId2 = 0;
985
- var store2 = {};
986
- var completionApiStore = (0, import_swr_store2.createSWRStore)({
987
- get: async (key) => {
988
- var _a;
989
- return (_a = store2[key]) != null ? _a : [];
990
- }
991
- });
992
- function useCompletion({
993
- api = "/api/completion",
994
- id,
995
- initialCompletion = "",
996
- initialInput = "",
997
- credentials,
998
- headers,
999
- body,
1000
- streamMode,
1001
- onResponse,
1002
- onFinish,
1003
- onError
1004
- } = {}) {
1005
- const completionId = id || `completion-${uniqueId2++}`;
1006
- const key = `${api}|${completionId}`;
1007
- const data = (0, import_solid_swr_store2.useSWRStore)(completionApiStore, () => [key], {
1008
- initialData: initialCompletion
1009
- });
1010
- const mutate = (data2) => {
1011
- store2[key] = data2;
1012
- return completionApiStore.mutate([key], {
1013
- data: data2,
1014
- status: "success"
1015
- });
1016
- };
1017
- const completion = data;
1018
- const [error, setError] = (0, import_solid_js2.createSignal)(void 0);
1019
- const [streamData, setStreamData] = (0, import_solid_js2.createSignal)(
1020
- void 0
1021
- );
1022
- const [isLoading, setIsLoading] = (0, import_solid_js2.createSignal)(false);
1023
- let abortController = null;
1024
- const complete = async (prompt, options) => {
1025
- var _a;
1026
- const existingData = (_a = streamData()) != null ? _a : [];
1027
- return callCompletionApi({
1028
- api,
1029
- prompt,
1030
- credentials,
1031
- headers: {
1032
- ...headers,
1033
- ...options == null ? void 0 : options.headers
1034
- },
1035
- body: {
1036
- ...body,
1037
- ...options == null ? void 0 : options.body
1038
- },
1039
- streamMode,
1040
- setCompletion: mutate,
1041
- setLoading: setIsLoading,
1042
- setError,
1043
- setAbortController: (controller) => {
1044
- abortController = controller;
1045
- },
1046
- onResponse,
1047
- onFinish,
1048
- onError,
1049
- onData: (data2) => {
1050
- setStreamData([...existingData, ...data2 != null ? data2 : []]);
1051
- }
1052
- });
1053
- };
1054
- const stop = () => {
1055
- if (abortController) {
1056
- abortController.abort();
1057
- abortController = null;
1058
- }
1059
- };
1060
- const setCompletion = (completion2) => {
1061
- mutate(completion2);
1062
- };
1063
- const [input, setInput] = (0, import_solid_js2.createSignal)(initialInput);
1064
- const handleSubmit = (e) => {
1065
- e.preventDefault();
1066
- const inputValue = input();
1067
- if (!inputValue)
1068
- return;
1069
- return complete(inputValue);
1070
- };
1071
- return {
1072
- completion,
1073
- complete,
1074
- error,
1075
- stop,
1076
- setCompletion,
1077
- input,
1078
- setInput,
1079
- handleSubmit,
1080
- isLoading,
1081
- data: streamData
1082
- };
1083
- }
27
+ var import_solid = require("@ai-sdk/solid");
28
+ var useChat = import_solid.useChat;
29
+ var useCompletion = import_solid.useCompletion;
1084
30
  // Annotate the CommonJS export names for ESM import in node:
1085
31
  0 && (module.exports = {
1086
32
  useChat,