ai 0.0.0-85f9a635-20240518005312 → 0.0.0-9477ebb9-20250403064906

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