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