@ai-sdk/react 2.0.0-canary.19 → 2.0.0-canary.20

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 2.0.0-canary.20
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [d964901]
8
+ - Updated dependencies [0560977]
9
+ - Updated dependencies [66af894]
10
+ - Updated dependencies [516be5b]
11
+ - Updated dependencies [bfbfc4c]
12
+ - Updated dependencies [ea7a7c9]
13
+ - Updated dependencies [1409e13]
14
+ - ai@5.0.0-canary.21
15
+ - @ai-sdk/provider-utils@3.0.0-canary.17
16
+
3
17
  ## 2.0.0-canary.19
4
18
 
5
19
  ### Major Changes
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
- import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, JSONValue, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, JSONValue, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
3
  import { FetchFunction } from '@ai-sdk/provider-utils';
4
4
  import z from 'zod';
5
5
 
6
- type UseChatHelpers = {
6
+ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
7
7
  /** Current messages in the chat */
8
- messages: UIMessage[];
8
+ messages: UIMessage<MESSAGE_METADATA>[];
9
9
  /** The error object of the API request */
10
10
  error: undefined | Error;
11
11
  /**
@@ -14,7 +14,7 @@ type UseChatHelpers = {
14
14
  * @param message The message to append
15
15
  * @param options Additional options to pass to the API call
16
16
  */
17
- append: (message: UIMessage | CreateUIMessage, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
17
+ append: (message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
18
18
  /**
19
19
  * Reload the last AI chat response for the given chat history. If the last
20
20
  * message isn't from the assistant, it will request the API to generate a
@@ -34,7 +34,7 @@ type UseChatHelpers = {
34
34
  * edit the messages on the client, and then trigger the `reload` method
35
35
  * manually to regenerate the AI response.
36
36
  */
37
- setMessages: (messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => void;
37
+ setMessages: (messages: UIMessage<MESSAGE_METADATA>[] | ((messages: UIMessage<MESSAGE_METADATA>[]) => UIMessage<MESSAGE_METADATA>[])) => void;
38
38
  /** The current value of the input */
39
39
  input: string;
40
40
  /** setState-powered method to update the input value */
@@ -63,10 +63,6 @@ type UseChatHelpers = {
63
63
  * - `error`: An error occurred during the API request, preventing successful completion.
64
64
  */
65
65
  status: 'submitted' | 'streaming' | 'ready' | 'error';
66
- /** Additional data added on the server via StreamData. */
67
- data?: JSONValue[];
68
- /** Set the data of the chat. You can use this to transform or clear the chat data. */
69
- setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
70
66
  addToolResult: ({ toolCallId, result, }: {
71
67
  toolCallId: string;
72
68
  result: any;
@@ -74,8 +70,7 @@ type UseChatHelpers = {
74
70
  /** The id of the chat */
75
71
  id: string;
76
72
  };
77
- declare function useChat({ api, id, initialMessages, initialInput, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, experimental_throttle: throttleWaitMs, ...options }?: UseChatOptions & {
78
- key?: string;
73
+ declare function useChat<MESSAGE_METADATA>({ api, id, initialMessages, initialInput, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, experimental_throttle: throttleWaitMs, messageMetadataSchema, }?: UseChatOptions<MESSAGE_METADATA> & {
79
74
  /**
80
75
  * Experimental (React only). When a function is provided, it will be used
81
76
  * to prepare the request body for the chat API. This can be useful for
@@ -96,10 +91,7 @@ declare function useChat({ api, id, initialMessages, initialInput, onToolCall, e
96
91
  Default is undefined, which disables throttling.
97
92
  */
98
93
  experimental_throttle?: number;
99
- '~internal'?: {
100
- currentDate?: () => Date;
101
- };
102
- }): UseChatHelpers;
94
+ }): UseChatHelpers<MESSAGE_METADATA>;
103
95
 
104
96
  type UseCompletionHelpers = {
105
97
  /** The current completion result */
@@ -144,8 +136,6 @@ type UseCompletionHelpers = {
144
136
  }) => void;
145
137
  /** Whether the API request is in progress */
146
138
  isLoading: boolean;
147
- /** Additional data added on the server via StreamData */
148
- data?: JSONValue[];
149
139
  };
150
140
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onResponse, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
151
141
  /**
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, JSONValue, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, JSONValue, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
3
  import { FetchFunction } from '@ai-sdk/provider-utils';
4
4
  import z from 'zod';
5
5
 
6
- type UseChatHelpers = {
6
+ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
7
7
  /** Current messages in the chat */
8
- messages: UIMessage[];
8
+ messages: UIMessage<MESSAGE_METADATA>[];
9
9
  /** The error object of the API request */
10
10
  error: undefined | Error;
11
11
  /**
@@ -14,7 +14,7 @@ type UseChatHelpers = {
14
14
  * @param message The message to append
15
15
  * @param options Additional options to pass to the API call
16
16
  */
17
- append: (message: UIMessage | CreateUIMessage, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
17
+ append: (message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
18
18
  /**
19
19
  * Reload the last AI chat response for the given chat history. If the last
20
20
  * message isn't from the assistant, it will request the API to generate a
@@ -34,7 +34,7 @@ type UseChatHelpers = {
34
34
  * edit the messages on the client, and then trigger the `reload` method
35
35
  * manually to regenerate the AI response.
36
36
  */
37
- setMessages: (messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => void;
37
+ setMessages: (messages: UIMessage<MESSAGE_METADATA>[] | ((messages: UIMessage<MESSAGE_METADATA>[]) => UIMessage<MESSAGE_METADATA>[])) => void;
38
38
  /** The current value of the input */
39
39
  input: string;
40
40
  /** setState-powered method to update the input value */
@@ -63,10 +63,6 @@ type UseChatHelpers = {
63
63
  * - `error`: An error occurred during the API request, preventing successful completion.
64
64
  */
65
65
  status: 'submitted' | 'streaming' | 'ready' | 'error';
66
- /** Additional data added on the server via StreamData. */
67
- data?: JSONValue[];
68
- /** Set the data of the chat. You can use this to transform or clear the chat data. */
69
- setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
70
66
  addToolResult: ({ toolCallId, result, }: {
71
67
  toolCallId: string;
72
68
  result: any;
@@ -74,8 +70,7 @@ type UseChatHelpers = {
74
70
  /** The id of the chat */
75
71
  id: string;
76
72
  };
77
- declare function useChat({ api, id, initialMessages, initialInput, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, experimental_throttle: throttleWaitMs, ...options }?: UseChatOptions & {
78
- key?: string;
73
+ declare function useChat<MESSAGE_METADATA>({ api, id, initialMessages, initialInput, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, experimental_throttle: throttleWaitMs, messageMetadataSchema, }?: UseChatOptions<MESSAGE_METADATA> & {
79
74
  /**
80
75
  * Experimental (React only). When a function is provided, it will be used
81
76
  * to prepare the request body for the chat API. This can be useful for
@@ -96,10 +91,7 @@ declare function useChat({ api, id, initialMessages, initialInput, onToolCall, e
96
91
  Default is undefined, which disables throttling.
97
92
  */
98
93
  experimental_throttle?: number;
99
- '~internal'?: {
100
- currentDate?: () => Date;
101
- };
102
- }): UseChatHelpers;
94
+ }): UseChatHelpers<MESSAGE_METADATA>;
103
95
 
104
96
  type UseCompletionHelpers = {
105
97
  /** The current completion result */
@@ -144,8 +136,6 @@ type UseCompletionHelpers = {
144
136
  }) => void;
145
137
  /** Whether the API request is in progress */
146
138
  isLoading: boolean;
147
- /** Additional data added on the server via StreamData */
148
- data?: JSONValue[];
149
139
  };
150
140
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onResponse, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
151
141
  /**
package/dist/index.js CHANGED
@@ -79,12 +79,8 @@ function useChat({
79
79
  generateId = import_ai2.generateId,
80
80
  fetch: fetch2,
81
81
  experimental_throttle: throttleWaitMs,
82
- ...options
82
+ messageMetadataSchema
83
83
  } = {}) {
84
- const getCurrentDate = (0, import_react2.useCallback)(() => {
85
- var _a, _b, _c;
86
- return (_c = (_b = (_a = options["~internal"]) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
87
- }, [options]);
88
84
  const [hookId] = (0, import_react2.useState)(generateId);
89
85
  const chatId = id != null ? id : hookId;
90
86
  const chatKey = typeof api === "string" ? [api, chatId] : chatId;
@@ -102,11 +98,6 @@ function useChat({
102
98
  (0, import_react2.useEffect)(() => {
103
99
  messagesRef.current = messages || [];
104
100
  }, [messages]);
105
- const { data: streamData, mutate: mutateStreamData } = (0, import_swr.default)([chatKey, "streamData"], null);
106
- const streamDataRef = (0, import_react2.useRef)(streamData);
107
- (0, import_react2.useEffect)(() => {
108
- streamDataRef.current = streamData;
109
- }, [streamData]);
110
101
  const { data: status = "ready", mutate: mutateStatus } = (0, import_swr.default)([chatKey, "status"], null);
111
102
  const { data: error = void 0, mutate: setError } = (0, import_swr.default)([chatKey, "error"], null);
112
103
  const abortControllerRef = (0, import_react2.useRef)(null);
@@ -136,12 +127,7 @@ function useChat({
136
127
  const abortController = new AbortController();
137
128
  abortControllerRef.current = abortController;
138
129
  const throttledMutate = throttle(mutate, throttleWaitMs);
139
- const throttledMutateStreamData = throttle(
140
- mutateStreamData,
141
- throttleWaitMs
142
- );
143
130
  throttledMutate(chatMessages, false);
144
- const existingData = streamDataRef.current;
145
131
  await (0, import_ai2.callChatApi)({
146
132
  api,
147
133
  body: (_a = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
@@ -164,8 +150,9 @@ function useChat({
164
150
  },
165
151
  abortController: () => abortControllerRef.current,
166
152
  onResponse,
167
- onUpdate({ message, data, replaceLastMessage }) {
153
+ onUpdate({ message }) {
168
154
  mutateStatus("streaming");
155
+ const replaceLastMessage = message.id === chatMessages[chatMessages.length - 1].id;
169
156
  throttledMutate(
170
157
  [
171
158
  ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
@@ -173,20 +160,14 @@ function useChat({
173
160
  ],
174
161
  false
175
162
  );
176
- if (data == null ? void 0 : data.length) {
177
- throttledMutateStreamData(
178
- [...existingData != null ? existingData : [], ...data],
179
- false
180
- );
181
- }
182
163
  },
183
164
  onToolCall,
184
165
  onFinish,
185
166
  generateId,
186
167
  fetch: fetch2,
187
168
  lastMessage: chatMessages[chatMessages.length - 1],
188
- getCurrentDate,
189
- requestType
169
+ requestType,
170
+ messageMetadataSchema
190
171
  });
191
172
  abortControllerRef.current = null;
192
173
  mutateStatus("ready");
@@ -221,8 +202,6 @@ function useChat({
221
202
  onFinish,
222
203
  onError,
223
204
  setError,
224
- mutateStreamData,
225
- streamDataRef,
226
205
  streamProtocol,
227
206
  experimental_prepareRequestBody,
228
207
  onToolCall,
@@ -233,24 +212,23 @@ function useChat({
233
212
  fetch2,
234
213
  throttleWaitMs,
235
214
  chatId,
236
- getCurrentDate
215
+ messageMetadataSchema
237
216
  ]
238
217
  );
239
218
  const append = (0, import_react2.useCallback)(
240
219
  (message, { data, headers: headers2, body: body2 } = {}) => {
241
- var _a, _b;
220
+ var _a;
242
221
  return triggerRequest({
243
222
  messages: messagesRef.current.concat({
244
223
  ...message,
245
- id: (_a = message.id) != null ? _a : generateId(),
246
- createdAt: (_b = message.createdAt) != null ? _b : getCurrentDate()
224
+ id: (_a = message.id) != null ? _a : generateId()
247
225
  }),
248
226
  headers: headers2,
249
227
  body: body2,
250
228
  data
251
229
  });
252
230
  },
253
- [triggerRequest, generateId, getCurrentDate]
231
+ [triggerRequest, generateId]
254
232
  );
255
233
  const reload = (0, import_react2.useCallback)(
256
234
  async ({ data, headers: headers2, body: body2 } = {}) => {
@@ -288,22 +266,12 @@ function useChat({
288
266
  },
289
267
  [mutate]
290
268
  );
291
- const setData = (0, import_react2.useCallback)(
292
- (data) => {
293
- if (typeof data === "function") {
294
- data = data(streamDataRef.current);
295
- }
296
- mutateStreamData(data, false);
297
- streamDataRef.current = data;
298
- },
299
- [mutateStreamData]
300
- );
301
269
  const [input, setInput] = (0, import_react2.useState)(initialInput);
302
270
  const handleSubmit = (0, import_react2.useCallback)(
303
- async (event, options2 = {}, metadata) => {
271
+ async (event, options = {}, metadata) => {
304
272
  var _a;
305
273
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
306
- if (!input && !options2.allowEmptySubmit)
274
+ if (!input && !options.allowEmptySubmit)
307
275
  return;
308
276
  if (metadata) {
309
277
  extraMetadataRef.current = {
@@ -311,21 +279,21 @@ function useChat({
311
279
  ...metadata
312
280
  };
313
281
  }
314
- const fileParts = Array.isArray(options2 == null ? void 0 : options2.files) ? options2.files : await (0, import_ai2.convertFileListToFileUIParts)(options2 == null ? void 0 : options2.files);
282
+ const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await (0, import_ai2.convertFileListToFileUIParts)(options == null ? void 0 : options.files);
315
283
  triggerRequest({
316
284
  messages: messagesRef.current.concat({
317
285
  id: generateId(),
318
- createdAt: getCurrentDate(),
319
286
  role: "user",
287
+ metadata: void 0,
320
288
  parts: [...fileParts, { type: "text", text: input }]
321
289
  }),
322
- headers: options2.headers,
323
- body: options2.body,
324
- data: options2.data
290
+ headers: options.headers,
291
+ body: options.body,
292
+ data: options.data
325
293
  });
326
294
  setInput("");
327
295
  },
328
- [input, generateId, triggerRequest, getCurrentDate]
296
+ [input, generateId, triggerRequest]
329
297
  );
330
298
  const handleInputChange = (e) => {
331
299
  setInput(e.target.value);
@@ -364,8 +332,6 @@ function useChat({
364
332
  messages: messages != null ? messages : [],
365
333
  id: chatId,
366
334
  setMessages,
367
- data: streamData,
368
- setData,
369
335
  error,
370
336
  append,
371
337
  reload,
@@ -409,7 +375,6 @@ function useCompletion({
409
375
  [completionId, "loading"],
410
376
  null
411
377
  );
412
- const { data: streamData, mutate: mutateStreamData } = (0, import_swr2.default)([completionId, "streamData"], null);
413
378
  const [error, setError] = (0, import_react3.useState)(void 0);
414
379
  const completion = data;
415
380
  const [abortController, setAbortController] = (0, import_react3.useState)(null);
@@ -442,10 +407,6 @@ function useCompletion({
442
407
  (completion2) => mutate(completion2, false),
443
408
  throttleWaitMs
444
409
  ),
445
- onData: throttle(
446
- (data2) => mutateStreamData([...streamData != null ? streamData : [], ...data2 != null ? data2 : []], false),
447
- throttleWaitMs
448
- ),
449
410
  setLoading: mutateLoading,
450
411
  setError,
451
412
  setAbortController,
@@ -463,10 +424,8 @@ function useCompletion({
463
424
  onFinish,
464
425
  onError,
465
426
  setError,
466
- streamData,
467
427
  streamProtocol,
468
428
  fetch2,
469
- mutateStreamData,
470
429
  throttleWaitMs
471
430
  ]
472
431
  );
@@ -513,8 +472,7 @@ function useCompletion({
513
472
  setInput,
514
473
  handleInputChange,
515
474
  handleSubmit,
516
- isLoading,
517
- data: streamData
475
+ isLoading
518
476
  };
519
477
  }
520
478
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n JSONValue,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n convertFileListToFileUIParts,\n extractMaxToolInvocationStep,\n generateId as generateIdFunc,\n getToolInvocations,\n isAssistantMessageWithCompletedToolCalls,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: UIMessage | CreateUIMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[]),\n ) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n experimental_throttle: throttleWaitMs,\n ...options\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n '~internal'?: {\n currentDate?: () => Date;\n };\n} = {}): UseChatHelpers {\n // allow overriding the current date for testing purposes:\n const getCurrentDate = useCallback(() => {\n return options['~internal']?.currentDate?.() ?? new Date();\n }, [options]);\n\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => stableInitialMessages,\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (\n chatRequest: {\n headers?: Record<string, string> | Headers;\n body?: object;\n messages: UIMessage[];\n data?: JSONValue;\n },\n requestType: 'generate' | 'resume' = 'generate',\n ) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = chatRequest.messages;\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n getToolInvocations(chatMessages[chatMessages.length - 1]),\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to show the updated messages immediately:\n throttledMutate(chatMessages, false);\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: chatMessages,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n getCurrentDate,\n requestType,\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n throttleWaitMs,\n chatId,\n getCurrentDate,\n ],\n );\n\n const append = useCallback(\n (\n message: UIMessage | CreateUIMessage,\n { data, headers, body }: ChatRequestOptions = {},\n ) =>\n triggerRequest({\n messages: messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? getCurrentDate(),\n }),\n headers,\n body,\n data,\n }),\n [triggerRequest, generateId, getCurrentDate],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const experimental_resume = useCallback(async () => {\n const messages = messagesRef.current;\n\n triggerRequest({ messages }, 'resume');\n }, [triggerRequest]);\n\n const setMessages = useCallback(\n (messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n mutate(messages, false);\n messagesRef.current = messages;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n triggerRequest({\n messages: messagesRef.current.concat({\n id: generateId(),\n createdAt: getCurrentDate(),\n role: 'user',\n parts: [...fileParts, { type: 'text', text: input }],\n }),\n headers: options.headers,\n body: options.body,\n data: options.data,\n });\n\n setInput('');\n },\n [input, generateId, triggerRequest, getCurrentDate],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n {\n ...currentMessages[currentMessages.length - 1],\n // @ts-ignore\n // update the revisionId to trigger a re-render\n revisionId: generateId(),\n },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest, generateId],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n CompletionRequestOptions,\n JSONValue,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n /** Additional data added on the server via StreamData */\n data?: JSONValue[];\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onResponse,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n data: streamData,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA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;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASE,QAAO;AACd,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["import_ai","import_react","throttleFunction","generateIdFunc","fetch","useSWR","messages","headers","body","options","import_ai","import_react","import_swr","fetch","useSWR","completion","data","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n JSONValue,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n convertFileListToFileUIParts,\n extractMaxToolInvocationStep,\n generateId as generateIdFunc,\n getToolInvocations,\n isAssistantMessageWithCompletedToolCalls,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<MESSAGE_METADATA = unknown> = {\n /** Current messages in the chat */\n messages: UIMessage<MESSAGE_METADATA>[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat<MESSAGE_METADATA>({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n experimental_throttle: throttleWaitMs,\n messageMetadataSchema,\n}: UseChatOptions<MESSAGE_METADATA> & {\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA> {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => stableInitialMessages,\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage<MESSAGE_METADATA>[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage<MESSAGE_METADATA>[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (\n chatRequest: {\n headers?: Record<string, string> | Headers;\n body?: object;\n messages: UIMessage<MESSAGE_METADATA>[];\n data?: JSONValue;\n },\n requestType: 'generate' | 'resume' = 'generate',\n ) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = chatRequest.messages;\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n getToolInvocations(chatMessages[chatMessages.length - 1]),\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n\n // Do an optimistic update to show the updated messages immediately:\n throttledMutate(chatMessages, false);\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: chatMessages,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n onResponse,\n onUpdate({ message }) {\n mutateStatus('streaming');\n\n const replaceLastMessage =\n message.id === chatMessages[chatMessages.length - 1].id;\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n requestType,\n messageMetadataSchema,\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n streamProtocol,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n throttleWaitMs,\n chatId,\n messageMetadataSchema,\n ],\n );\n\n const append = useCallback(\n (\n message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>,\n { data, headers, body }: ChatRequestOptions = {},\n ) =>\n triggerRequest({\n messages: messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n }),\n headers,\n body,\n data,\n }),\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const experimental_resume = useCallback(async () => {\n const messages = messagesRef.current;\n\n triggerRequest({ messages }, 'resume');\n }, [triggerRequest]);\n\n const setMessages = useCallback(\n (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n mutate(messages, false);\n messagesRef.current = messages;\n },\n [mutate],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n triggerRequest({\n messages: messagesRef.current.concat({\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n }),\n headers: options.headers,\n body: options.body,\n data: options.data,\n });\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n {\n ...currentMessages[currentMessages.length - 1],\n // @ts-ignore\n // update the revisionId to trigger a re-render\n revisionId: generateId(),\n },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest, generateId],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onResponse,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,IAAAA,aASO;AACP,IAAAC,gBAAkE;AAClE,iBAAmB;;;ACnBnB,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAC,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,gBAAgC;AAChC,mBAAoC;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAY,WAAW;AAEjD,8BAAU,MAAM;AACd,QAAI,KAAC,2BA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;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["import_ai","import_react","throttleFunction","generateIdFunc","fetch","useSWR","messages","headers","body","import_ai","import_react","import_swr","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -50,12 +50,8 @@ function useChat({
50
50
  generateId = generateIdFunc,
51
51
  fetch: fetch2,
52
52
  experimental_throttle: throttleWaitMs,
53
- ...options
53
+ messageMetadataSchema
54
54
  } = {}) {
55
- const getCurrentDate = useCallback(() => {
56
- var _a, _b, _c;
57
- return (_c = (_b = (_a = options["~internal"]) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
58
- }, [options]);
59
55
  const [hookId] = useState2(generateId);
60
56
  const chatId = id != null ? id : hookId;
61
57
  const chatKey = typeof api === "string" ? [api, chatId] : chatId;
@@ -73,11 +69,6 @@ function useChat({
73
69
  useEffect2(() => {
74
70
  messagesRef.current = messages || [];
75
71
  }, [messages]);
76
- const { data: streamData, mutate: mutateStreamData } = useSWR([chatKey, "streamData"], null);
77
- const streamDataRef = useRef(streamData);
78
- useEffect2(() => {
79
- streamDataRef.current = streamData;
80
- }, [streamData]);
81
72
  const { data: status = "ready", mutate: mutateStatus } = useSWR([chatKey, "status"], null);
82
73
  const { data: error = void 0, mutate: setError } = useSWR([chatKey, "error"], null);
83
74
  const abortControllerRef = useRef(null);
@@ -107,12 +98,7 @@ function useChat({
107
98
  const abortController = new AbortController();
108
99
  abortControllerRef.current = abortController;
109
100
  const throttledMutate = throttle(mutate, throttleWaitMs);
110
- const throttledMutateStreamData = throttle(
111
- mutateStreamData,
112
- throttleWaitMs
113
- );
114
101
  throttledMutate(chatMessages, false);
115
- const existingData = streamDataRef.current;
116
102
  await callChatApi({
117
103
  api,
118
104
  body: (_a = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
@@ -135,8 +121,9 @@ function useChat({
135
121
  },
136
122
  abortController: () => abortControllerRef.current,
137
123
  onResponse,
138
- onUpdate({ message, data, replaceLastMessage }) {
124
+ onUpdate({ message }) {
139
125
  mutateStatus("streaming");
126
+ const replaceLastMessage = message.id === chatMessages[chatMessages.length - 1].id;
140
127
  throttledMutate(
141
128
  [
142
129
  ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
@@ -144,20 +131,14 @@ function useChat({
144
131
  ],
145
132
  false
146
133
  );
147
- if (data == null ? void 0 : data.length) {
148
- throttledMutateStreamData(
149
- [...existingData != null ? existingData : [], ...data],
150
- false
151
- );
152
- }
153
134
  },
154
135
  onToolCall,
155
136
  onFinish,
156
137
  generateId,
157
138
  fetch: fetch2,
158
139
  lastMessage: chatMessages[chatMessages.length - 1],
159
- getCurrentDate,
160
- requestType
140
+ requestType,
141
+ messageMetadataSchema
161
142
  });
162
143
  abortControllerRef.current = null;
163
144
  mutateStatus("ready");
@@ -192,8 +173,6 @@ function useChat({
192
173
  onFinish,
193
174
  onError,
194
175
  setError,
195
- mutateStreamData,
196
- streamDataRef,
197
176
  streamProtocol,
198
177
  experimental_prepareRequestBody,
199
178
  onToolCall,
@@ -204,24 +183,23 @@ function useChat({
204
183
  fetch2,
205
184
  throttleWaitMs,
206
185
  chatId,
207
- getCurrentDate
186
+ messageMetadataSchema
208
187
  ]
209
188
  );
210
189
  const append = useCallback(
211
190
  (message, { data, headers: headers2, body: body2 } = {}) => {
212
- var _a, _b;
191
+ var _a;
213
192
  return triggerRequest({
214
193
  messages: messagesRef.current.concat({
215
194
  ...message,
216
- id: (_a = message.id) != null ? _a : generateId(),
217
- createdAt: (_b = message.createdAt) != null ? _b : getCurrentDate()
195
+ id: (_a = message.id) != null ? _a : generateId()
218
196
  }),
219
197
  headers: headers2,
220
198
  body: body2,
221
199
  data
222
200
  });
223
201
  },
224
- [triggerRequest, generateId, getCurrentDate]
202
+ [triggerRequest, generateId]
225
203
  );
226
204
  const reload = useCallback(
227
205
  async ({ data, headers: headers2, body: body2 } = {}) => {
@@ -259,22 +237,12 @@ function useChat({
259
237
  },
260
238
  [mutate]
261
239
  );
262
- const setData = useCallback(
263
- (data) => {
264
- if (typeof data === "function") {
265
- data = data(streamDataRef.current);
266
- }
267
- mutateStreamData(data, false);
268
- streamDataRef.current = data;
269
- },
270
- [mutateStreamData]
271
- );
272
240
  const [input, setInput] = useState2(initialInput);
273
241
  const handleSubmit = useCallback(
274
- async (event, options2 = {}, metadata) => {
242
+ async (event, options = {}, metadata) => {
275
243
  var _a;
276
244
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
277
- if (!input && !options2.allowEmptySubmit)
245
+ if (!input && !options.allowEmptySubmit)
278
246
  return;
279
247
  if (metadata) {
280
248
  extraMetadataRef.current = {
@@ -282,21 +250,21 @@ function useChat({
282
250
  ...metadata
283
251
  };
284
252
  }
285
- const fileParts = Array.isArray(options2 == null ? void 0 : options2.files) ? options2.files : await convertFileListToFileUIParts(options2 == null ? void 0 : options2.files);
253
+ const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await convertFileListToFileUIParts(options == null ? void 0 : options.files);
286
254
  triggerRequest({
287
255
  messages: messagesRef.current.concat({
288
256
  id: generateId(),
289
- createdAt: getCurrentDate(),
290
257
  role: "user",
258
+ metadata: void 0,
291
259
  parts: [...fileParts, { type: "text", text: input }]
292
260
  }),
293
- headers: options2.headers,
294
- body: options2.body,
295
- data: options2.data
261
+ headers: options.headers,
262
+ body: options.body,
263
+ data: options.data
296
264
  });
297
265
  setInput("");
298
266
  },
299
- [input, generateId, triggerRequest, getCurrentDate]
267
+ [input, generateId, triggerRequest]
300
268
  );
301
269
  const handleInputChange = (e) => {
302
270
  setInput(e.target.value);
@@ -335,8 +303,6 @@ function useChat({
335
303
  messages: messages != null ? messages : [],
336
304
  id: chatId,
337
305
  setMessages,
338
- data: streamData,
339
- setData,
340
306
  error,
341
307
  append,
342
308
  reload,
@@ -382,7 +348,6 @@ function useCompletion({
382
348
  [completionId, "loading"],
383
349
  null
384
350
  );
385
- const { data: streamData, mutate: mutateStreamData } = useSWR2([completionId, "streamData"], null);
386
351
  const [error, setError] = useState3(void 0);
387
352
  const completion = data;
388
353
  const [abortController, setAbortController] = useState3(null);
@@ -415,10 +380,6 @@ function useCompletion({
415
380
  (completion2) => mutate(completion2, false),
416
381
  throttleWaitMs
417
382
  ),
418
- onData: throttle(
419
- (data2) => mutateStreamData([...streamData != null ? streamData : [], ...data2 != null ? data2 : []], false),
420
- throttleWaitMs
421
- ),
422
383
  setLoading: mutateLoading,
423
384
  setError,
424
385
  setAbortController,
@@ -436,10 +397,8 @@ function useCompletion({
436
397
  onFinish,
437
398
  onError,
438
399
  setError,
439
- streamData,
440
400
  streamProtocol,
441
401
  fetch2,
442
- mutateStreamData,
443
402
  throttleWaitMs
444
403
  ]
445
404
  );
@@ -486,8 +445,7 @@ function useCompletion({
486
445
  setInput,
487
446
  handleInputChange,
488
447
  handleSubmit,
489
- isLoading,
490
- data: streamData
448
+ isLoading
491
449
  };
492
450
  }
493
451
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n JSONValue,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n convertFileListToFileUIParts,\n extractMaxToolInvocationStep,\n generateId as generateIdFunc,\n getToolInvocations,\n isAssistantMessageWithCompletedToolCalls,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: UIMessage | CreateUIMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[]),\n ) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n experimental_throttle: throttleWaitMs,\n ...options\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n '~internal'?: {\n currentDate?: () => Date;\n };\n} = {}): UseChatHelpers {\n // allow overriding the current date for testing purposes:\n const getCurrentDate = useCallback(() => {\n return options['~internal']?.currentDate?.() ?? new Date();\n }, [options]);\n\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => stableInitialMessages,\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (\n chatRequest: {\n headers?: Record<string, string> | Headers;\n body?: object;\n messages: UIMessage[];\n data?: JSONValue;\n },\n requestType: 'generate' | 'resume' = 'generate',\n ) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = chatRequest.messages;\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n getToolInvocations(chatMessages[chatMessages.length - 1]),\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to show the updated messages immediately:\n throttledMutate(chatMessages, false);\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: chatMessages,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n getCurrentDate,\n requestType,\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n throttleWaitMs,\n chatId,\n getCurrentDate,\n ],\n );\n\n const append = useCallback(\n (\n message: UIMessage | CreateUIMessage,\n { data, headers, body }: ChatRequestOptions = {},\n ) =>\n triggerRequest({\n messages: messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? getCurrentDate(),\n }),\n headers,\n body,\n data,\n }),\n [triggerRequest, generateId, getCurrentDate],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const experimental_resume = useCallback(async () => {\n const messages = messagesRef.current;\n\n triggerRequest({ messages }, 'resume');\n }, [triggerRequest]);\n\n const setMessages = useCallback(\n (messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n mutate(messages, false);\n messagesRef.current = messages;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n triggerRequest({\n messages: messagesRef.current.concat({\n id: generateId(),\n createdAt: getCurrentDate(),\n role: 'user',\n parts: [...fileParts, { type: 'text', text: input }],\n }),\n headers: options.headers,\n body: options.body,\n data: options.data,\n });\n\n setInput('');\n },\n [input, generateId, triggerRequest, getCurrentDate],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n {\n ...currentMessages[currentMessages.length - 1],\n // @ts-ignore\n // update the revisionId to trigger a re-render\n revisionId: generateId(),\n },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest, generateId],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n CompletionRequestOptions,\n JSONValue,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n /** Additional data added on the server via StreamData */\n data?: JSONValue[];\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onResponse,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n data: streamData,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAAA,YAAW,SAAS,QAAQ,YAAAC,iBAAgB;AAClE,OAAO,YAAY;;;ACnBnB,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,SAAS,uBAAuB;AAChC,SAAS,WAAW,gBAAgB;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,WAAW;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,gBAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,aAAa,KAAK,CAAC;AAEvB,SAAO;AACT;;;AF4GO,SAAS,QAAQ;AAAA,EACtB,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,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AA,QAC7B;AAAA,MACF;AAEA,UAAI,SAAS,QAAQ,MAAM;AACzB,cAAM,IAAI,MAAM,6BAA6B;AAAA,MAC/C;AAEA,UAAI,kBAAkB;AACtB,UAAI,eAAgD;AAEpD,YAAM,SAAS,KAAK,YAAY,IAAI,kBAAkB,CAAC,EAAE;AAAA,QACvD,IAAI,eAAuB;AAAA,UACzB,MAAM,MAAM,OAAO;AACjB,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,MAAM,iBAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,CAACN,iBAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,MAAM,kBAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,QAAQ,SAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASO,QAAO;AACd,UAAI,aAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useEffect","useState","fetch","useState","useEffect","messages","headers","body","options","useCallback","useEffect","useRef","useState","useSWR","fetch","useSWR","useState","useRef","useEffect","useCallback","completion","data","isDeepEqualData","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n JSONValue,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n convertFileListToFileUIParts,\n extractMaxToolInvocationStep,\n generateId as generateIdFunc,\n getToolInvocations,\n isAssistantMessageWithCompletedToolCalls,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<MESSAGE_METADATA = unknown> = {\n /** Current messages in the chat */\n messages: UIMessage<MESSAGE_METADATA>[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat<MESSAGE_METADATA>({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n experimental_throttle: throttleWaitMs,\n messageMetadataSchema,\n}: UseChatOptions<MESSAGE_METADATA> & {\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA> {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => stableInitialMessages,\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage<MESSAGE_METADATA>[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage<MESSAGE_METADATA>[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (\n chatRequest: {\n headers?: Record<string, string> | Headers;\n body?: object;\n messages: UIMessage<MESSAGE_METADATA>[];\n data?: JSONValue;\n },\n requestType: 'generate' | 'resume' = 'generate',\n ) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = chatRequest.messages;\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n getToolInvocations(chatMessages[chatMessages.length - 1]),\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n\n // Do an optimistic update to show the updated messages immediately:\n throttledMutate(chatMessages, false);\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: chatMessages,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n onResponse,\n onUpdate({ message }) {\n mutateStatus('streaming');\n\n const replaceLastMessage =\n message.id === chatMessages[chatMessages.length - 1].id;\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n requestType,\n messageMetadataSchema,\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n streamProtocol,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n throttleWaitMs,\n chatId,\n messageMetadataSchema,\n ],\n );\n\n const append = useCallback(\n (\n message: UIMessage<MESSAGE_METADATA> | CreateUIMessage<MESSAGE_METADATA>,\n { data, headers, body }: ChatRequestOptions = {},\n ) =>\n triggerRequest({\n messages: messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n }),\n headers,\n body,\n data,\n }),\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const experimental_resume = useCallback(async () => {\n const messages = messagesRef.current;\n\n triggerRequest({ messages }, 'resume');\n }, [triggerRequest]);\n\n const setMessages = useCallback(\n (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n mutate(messages, false);\n messagesRef.current = messages;\n },\n [mutate],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n triggerRequest({\n messages: messagesRef.current.concat({\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n }),\n headers: options.headers,\n body: options.body,\n data: options.data,\n });\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n {\n ...currentMessages[currentMessages.length - 1],\n // @ts-ignore\n // update the revisionId to trigger a re-render\n revisionId: generateId(),\n },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest, generateId],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onResponse,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAAA,YAAW,SAAS,QAAQ,YAAAC,iBAAgB;AAClE,OAAO,YAAY;;;ACnBnB,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,SAAS,uBAAuB;AAChC,SAAS,WAAW,gBAAgB;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,WAAW;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,gBAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,aAAa,KAAK,CAAC;AAEvB,SAAO;AACT;;;AFqGO,SAAS,QAA0B;AAAA,EACxC,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb,OAAAC;AAAA,EACA,uBAAuB;AAAA,EACvB;AACF,IAsBI,CAAC,GA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,MAC/C;AAEA,UAAI,kBAAkB;AACtB,UAAI,eAAgD;AAEpD,YAAM,SAAS,KAAK,YAAY,IAAI,kBAAkB,CAAC,EAAE;AAAA,QACvD,IAAI,eAAuB;AAAA,UACzB,MAAM,MAAM,OAAO;AACjB,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,MAAM,iBAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,CAACN,iBAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,MAAM,kBAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,QAAQ,SAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASO,QAAO;AACd,UAAI,aAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useEffect","useState","fetch","useState","useEffect","messages","headers","body","useCallback","useEffect","useRef","useState","useSWR","fetch","useSWR","useState","useRef","useEffect","useCallback","completion","isDeepEqualData","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "2.0.0-canary.19",
3
+ "version": "2.0.0-canary.20",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "swr": "^2.2.5",
23
23
  "throttleit": "2.1.0",
24
- "ai": "5.0.0-canary.20",
25
- "@ai-sdk/provider-utils": "3.0.0-canary.16"
24
+ "ai": "5.0.0-canary.21",
25
+ "@ai-sdk/provider-utils": "3.0.0-canary.17"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@testing-library/jest-dom": "^6.6.3",