@ai-sdk/react 1.2.4 → 2.0.0-canary.0

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.
package/dist/index.mjs CHANGED
@@ -1,173 +1,3 @@
1
- // src/use-assistant.ts
2
- import { isAbortError } from "@ai-sdk/provider-utils";
3
- import {
4
- generateId,
5
- processAssistantStream
6
- } from "@ai-sdk/ui-utils";
7
- import { useCallback, useRef, useState } from "react";
8
- var getOriginalFetch = () => fetch;
9
- function useAssistant({
10
- api,
11
- threadId: threadIdParam,
12
- credentials,
13
- headers,
14
- body,
15
- onError,
16
- fetch: fetch2
17
- }) {
18
- const [messages, setMessages] = useState([]);
19
- const [input, setInput] = useState("");
20
- const [currentThreadId, setCurrentThreadId] = useState(
21
- void 0
22
- );
23
- const [status, setStatus] = useState("awaiting_message");
24
- const [error, setError] = useState(void 0);
25
- const handleInputChange = (event) => {
26
- setInput(event.target.value);
27
- };
28
- const abortControllerRef = useRef(null);
29
- const stop = useCallback(() => {
30
- if (abortControllerRef.current) {
31
- abortControllerRef.current.abort();
32
- abortControllerRef.current = null;
33
- }
34
- }, []);
35
- const append = async (message, requestOptions) => {
36
- var _a, _b;
37
- setStatus("in_progress");
38
- setMessages((messages2) => {
39
- var _a2;
40
- return [
41
- ...messages2,
42
- {
43
- ...message,
44
- id: (_a2 = message.id) != null ? _a2 : generateId()
45
- }
46
- ];
47
- });
48
- setInput("");
49
- const abortController = new AbortController();
50
- try {
51
- abortControllerRef.current = abortController;
52
- const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
53
- const response = await actualFetch(api, {
54
- method: "POST",
55
- credentials,
56
- signal: abortController.signal,
57
- headers: { "Content-Type": "application/json", ...headers },
58
- body: JSON.stringify({
59
- ...body,
60
- // always use user-provided threadId when available:
61
- threadId: (_a = threadIdParam != null ? threadIdParam : currentThreadId) != null ? _a : null,
62
- message: message.content,
63
- // optional request data:
64
- data: requestOptions == null ? void 0 : requestOptions.data
65
- })
66
- });
67
- if (!response.ok) {
68
- throw new Error(
69
- (_b = await response.text()) != null ? _b : "Failed to fetch the assistant response."
70
- );
71
- }
72
- if (response.body == null) {
73
- throw new Error("The response body is empty.");
74
- }
75
- await processAssistantStream({
76
- stream: response.body,
77
- onAssistantMessagePart(value) {
78
- setMessages((messages2) => [
79
- ...messages2,
80
- {
81
- id: value.id,
82
- role: value.role,
83
- content: value.content[0].text.value,
84
- parts: []
85
- }
86
- ]);
87
- },
88
- onTextPart(value) {
89
- setMessages((messages2) => {
90
- const lastMessage = messages2[messages2.length - 1];
91
- return [
92
- ...messages2.slice(0, messages2.length - 1),
93
- {
94
- id: lastMessage.id,
95
- role: lastMessage.role,
96
- content: lastMessage.content + value,
97
- parts: lastMessage.parts
98
- }
99
- ];
100
- });
101
- },
102
- onAssistantControlDataPart(value) {
103
- setCurrentThreadId(value.threadId);
104
- setMessages((messages2) => {
105
- const lastMessage = messages2[messages2.length - 1];
106
- lastMessage.id = value.messageId;
107
- return [...messages2.slice(0, messages2.length - 1), lastMessage];
108
- });
109
- },
110
- onDataMessagePart(value) {
111
- setMessages((messages2) => {
112
- var _a2;
113
- return [
114
- ...messages2,
115
- {
116
- id: (_a2 = value.id) != null ? _a2 : generateId(),
117
- role: "data",
118
- content: "",
119
- data: value.data,
120
- parts: []
121
- }
122
- ];
123
- });
124
- },
125
- onErrorPart(value) {
126
- setError(new Error(value));
127
- }
128
- });
129
- } catch (error2) {
130
- if (isAbortError(error2) && abortController.signal.aborted) {
131
- abortControllerRef.current = null;
132
- return;
133
- }
134
- if (onError && error2 instanceof Error) {
135
- onError(error2);
136
- }
137
- setError(error2);
138
- } finally {
139
- abortControllerRef.current = null;
140
- setStatus("awaiting_message");
141
- }
142
- };
143
- const submitMessage = async (event, requestOptions) => {
144
- var _a;
145
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
146
- if (input === "") {
147
- return;
148
- }
149
- append({ role: "user", content: input, parts: [] }, requestOptions);
150
- };
151
- const setThreadId = (threadId) => {
152
- setCurrentThreadId(threadId);
153
- setMessages([]);
154
- };
155
- return {
156
- append,
157
- messages,
158
- setMessages,
159
- threadId: currentThreadId,
160
- setThreadId,
161
- input,
162
- setInput,
163
- handleInputChange,
164
- submitMessage,
165
- status,
166
- error,
167
- stop
168
- };
169
- }
170
-
171
1
  // src/use-chat.ts
172
2
  import {
173
3
  callChatApi,
@@ -180,7 +10,7 @@ import {
180
10
  shouldResubmitMessages,
181
11
  updateToolCallResult
182
12
  } from "@ai-sdk/ui-utils";
183
- import { useCallback as useCallback2, useEffect as useEffect2, useMemo, useRef as useRef2, useState as useState3 } from "react";
13
+ import { useCallback, useEffect as useEffect2, useMemo, useRef, useState as useState2 } from "react";
184
14
  import useSWR from "swr";
185
15
 
186
16
  // src/throttle.ts
@@ -191,9 +21,9 @@ function throttle(fn, waitMs) {
191
21
 
192
22
  // src/util/use-stable-value.ts
193
23
  import { isDeepEqualData } from "@ai-sdk/ui-utils";
194
- import { useEffect, useState as useState2 } from "react";
24
+ import { useEffect, useState } from "react";
195
25
  function useStableValue(latestValue) {
196
- const [value, setValue] = useState2(latestValue);
26
+ const [value, setValue] = useState(latestValue);
197
27
  useEffect(() => {
198
28
  if (!isDeepEqualData(latestValue, value)) {
199
29
  setValue(latestValue);
@@ -219,12 +49,12 @@ function useChat({
219
49
  credentials,
220
50
  headers,
221
51
  body,
222
- generateId: generateId2 = generateIdFunc,
52
+ generateId = generateIdFunc,
223
53
  fetch: fetch2,
224
54
  keepLastMessageOnError = true,
225
55
  experimental_throttle: throttleWaitMs
226
56
  } = {}) {
227
- const [hookId] = useState3(generateId2);
57
+ const [hookId] = useState2(generateId);
228
58
  const chatId = id != null ? id : hookId;
229
59
  const chatKey = typeof api === "string" ? [api, chatId] : chatId;
230
60
  const stableInitialMessages = useStableValue(initialMessages != null ? initialMessages : []);
@@ -237,19 +67,19 @@ function useChat({
237
67
  null,
238
68
  { fallbackData: processedInitialMessages }
239
69
  );
240
- const messagesRef = useRef2(messages || []);
70
+ const messagesRef = useRef(messages || []);
241
71
  useEffect2(() => {
242
72
  messagesRef.current = messages || [];
243
73
  }, [messages]);
244
74
  const { data: streamData, mutate: mutateStreamData } = useSWR([chatKey, "streamData"], null);
245
- const streamDataRef = useRef2(streamData);
75
+ const streamDataRef = useRef(streamData);
246
76
  useEffect2(() => {
247
77
  streamDataRef.current = streamData;
248
78
  }, [streamData]);
249
79
  const { data: status = "ready", mutate: mutateStatus } = useSWR([chatKey, "status"], null);
250
80
  const { data: error = void 0, mutate: setError } = useSWR([chatKey, "error"], null);
251
- const abortControllerRef = useRef2(null);
252
- const extraMetadataRef = useRef2({
81
+ const abortControllerRef = useRef(null);
82
+ const extraMetadataRef = useRef({
253
83
  credentials,
254
84
  headers,
255
85
  body
@@ -261,7 +91,7 @@ function useChat({
261
91
  body
262
92
  };
263
93
  }, [credentials, headers, body]);
264
- const triggerRequest = useCallback2(
94
+ const triggerRequest = useCallback(
265
95
  async (chatRequest) => {
266
96
  var _a, _b;
267
97
  mutateStatus("submitted");
@@ -348,7 +178,7 @@ function useChat({
348
178
  },
349
179
  onToolCall,
350
180
  onFinish,
351
- generateId: generateId2,
181
+ generateId,
352
182
  fetch: fetch2,
353
183
  lastMessage: chatMessages[chatMessages.length - 1]
354
184
  });
@@ -394,14 +224,14 @@ function useChat({
394
224
  maxSteps,
395
225
  messagesRef,
396
226
  abortControllerRef,
397
- generateId2,
227
+ generateId,
398
228
  fetch2,
399
229
  keepLastMessageOnError,
400
230
  throttleWaitMs,
401
231
  chatId
402
232
  ]
403
233
  );
404
- const append = useCallback2(
234
+ const append = useCallback(
405
235
  async (message, {
406
236
  data,
407
237
  headers: headers2,
@@ -414,16 +244,16 @@ function useChat({
414
244
  );
415
245
  const messages2 = messagesRef.current.concat({
416
246
  ...message,
417
- id: (_a = message.id) != null ? _a : generateId2(),
247
+ id: (_a = message.id) != null ? _a : generateId(),
418
248
  createdAt: (_b = message.createdAt) != null ? _b : /* @__PURE__ */ new Date(),
419
249
  experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
420
250
  parts: getMessageParts(message)
421
251
  });
422
252
  return triggerRequest({ messages: messages2, headers: headers2, body: body2, data });
423
253
  },
424
- [triggerRequest, generateId2]
254
+ [triggerRequest, generateId]
425
255
  );
426
- const reload = useCallback2(
256
+ const reload = useCallback(
427
257
  async ({ data, headers: headers2, body: body2 } = {}) => {
428
258
  const messages2 = messagesRef.current;
429
259
  if (messages2.length === 0) {
@@ -439,13 +269,13 @@ function useChat({
439
269
  },
440
270
  [triggerRequest]
441
271
  );
442
- const stop = useCallback2(() => {
272
+ const stop = useCallback(() => {
443
273
  if (abortControllerRef.current) {
444
274
  abortControllerRef.current.abort();
445
275
  abortControllerRef.current = null;
446
276
  }
447
277
  }, []);
448
- const setMessages = useCallback2(
278
+ const setMessages = useCallback(
449
279
  (messages2) => {
450
280
  if (typeof messages2 === "function") {
451
281
  messages2 = messages2(messagesRef.current);
@@ -456,7 +286,7 @@ function useChat({
456
286
  },
457
287
  [mutate]
458
288
  );
459
- const setData = useCallback2(
289
+ const setData = useCallback(
460
290
  (data) => {
461
291
  if (typeof data === "function") {
462
292
  data = data(streamDataRef.current);
@@ -466,8 +296,8 @@ function useChat({
466
296
  },
467
297
  [mutateStreamData]
468
298
  );
469
- const [input, setInput] = useState3(initialInput);
470
- const handleSubmit = useCallback2(
299
+ const [input, setInput] = useState2(initialInput);
300
+ const handleSubmit = useCallback(
471
301
  async (event, options = {}, metadata) => {
472
302
  var _a;
473
303
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
@@ -483,7 +313,7 @@ function useChat({
483
313
  options.experimental_attachments
484
314
  );
485
315
  const messages2 = messagesRef.current.concat({
486
- id: generateId2(),
316
+ id: generateId(),
487
317
  createdAt: /* @__PURE__ */ new Date(),
488
318
  role: "user",
489
319
  content: input,
@@ -499,12 +329,12 @@ function useChat({
499
329
  triggerRequest(chatRequest);
500
330
  setInput("");
501
331
  },
502
- [input, generateId2, triggerRequest]
332
+ [input, generateId, triggerRequest]
503
333
  );
504
334
  const handleInputChange = (e) => {
505
335
  setInput(e.target.value);
506
336
  };
507
- const addToolResult = useCallback2(
337
+ const addToolResult = useCallback(
508
338
  ({ toolCallId, result }) => {
509
339
  const currentMessages = messagesRef.current;
510
340
  updateToolCallResult({
@@ -512,13 +342,22 @@ function useChat({
512
342
  toolCallId,
513
343
  toolResult: result
514
344
  });
515
- mutate(currentMessages, false);
345
+ mutate(
346
+ [
347
+ ...currentMessages.slice(0, currentMessages.length - 1),
348
+ { ...currentMessages[currentMessages.length - 1] }
349
+ ],
350
+ false
351
+ );
352
+ if (status === "submitted" || status === "streaming") {
353
+ return;
354
+ }
516
355
  const lastMessage = currentMessages[currentMessages.length - 1];
517
356
  if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
518
357
  triggerRequest({ messages: currentMessages });
519
358
  }
520
359
  },
521
- [mutate, triggerRequest]
360
+ [mutate, status, triggerRequest]
522
361
  );
523
362
  return {
524
363
  messages: messages != null ? messages : [],
@@ -544,7 +383,7 @@ function useChat({
544
383
  import {
545
384
  callCompletionApi
546
385
  } from "@ai-sdk/ui-utils";
547
- import { useCallback as useCallback3, useEffect as useEffect3, useId, useRef as useRef3, useState as useState4 } from "react";
386
+ import { useCallback as useCallback2, useEffect as useEffect3, useId, useRef as useRef2, useState as useState3 } from "react";
548
387
  import useSWR2 from "swr";
549
388
  function useCompletion({
550
389
  api = "/api/completion",
@@ -571,10 +410,10 @@ function useCompletion({
571
410
  null
572
411
  );
573
412
  const { data: streamData, mutate: mutateStreamData } = useSWR2([completionId, "streamData"], null);
574
- const [error, setError] = useState4(void 0);
413
+ const [error, setError] = useState3(void 0);
575
414
  const completion = data;
576
- const [abortController, setAbortController] = useState4(null);
577
- const extraMetadataRef = useRef3({
415
+ const [abortController, setAbortController] = useState3(null);
416
+ const extraMetadataRef = useRef2({
578
417
  credentials,
579
418
  headers,
580
419
  body
@@ -586,7 +425,7 @@ function useCompletion({
586
425
  body
587
426
  };
588
427
  }, [credentials, headers, body]);
589
- const triggerRequest = useCallback3(
428
+ const triggerRequest = useCallback2(
590
429
  async (prompt, options) => callCompletionApi({
591
430
  api,
592
431
  prompt,
@@ -631,26 +470,26 @@ function useCompletion({
631
470
  throttleWaitMs
632
471
  ]
633
472
  );
634
- const stop = useCallback3(() => {
473
+ const stop = useCallback2(() => {
635
474
  if (abortController) {
636
475
  abortController.abort();
637
476
  setAbortController(null);
638
477
  }
639
478
  }, [abortController]);
640
- const setCompletion = useCallback3(
479
+ const setCompletion = useCallback2(
641
480
  (completion2) => {
642
481
  mutate(completion2, false);
643
482
  },
644
483
  [mutate]
645
484
  );
646
- const complete = useCallback3(
485
+ const complete = useCallback2(
647
486
  async (prompt, options) => {
648
487
  return triggerRequest(prompt, options);
649
488
  },
650
489
  [triggerRequest]
651
490
  );
652
- const [input, setInput] = useState4(initialInput);
653
- const handleSubmit = useCallback3(
491
+ const [input, setInput] = useState3(initialInput);
492
+ const handleSubmit = useCallback2(
654
493
  (event) => {
655
494
  var _a;
656
495
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
@@ -658,7 +497,7 @@ function useCompletion({
658
497
  },
659
498
  [input, complete]
660
499
  );
661
- const handleInputChange = useCallback3(
500
+ const handleInputChange = useCallback2(
662
501
  (e) => {
663
502
  setInput(e.target.value);
664
503
  },
@@ -681,7 +520,7 @@ function useCompletion({
681
520
 
682
521
  // src/use-object.ts
683
522
  import {
684
- isAbortError as isAbortError2,
523
+ isAbortError,
685
524
  safeValidateTypes
686
525
  } from "@ai-sdk/provider-utils";
687
526
  import {
@@ -689,9 +528,9 @@ import {
689
528
  isDeepEqualData as isDeepEqualData2,
690
529
  parsePartialJson
691
530
  } from "@ai-sdk/ui-utils";
692
- import { useCallback as useCallback4, useId as useId2, useRef as useRef4, useState as useState5 } from "react";
531
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState4 } from "react";
693
532
  import useSWR3 from "swr";
694
- var getOriginalFetch2 = () => fetch;
533
+ var getOriginalFetch = () => fetch;
695
534
  function useObject({
696
535
  api,
697
536
  id,
@@ -711,10 +550,10 @@ function useObject({
711
550
  null,
712
551
  { fallbackData: initialValue }
713
552
  );
714
- const [error, setError] = useState5(void 0);
715
- const [isLoading, setIsLoading] = useState5(false);
716
- const abortControllerRef = useRef4(null);
717
- const stop = useCallback4(() => {
553
+ const [error, setError] = useState4(void 0);
554
+ const [isLoading, setIsLoading] = useState4(false);
555
+ const abortControllerRef = useRef3(null);
556
+ const stop = useCallback3(() => {
718
557
  var _a;
719
558
  try {
720
559
  (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
@@ -732,7 +571,7 @@ function useObject({
732
571
  setError(void 0);
733
572
  const abortController = new AbortController();
734
573
  abortControllerRef.current = abortController;
735
- const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch2();
574
+ const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
736
575
  const response = await actualFetch(api, {
737
576
  method: "POST",
738
577
  headers: {
@@ -780,7 +619,7 @@ function useObject({
780
619
  })
781
620
  );
782
621
  } catch (error2) {
783
- if (isAbortError2(error2)) {
622
+ if (isAbortError(error2)) {
784
623
  return;
785
624
  }
786
625
  if (onError && error2 instanceof Error) {
@@ -801,7 +640,6 @@ function useObject({
801
640
  var experimental_useObject = useObject;
802
641
  export {
803
642
  experimental_useObject,
804
- useAssistant,
805
643
  useChat,
806
644
  useCompletion
807
645
  };