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