@ai-sdk/react 1.0.10 → 1.0.11

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,13 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 1.0.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 37f4510: feat (ui): expose useChat id and send it to the server
8
+ - Updated dependencies [37f4510]
9
+ - @ai-sdk/ui-utils@1.0.10
10
+
3
11
  ## 1.0.10
4
12
 
5
13
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -107,6 +107,8 @@ type UseChatHelpers = {
107
107
  data?: JSONValue[];
108
108
  /** Set the data of the chat. You can use this to transform or clear the chat data. */
109
109
  setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
110
+ /** The id of the chat */
111
+ id: string;
110
112
  };
111
113
  declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, experimental_throttle: throttleWaitMs, }?: UseChatOptions & {
112
114
  key?: string;
package/dist/index.d.ts CHANGED
@@ -107,6 +107,8 @@ type UseChatHelpers = {
107
107
  data?: JSONValue[];
108
108
  /** Set the data of the chat. You can use this to transform or clear the chat data. */
109
109
  setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
110
+ /** The id of the chat */
111
+ id: string;
110
112
  };
111
113
  declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, experimental_throttle: throttleWaitMs, }?: UseChatOptions & {
112
114
  key?: string;
package/dist/index.js CHANGED
@@ -213,7 +213,7 @@ function throttle(fn, waitMs) {
213
213
  }
214
214
 
215
215
  // src/use-chat.ts
216
- var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, existingDataRef, extraMetadataRef, messagesRef, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, experimental_prepareRequestBody, fetch2, keepLastMessageOnError) => {
216
+ var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, existingDataRef, extraMetadataRef, messagesRef, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, experimental_prepareRequestBody, fetch2, keepLastMessageOnError, id) => {
217
217
  var _a;
218
218
  const previousMessages = messagesRef.current;
219
219
  mutate(chatRequest.messages, false);
@@ -240,10 +240,12 @@ var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, e
240
240
  return await (0, import_ui_utils2.callChatApi)({
241
241
  api,
242
242
  body: (_a = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
243
+ id,
243
244
  messages: chatRequest.messages,
244
245
  requestData: chatRequest.data,
245
246
  requestBody: chatRequest.body
246
247
  })) != null ? _a : {
248
+ id,
247
249
  messages: constructedMessagesPayload,
248
250
  data: chatRequest.data,
249
251
  ...extraMetadataRef.current.body,
@@ -295,9 +297,9 @@ function useChat({
295
297
  keepLastMessageOnError = true,
296
298
  experimental_throttle: throttleWaitMs
297
299
  } = {}) {
298
- const hookId = (0, import_react2.useId)();
299
- const idKey = id != null ? id : hookId;
300
- const chatKey = typeof api === "string" ? [api, idKey] : idKey;
300
+ const [hookId] = (0, import_react2.useState)(generateId2);
301
+ const chatId = id != null ? id : hookId;
302
+ const chatKey = typeof api === "string" ? [api, chatId] : chatId;
301
303
  const [initialMessagesFallback] = (0, import_react2.useState)([]);
302
304
  const { data: messages, mutate } = (0, import_swr.default)(
303
305
  [chatKey, "messages"],
@@ -357,7 +359,8 @@ function useChat({
357
359
  sendExtraMessageFields,
358
360
  experimental_prepareRequestBody,
359
361
  fetch2,
360
- keepLastMessageOnError
362
+ keepLastMessageOnError,
363
+ chatId
361
364
  );
362
365
  abortControllerRef.current = null;
363
366
  } catch (err) {
@@ -406,7 +409,8 @@ function useChat({
406
409
  generateId2,
407
410
  fetch2,
408
411
  keepLastMessageOnError,
409
- throttleWaitMs
412
+ throttleWaitMs,
413
+ chatId
410
414
  ]
411
415
  );
412
416
  const append = (0, import_react2.useCallback)(
@@ -536,6 +540,7 @@ function useChat({
536
540
  };
537
541
  return {
538
542
  messages: messages || [],
543
+ id: chatId,
539
544
  setMessages,
540
545
  data: streamData,
541
546
  setData,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-assistant.ts","../src/use-chat.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-assistant';\nexport * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import { isAbortError } from '@ai-sdk/provider-utils';\nimport {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n generateId,\n processAssistantStream,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useRef, useState } from 'react';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Message[];\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * The current thread ID.\n */\n threadId: string | undefined;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n\n /**\n * The current value of the input field.\n */\n input: string;\n\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 requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\nAbort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * setState-powered method to update the input value.\n */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler that automatically resets the input field and appends a user message.\n */\n submitMessage: (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * The current status of the assistant. This can be used to show a loading indicator.\n */\n status: AssistantStatus;\n\n /**\n * The error thrown during the assistant message processing, if any.\n */\n error: undefined | Error;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n fetch,\n}: UseAssistantOptions): UseAssistantHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState('');\n const [currentThreadId, setCurrentThreadId] = useState<string | undefined>(\n undefined,\n );\n const [status, setStatus] = useState<AssistantStatus>('awaiting_message');\n const [error, setError] = useState<undefined | Error>(undefined);\n\n const handleInputChange = (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => {\n setInput(event.target.value);\n };\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n setStatus('in_progress');\n\n setMessages(messages => [\n ...messages,\n {\n ...message,\n id: message.id ?? generateId(),\n },\n ]);\n\n setInput('');\n\n const abortController = new AbortController();\n\n try {\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n credentials,\n signal: abortController.signal,\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify({\n ...body,\n // always use user-provided threadId when available:\n threadId: threadIdParam ?? currentThreadId ?? null,\n message: message.content,\n\n // optional request data:\n data: requestOptions?.data,\n }),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the assistant response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n },\n onTextPart(value) {\n // text delta - add to last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n return [\n ...messages.slice(0, messages.length - 1),\n {\n id: lastMessage.id,\n role: lastMessage.role,\n content: lastMessage.content + value,\n },\n ];\n });\n },\n onAssistantControlDataPart(value) {\n setCurrentThreadId(value.threadId);\n\n // set id of last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n },\n onErrorPart(value) {\n setError(new Error(value));\n },\n });\n } catch (error) {\n // Ignore abort errors as they are expected when the user cancels the request:\n if (isAbortError(error) && abortController.signal.aborted) {\n abortControllerRef.current = null;\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n abortControllerRef.current = null;\n setStatus('awaiting_message');\n }\n };\n\n const submitMessage = async (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (input === '') {\n return;\n }\n\n append({ role: 'user', content: input }, requestOptions);\n };\n\n const setThreadId = (threadId: string | undefined) => {\n setCurrentThreadId(threadId);\n setMessages([]);\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: currentThreadId,\n setThreadId,\n input,\n setInput,\n handleInputChange,\n submitMessage,\n status,\n error,\n stop,\n };\n}\n","import { FetchFunction } from '@ai-sdk/provider-utils';\nimport type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n IdGenerator,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n prepareAttachmentsForRequest,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR, { KeyedMutator } from 'swr';\nimport { throttle } from './throttle';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Message[];\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: Message | CreateMessage,\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 * 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: Message[] | ((messages: Message[]) => Message[]),\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 ) => void;\n metadata?: Object;\n /** Whether the API request is in progress */\n isLoading: boolean;\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\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\nconst processResponseStream = async (\n api: string,\n chatRequest: ChatRequest,\n mutate: KeyedMutator<Message[]>,\n mutateStreamData: KeyedMutator<JSONValue[] | undefined>,\n existingDataRef: React.MutableRefObject<JSONValue[] | undefined>,\n extraMetadataRef: React.MutableRefObject<any>,\n messagesRef: React.MutableRefObject<Message[]>,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n generateId: IdGenerator,\n streamProtocol: UseChatOptions['streamProtocol'],\n onFinish: UseChatOptions['onFinish'],\n onResponse: ((response: Response) => void | Promise<void>) | undefined,\n onToolCall: UseChatOptions['onToolCall'] | undefined,\n sendExtraMessageFields: boolean | undefined,\n experimental_prepareRequestBody:\n | ((options: {\n messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue)\n | undefined,\n fetch: FetchFunction | undefined,\n keepLastMessageOnError: boolean,\n) => {\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n mutate(chatRequest.messages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n }),\n );\n\n const existingData = existingDataRef.current;\n\n return await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n messages: chatRequest.messages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n messages: constructedMessagesPayload,\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 restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n mutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged], false);\n if (data?.length) {\n mutateStreamData([...(existingData ?? []), ...data], false);\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n });\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\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 keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\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 messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate a unique id for the chat if not provided.\n const hookId = useId();\n const idKey = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, idKey] : idKey;\n\n // Store a empty array as the initial messages\n // (instead of using a default parameter value that gets re-created each time)\n // to avoid re-renders:\n const [initialMessagesFallback] = useState([]);\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<Message[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: initialMessages ?? initialMessagesFallback },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<Message[]>(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 // We store loading state in another hook to sync loading states across hook invocations\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [chatKey, 'loading'],\n null,\n );\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 (chatRequest: ChatRequest) => {\n const messageCount = messagesRef.current.length;\n\n try {\n mutateLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n await processResponseStream(\n api,\n chatRequest,\n // throttle streamed ui updates:\n throttle(mutate, throttleWaitMs),\n throttle(mutateStreamData, throttleWaitMs),\n streamDataRef,\n extraMetadataRef,\n messagesRef,\n abortControllerRef,\n generateId,\n streamProtocol,\n onFinish,\n onResponse,\n onToolCall,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n fetch,\n keepLastMessageOnError,\n );\n\n abortControllerRef.current = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n } finally {\n mutateLoading(false);\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const messages = messagesRef.current;\n const lastMessage = messages[messages.length - 1];\n if (\n // ensure we actually have new messages (to prevent infinite loops in case of errors):\n messages.length > messageCount &&\n // ensure there is a last message:\n lastMessage != null &&\n // check if the feature is enabled:\n maxSteps > 1 &&\n // check that next step is possible:\n isAssistantMessageWithCompletedToolCalls(lastMessage) &&\n // limit the number of automatic steps:\n countTrailingAssistantMessages(messages) < maxSteps\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n });\n\n return triggerRequest({ messages, headers, body, 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 setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\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 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 attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages =\n !input && !attachmentsForRequest.length && options.allowEmptySubmit\n ? messagesRef.current\n : messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0\n ? attachmentsForRequest\n : undefined,\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\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 = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => {\n const updatedMessages = messagesRef.current.map((message, index, arr) =>\n // update the tool calls in the last assistant message:\n index === arr.length - 1 &&\n message.role === 'assistant' &&\n message.toolInvocations\n ? {\n ...message,\n toolInvocations: message.toolInvocations.map(toolInvocation =>\n toolInvocation.toolCallId === toolCallId\n ? {\n ...toolInvocation,\n result,\n state: 'result' as const,\n }\n : toolInvocation,\n ),\n }\n : message,\n );\n\n mutate(updatedMessages, false);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = updatedMessages[updatedMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: updatedMessages });\n }\n };\n\n return {\n messages: messages || [],\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n addToolResult,\n };\n}\n\n/**\nCheck if the message is an assistant message with completed tool calls.\nThe message must have at least one tool invocation and all tool invocations\nmust have a result.\n */\nfunction isAssistantMessageWithCompletedToolCalls(message: Message) {\n return (\n message.role === 'assistant' &&\n message.toolInvocations &&\n message.toolInvocations.length > 0 &&\n message.toolInvocations.every(toolInvocation => 'result' in toolInvocation)\n );\n}\n\n/**\nReturns the number of trailing assistant messages in the array.\n */\nfunction countTrailingAssistantMessages(messages: Message[]) {\n let count = 0;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n count++;\n } else {\n break;\n }\n }\n return count;\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 {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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?: RequestOptions) =>\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-sdk/ui-utils';\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\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}: 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 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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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;AAAA;;;ACAA,4BAA6B;AAC7B,sBAOO;AACP,mBAA8C;AAG9C,IAAM,mBAAmB,MAAM;AAiFxB,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AACF,GAA6C;AAC3C,QAAM,CAAC,UAAU,WAAW,QAAI,uBAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAS,EAAE;AACrC,QAAM,CAAC,iBAAiB,kBAAkB,QAAI;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,CAAC,QAAQ,SAAS,QAAI,uBAA0B,kBAAkB;AACxE,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAA4B,MAAS;AAE/D,QAAM,oBAAoB,CACxB,UAGG;AACH,aAAS,MAAM,OAAO,KAAK;AAAA,EAC7B;AAGA,QAAM,yBAAqB,qBAA+B,IAAI;AAE9D,QAAM,WAAO,0BAAY,MAAM;AAC7B,QAAI,mBAAmB,SAAS;AAC9B,yBAAmB,QAAQ,MAAM;AACjC,yBAAmB,UAAU;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,QAAM,SAAS,OACb,SACA,mBAGG;AArIP;AAsII,cAAU,aAAa;AAEvB,gBAAY,CAAAC,cAAS;AAxIzB,UAAAC;AAwI4B;AAAA,QACtB,GAAGD;AAAA,QACH;AAAA,UACE,GAAG;AAAA,UACH,KAAIC,MAAA,QAAQ,OAAR,OAAAA,UAAc,4BAAW;AAAA,QAC/B;AAAA,MACF;AAAA,KAAC;AAED,aAAS,EAAE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;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,QAAQ;AACN,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,uBAAmB,0CAAkB;AAAA,gBACzC,OAAO;AAAA,gBACP,YAAQ,2BAAS,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,SAASG,QAAO;AACd,cAAI,qCAAaA,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":["fetch","messages","_a","error","import_ui_utils","import_react","throttleFunction","generateId","fetch","generateIdFunc","useSWR","messages","headers","body","import_ui_utils","import_react","import_swr","fetch","useSWR","completion","data","import_provider_utils","import_ui_utils","import_react","import_swr","getOriginalFetch","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-assistant.ts","../src/use-chat.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-assistant';\nexport * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import { isAbortError } from '@ai-sdk/provider-utils';\nimport {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n generateId,\n processAssistantStream,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useRef, useState } from 'react';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Message[];\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * The current thread ID.\n */\n threadId: string | undefined;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n\n /**\n * The current value of the input field.\n */\n input: string;\n\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 requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\nAbort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * setState-powered method to update the input value.\n */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler that automatically resets the input field and appends a user message.\n */\n submitMessage: (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * The current status of the assistant. This can be used to show a loading indicator.\n */\n status: AssistantStatus;\n\n /**\n * The error thrown during the assistant message processing, if any.\n */\n error: undefined | Error;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n fetch,\n}: UseAssistantOptions): UseAssistantHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState('');\n const [currentThreadId, setCurrentThreadId] = useState<string | undefined>(\n undefined,\n );\n const [status, setStatus] = useState<AssistantStatus>('awaiting_message');\n const [error, setError] = useState<undefined | Error>(undefined);\n\n const handleInputChange = (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => {\n setInput(event.target.value);\n };\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n setStatus('in_progress');\n\n setMessages(messages => [\n ...messages,\n {\n ...message,\n id: message.id ?? generateId(),\n },\n ]);\n\n setInput('');\n\n const abortController = new AbortController();\n\n try {\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n credentials,\n signal: abortController.signal,\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify({\n ...body,\n // always use user-provided threadId when available:\n threadId: threadIdParam ?? currentThreadId ?? null,\n message: message.content,\n\n // optional request data:\n data: requestOptions?.data,\n }),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the assistant response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n },\n onTextPart(value) {\n // text delta - add to last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n return [\n ...messages.slice(0, messages.length - 1),\n {\n id: lastMessage.id,\n role: lastMessage.role,\n content: lastMessage.content + value,\n },\n ];\n });\n },\n onAssistantControlDataPart(value) {\n setCurrentThreadId(value.threadId);\n\n // set id of last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n },\n onErrorPart(value) {\n setError(new Error(value));\n },\n });\n } catch (error) {\n // Ignore abort errors as they are expected when the user cancels the request:\n if (isAbortError(error) && abortController.signal.aborted) {\n abortControllerRef.current = null;\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n abortControllerRef.current = null;\n setStatus('awaiting_message');\n }\n };\n\n const submitMessage = async (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (input === '') {\n return;\n }\n\n append({ role: 'user', content: input }, requestOptions);\n };\n\n const setThreadId = (threadId: string | undefined) => {\n setCurrentThreadId(threadId);\n setMessages([]);\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: currentThreadId,\n setThreadId,\n input,\n setInput,\n handleInputChange,\n submitMessage,\n status,\n error,\n stop,\n };\n}\n","import { FetchFunction } from '@ai-sdk/provider-utils';\nimport type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n IdGenerator,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n prepareAttachmentsForRequest,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport useSWR, { KeyedMutator } from 'swr';\nimport { throttle } from './throttle';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Message[];\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: Message | CreateMessage,\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 * 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: Message[] | ((messages: Message[]) => Message[]),\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 ) => void;\n metadata?: Object;\n /** Whether the API request is in progress */\n isLoading: boolean;\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\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 /** The id of the chat */\n id: string;\n};\n\nconst processResponseStream = async (\n api: string,\n chatRequest: ChatRequest,\n mutate: KeyedMutator<Message[]>,\n mutateStreamData: KeyedMutator<JSONValue[] | undefined>,\n existingDataRef: React.MutableRefObject<JSONValue[] | undefined>,\n extraMetadataRef: React.MutableRefObject<any>,\n messagesRef: React.MutableRefObject<Message[]>,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n generateId: IdGenerator,\n streamProtocol: UseChatOptions['streamProtocol'],\n onFinish: UseChatOptions['onFinish'],\n onResponse: ((response: Response) => void | Promise<void>) | undefined,\n onToolCall: UseChatOptions['onToolCall'] | undefined,\n sendExtraMessageFields: boolean | undefined,\n experimental_prepareRequestBody:\n | ((options: {\n id: string;\n messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue)\n | undefined,\n fetch: FetchFunction | undefined,\n keepLastMessageOnError: boolean,\n id: string,\n) => {\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n mutate(chatRequest.messages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n }),\n );\n\n const existingData = existingDataRef.current;\n\n return await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id,\n messages: chatRequest.messages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id,\n messages: constructedMessagesPayload,\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 restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n mutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged], false);\n if (data?.length) {\n mutateStreamData([...(existingData ?? []), ...data], false);\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n });\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\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 keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\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 messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\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 a empty array as the initial messages\n // (instead of using a default parameter value that gets re-created each time)\n // to avoid re-renders:\n const [initialMessagesFallback] = useState([]);\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<Message[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: initialMessages ?? initialMessagesFallback },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<Message[]>(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 // We store loading state in another hook to sync loading states across hook invocations\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [chatKey, 'loading'],\n null,\n );\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 (chatRequest: ChatRequest) => {\n const messageCount = messagesRef.current.length;\n\n try {\n mutateLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n await processResponseStream(\n api,\n chatRequest,\n // throttle streamed ui updates:\n throttle(mutate, throttleWaitMs),\n throttle(mutateStreamData, throttleWaitMs),\n streamDataRef,\n extraMetadataRef,\n messagesRef,\n abortControllerRef,\n generateId,\n streamProtocol,\n onFinish,\n onResponse,\n onToolCall,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n fetch,\n keepLastMessageOnError,\n chatId,\n );\n\n abortControllerRef.current = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n } finally {\n mutateLoading(false);\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const messages = messagesRef.current;\n const lastMessage = messages[messages.length - 1];\n if (\n // ensure we actually have new messages (to prevent infinite loops in case of errors):\n messages.length > messageCount &&\n // ensure there is a last message:\n lastMessage != null &&\n // check if the feature is enabled:\n maxSteps > 1 &&\n // check that next step is possible:\n isAssistantMessageWithCompletedToolCalls(lastMessage) &&\n // limit the number of automatic steps:\n countTrailingAssistantMessages(messages) < maxSteps\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n });\n\n return triggerRequest({ messages, headers, body, 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 setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\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 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 attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages =\n !input && !attachmentsForRequest.length && options.allowEmptySubmit\n ? messagesRef.current\n : messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0\n ? attachmentsForRequest\n : undefined,\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\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 = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => {\n const updatedMessages = messagesRef.current.map((message, index, arr) =>\n // update the tool calls in the last assistant message:\n index === arr.length - 1 &&\n message.role === 'assistant' &&\n message.toolInvocations\n ? {\n ...message,\n toolInvocations: message.toolInvocations.map(toolInvocation =>\n toolInvocation.toolCallId === toolCallId\n ? {\n ...toolInvocation,\n result,\n state: 'result' as const,\n }\n : toolInvocation,\n ),\n }\n : message,\n );\n\n mutate(updatedMessages, false);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = updatedMessages[updatedMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: updatedMessages });\n }\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 input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n addToolResult,\n };\n}\n\n/**\nCheck if the message is an assistant message with completed tool calls.\nThe message must have at least one tool invocation and all tool invocations\nmust have a result.\n */\nfunction isAssistantMessageWithCompletedToolCalls(message: Message) {\n return (\n message.role === 'assistant' &&\n message.toolInvocations &&\n message.toolInvocations.length > 0 &&\n message.toolInvocations.every(toolInvocation => 'result' in toolInvocation)\n );\n}\n\n/**\nReturns the number of trailing assistant messages in the array.\n */\nfunction countTrailingAssistantMessages(messages: Message[]) {\n let count = 0;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n count++;\n } else {\n break;\n }\n }\n return count;\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 {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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?: RequestOptions) =>\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-sdk/ui-utils';\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\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}: 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 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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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;AAAA;;;ACAA,4BAA6B;AAC7B,sBAOO;AACP,mBAA8C;AAG9C,IAAM,mBAAmB,MAAM;AAiFxB,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AACF,GAA6C;AAC3C,QAAM,CAAC,UAAU,WAAW,QAAI,uBAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,Q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SAASG,QAAO;AACd,cAAI,qCAAaA,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":["fetch","messages","_a","error","import_ui_utils","import_react","throttleFunction","generateId","fetch","generateIdFunc","useSWR","messages","headers","body","import_ui_utils","import_react","import_swr","fetch","useSWR","completion","data","import_provider_utils","import_ui_utils","import_react","import_swr","getOriginalFetch","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -171,7 +171,7 @@ import {
171
171
  generateId as generateIdFunc,
172
172
  prepareAttachmentsForRequest
173
173
  } from "@ai-sdk/ui-utils";
174
- import { useCallback as useCallback2, useEffect, useId, useRef as useRef2, useState as useState2 } from "react";
174
+ import { useCallback as useCallback2, useEffect, useRef as useRef2, useState as useState2 } from "react";
175
175
  import useSWR from "swr";
176
176
 
177
177
  // src/throttle.ts
@@ -181,7 +181,7 @@ function throttle(fn, waitMs) {
181
181
  }
182
182
 
183
183
  // src/use-chat.ts
184
- var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, existingDataRef, extraMetadataRef, messagesRef, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, experimental_prepareRequestBody, fetch2, keepLastMessageOnError) => {
184
+ var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, existingDataRef, extraMetadataRef, messagesRef, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, experimental_prepareRequestBody, fetch2, keepLastMessageOnError, id) => {
185
185
  var _a;
186
186
  const previousMessages = messagesRef.current;
187
187
  mutate(chatRequest.messages, false);
@@ -208,10 +208,12 @@ var processResponseStream = async (api, chatRequest, mutate, mutateStreamData, e
208
208
  return await callChatApi({
209
209
  api,
210
210
  body: (_a = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
211
+ id,
211
212
  messages: chatRequest.messages,
212
213
  requestData: chatRequest.data,
213
214
  requestBody: chatRequest.body
214
215
  })) != null ? _a : {
216
+ id,
215
217
  messages: constructedMessagesPayload,
216
218
  data: chatRequest.data,
217
219
  ...extraMetadataRef.current.body,
@@ -263,9 +265,9 @@ function useChat({
263
265
  keepLastMessageOnError = true,
264
266
  experimental_throttle: throttleWaitMs
265
267
  } = {}) {
266
- const hookId = useId();
267
- const idKey = id != null ? id : hookId;
268
- const chatKey = typeof api === "string" ? [api, idKey] : idKey;
268
+ const [hookId] = useState2(generateId2);
269
+ const chatId = id != null ? id : hookId;
270
+ const chatKey = typeof api === "string" ? [api, chatId] : chatId;
269
271
  const [initialMessagesFallback] = useState2([]);
270
272
  const { data: messages, mutate } = useSWR(
271
273
  [chatKey, "messages"],
@@ -325,7 +327,8 @@ function useChat({
325
327
  sendExtraMessageFields,
326
328
  experimental_prepareRequestBody,
327
329
  fetch2,
328
- keepLastMessageOnError
330
+ keepLastMessageOnError,
331
+ chatId
329
332
  );
330
333
  abortControllerRef.current = null;
331
334
  } catch (err) {
@@ -374,7 +377,8 @@ function useChat({
374
377
  generateId2,
375
378
  fetch2,
376
379
  keepLastMessageOnError,
377
- throttleWaitMs
380
+ throttleWaitMs,
381
+ chatId
378
382
  ]
379
383
  );
380
384
  const append = useCallback2(
@@ -504,6 +508,7 @@ function useChat({
504
508
  };
505
509
  return {
506
510
  messages: messages || [],
511
+ id: chatId,
507
512
  setMessages,
508
513
  data: streamData,
509
514
  setData,
@@ -538,7 +543,7 @@ function countTrailingAssistantMessages(messages) {
538
543
  import {
539
544
  callCompletionApi
540
545
  } from "@ai-sdk/ui-utils";
541
- import { useCallback as useCallback3, useEffect as useEffect2, useId as useId2, useRef as useRef3, useState as useState3 } from "react";
546
+ import { useCallback as useCallback3, useEffect as useEffect2, useId, useRef as useRef3, useState as useState3 } from "react";
542
547
  import useSWR2 from "swr";
543
548
  function useCompletion({
544
549
  api = "/api/completion",
@@ -555,7 +560,7 @@ function useCompletion({
555
560
  onError,
556
561
  experimental_throttle: throttleWaitMs
557
562
  } = {}) {
558
- const hookId = useId2();
563
+ const hookId = useId();
559
564
  const completionId = id || hookId;
560
565
  const { data, mutate } = useSWR2([api, completionId], null, {
561
566
  fallbackData: initialCompletion
@@ -683,7 +688,7 @@ import {
683
688
  isDeepEqualData,
684
689
  parsePartialJson
685
690
  } from "@ai-sdk/ui-utils";
686
- import { useCallback as useCallback4, useId as useId3, useRef as useRef4, useState as useState4 } from "react";
691
+ import { useCallback as useCallback4, useId as useId2, useRef as useRef4, useState as useState4 } from "react";
687
692
  import useSWR3 from "swr";
688
693
  var getOriginalFetch2 = () => fetch;
689
694
  function useObject({
@@ -697,7 +702,7 @@ function useObject({
697
702
  onFinish,
698
703
  headers
699
704
  }) {
700
- const hookId = useId3();
705
+ const hookId = useId2();
701
706
  const completionId = id != null ? id : hookId;
702
707
  const { data, mutate } = useSWR3(
703
708
  [api, completionId],
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-assistant.ts","../src/use-chat.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import { isAbortError } from '@ai-sdk/provider-utils';\nimport {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n generateId,\n processAssistantStream,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useRef, useState } from 'react';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Message[];\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * The current thread ID.\n */\n threadId: string | undefined;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n\n /**\n * The current value of the input field.\n */\n input: string;\n\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 requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\nAbort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * setState-powered method to update the input value.\n */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler that automatically resets the input field and appends a user message.\n */\n submitMessage: (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * The current status of the assistant. This can be used to show a loading indicator.\n */\n status: AssistantStatus;\n\n /**\n * The error thrown during the assistant message processing, if any.\n */\n error: undefined | Error;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n fetch,\n}: UseAssistantOptions): UseAssistantHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState('');\n const [currentThreadId, setCurrentThreadId] = useState<string | undefined>(\n undefined,\n );\n const [status, setStatus] = useState<AssistantStatus>('awaiting_message');\n const [error, setError] = useState<undefined | Error>(undefined);\n\n const handleInputChange = (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => {\n setInput(event.target.value);\n };\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n setStatus('in_progress');\n\n setMessages(messages => [\n ...messages,\n {\n ...message,\n id: message.id ?? generateId(),\n },\n ]);\n\n setInput('');\n\n const abortController = new AbortController();\n\n try {\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n credentials,\n signal: abortController.signal,\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify({\n ...body,\n // always use user-provided threadId when available:\n threadId: threadIdParam ?? currentThreadId ?? null,\n message: message.content,\n\n // optional request data:\n data: requestOptions?.data,\n }),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the assistant response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n },\n onTextPart(value) {\n // text delta - add to last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n return [\n ...messages.slice(0, messages.length - 1),\n {\n id: lastMessage.id,\n role: lastMessage.role,\n content: lastMessage.content + value,\n },\n ];\n });\n },\n onAssistantControlDataPart(value) {\n setCurrentThreadId(value.threadId);\n\n // set id of last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n },\n onErrorPart(value) {\n setError(new Error(value));\n },\n });\n } catch (error) {\n // Ignore abort errors as they are expected when the user cancels the request:\n if (isAbortError(error) && abortController.signal.aborted) {\n abortControllerRef.current = null;\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n abortControllerRef.current = null;\n setStatus('awaiting_message');\n }\n };\n\n const submitMessage = async (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (input === '') {\n return;\n }\n\n append({ role: 'user', content: input }, requestOptions);\n };\n\n const setThreadId = (threadId: string | undefined) => {\n setCurrentThreadId(threadId);\n setMessages([]);\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: currentThreadId,\n setThreadId,\n input,\n setInput,\n handleInputChange,\n submitMessage,\n status,\n error,\n stop,\n };\n}\n","import { FetchFunction } from '@ai-sdk/provider-utils';\nimport type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n IdGenerator,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n prepareAttachmentsForRequest,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR, { KeyedMutator } from 'swr';\nimport { throttle } from './throttle';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Message[];\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: Message | CreateMessage,\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 * 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: Message[] | ((messages: Message[]) => Message[]),\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 ) => void;\n metadata?: Object;\n /** Whether the API request is in progress */\n isLoading: boolean;\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\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\nconst processResponseStream = async (\n api: string,\n chatRequest: ChatRequest,\n mutate: KeyedMutator<Message[]>,\n mutateStreamData: KeyedMutator<JSONValue[] | undefined>,\n existingDataRef: React.MutableRefObject<JSONValue[] | undefined>,\n extraMetadataRef: React.MutableRefObject<any>,\n messagesRef: React.MutableRefObject<Message[]>,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n generateId: IdGenerator,\n streamProtocol: UseChatOptions['streamProtocol'],\n onFinish: UseChatOptions['onFinish'],\n onResponse: ((response: Response) => void | Promise<void>) | undefined,\n onToolCall: UseChatOptions['onToolCall'] | undefined,\n sendExtraMessageFields: boolean | undefined,\n experimental_prepareRequestBody:\n | ((options: {\n messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue)\n | undefined,\n fetch: FetchFunction | undefined,\n keepLastMessageOnError: boolean,\n) => {\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n mutate(chatRequest.messages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n }),\n );\n\n const existingData = existingDataRef.current;\n\n return await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n messages: chatRequest.messages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n messages: constructedMessagesPayload,\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 restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n mutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged], false);\n if (data?.length) {\n mutateStreamData([...(existingData ?? []), ...data], false);\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n });\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\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 keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\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 messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate a unique id for the chat if not provided.\n const hookId = useId();\n const idKey = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, idKey] : idKey;\n\n // Store a empty array as the initial messages\n // (instead of using a default parameter value that gets re-created each time)\n // to avoid re-renders:\n const [initialMessagesFallback] = useState([]);\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<Message[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: initialMessages ?? initialMessagesFallback },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<Message[]>(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 // We store loading state in another hook to sync loading states across hook invocations\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [chatKey, 'loading'],\n null,\n );\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 (chatRequest: ChatRequest) => {\n const messageCount = messagesRef.current.length;\n\n try {\n mutateLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n await processResponseStream(\n api,\n chatRequest,\n // throttle streamed ui updates:\n throttle(mutate, throttleWaitMs),\n throttle(mutateStreamData, throttleWaitMs),\n streamDataRef,\n extraMetadataRef,\n messagesRef,\n abortControllerRef,\n generateId,\n streamProtocol,\n onFinish,\n onResponse,\n onToolCall,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n fetch,\n keepLastMessageOnError,\n );\n\n abortControllerRef.current = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n } finally {\n mutateLoading(false);\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const messages = messagesRef.current;\n const lastMessage = messages[messages.length - 1];\n if (\n // ensure we actually have new messages (to prevent infinite loops in case of errors):\n messages.length > messageCount &&\n // ensure there is a last message:\n lastMessage != null &&\n // check if the feature is enabled:\n maxSteps > 1 &&\n // check that next step is possible:\n isAssistantMessageWithCompletedToolCalls(lastMessage) &&\n // limit the number of automatic steps:\n countTrailingAssistantMessages(messages) < maxSteps\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n });\n\n return triggerRequest({ messages, headers, body, 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 setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\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 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 attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages =\n !input && !attachmentsForRequest.length && options.allowEmptySubmit\n ? messagesRef.current\n : messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0\n ? attachmentsForRequest\n : undefined,\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\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 = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => {\n const updatedMessages = messagesRef.current.map((message, index, arr) =>\n // update the tool calls in the last assistant message:\n index === arr.length - 1 &&\n message.role === 'assistant' &&\n message.toolInvocations\n ? {\n ...message,\n toolInvocations: message.toolInvocations.map(toolInvocation =>\n toolInvocation.toolCallId === toolCallId\n ? {\n ...toolInvocation,\n result,\n state: 'result' as const,\n }\n : toolInvocation,\n ),\n }\n : message,\n );\n\n mutate(updatedMessages, false);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = updatedMessages[updatedMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: updatedMessages });\n }\n };\n\n return {\n messages: messages || [],\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n addToolResult,\n };\n}\n\n/**\nCheck if the message is an assistant message with completed tool calls.\nThe message must have at least one tool invocation and all tool invocations\nmust have a result.\n */\nfunction isAssistantMessageWithCompletedToolCalls(message: Message) {\n return (\n message.role === 'assistant' &&\n message.toolInvocations &&\n message.toolInvocations.length > 0 &&\n message.toolInvocations.every(toolInvocation => 'result' in toolInvocation)\n );\n}\n\n/**\nReturns the number of trailing assistant messages in the array.\n */\nfunction countTrailingAssistantMessages(messages: Message[]) {\n let count = 0;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n count++;\n } else {\n break;\n }\n }\n return count;\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 {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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?: RequestOptions) =>\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-sdk/ui-utils';\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\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}: 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 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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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,SAAS,oBAAoB;AAC7B;AAAA,EAKE;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,QAAQ,gBAAgB;AAG9C,IAAM,mBAAmB,MAAM;AAiFxB,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AACF,GAA6C;AAC3C,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,EAAE;AACrC,QAAM,CAAC,iBAAiB,kBAAkB,IAAI;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA0B,kBAAkB;AACxE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAE/D,QAAM,oBAAoB,CACxB,UAGG;AACH,aAAS,MAAM,OAAO,KAAK;AAAA,EAC7B;AAGA,QAAM,qBAAqB,OAA+B,IAAI;AAE9D,QAAM,OAAO,YAAY,MAAM;AAC7B,QAAI,mBAAmB,SAAS;AAC9B,yBAAmB,QAAQ,MAAM;AACjC,yBAAmB,UA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AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["fetch","messages","_a","error","useCallback","useRef","useState","generateId","fetch","useState","useRef","useCallback","messages","headers","body","useCallback","useEffect","useId","useRef","useState","useSWR","fetch","useId","useSWR","useState","useRef","useEffect","useCallback","completion","data","isAbortError","useCallback","useId","useRef","useState","useSWR","getOriginalFetch","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-assistant.ts","../src/use-chat.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import { isAbortError } from '@ai-sdk/provider-utils';\nimport {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n generateId,\n processAssistantStream,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useRef, useState } from 'react';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Message[];\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * The current thread ID.\n */\n threadId: string | undefined;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n\n /**\n * The current value of the input field.\n */\n input: string;\n\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 requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\nAbort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * setState-powered method to update the input value.\n */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler that automatically resets the input field and appends a user message.\n */\n submitMessage: (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * The current status of the assistant. This can be used to show a loading indicator.\n */\n status: AssistantStatus;\n\n /**\n * The error thrown during the assistant message processing, if any.\n */\n error: undefined | Error;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n fetch,\n}: UseAssistantOptions): UseAssistantHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState('');\n const [currentThreadId, setCurrentThreadId] = useState<string | undefined>(\n undefined,\n );\n const [status, setStatus] = useState<AssistantStatus>('awaiting_message');\n const [error, setError] = useState<undefined | Error>(undefined);\n\n const handleInputChange = (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => {\n setInput(event.target.value);\n };\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n setStatus('in_progress');\n\n setMessages(messages => [\n ...messages,\n {\n ...message,\n id: message.id ?? generateId(),\n },\n ]);\n\n setInput('');\n\n const abortController = new AbortController();\n\n try {\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n credentials,\n signal: abortController.signal,\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify({\n ...body,\n // always use user-provided threadId when available:\n threadId: threadIdParam ?? currentThreadId ?? null,\n message: message.content,\n\n // optional request data:\n data: requestOptions?.data,\n }),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the assistant response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n },\n onTextPart(value) {\n // text delta - add to last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n return [\n ...messages.slice(0, messages.length - 1),\n {\n id: lastMessage.id,\n role: lastMessage.role,\n content: lastMessage.content + value,\n },\n ];\n });\n },\n onAssistantControlDataPart(value) {\n setCurrentThreadId(value.threadId);\n\n // set id of last message:\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n },\n onErrorPart(value) {\n setError(new Error(value));\n },\n });\n } catch (error) {\n // Ignore abort errors as they are expected when the user cancels the request:\n if (isAbortError(error) && abortController.signal.aborted) {\n abortControllerRef.current = null;\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n abortControllerRef.current = null;\n setStatus('awaiting_message');\n }\n };\n\n const submitMessage = async (\n event?: React.FormEvent<HTMLFormElement>,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (input === '') {\n return;\n }\n\n append({ role: 'user', content: input }, requestOptions);\n };\n\n const setThreadId = (threadId: string | undefined) => {\n setCurrentThreadId(threadId);\n setMessages([]);\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: currentThreadId,\n setThreadId,\n input,\n setInput,\n handleInputChange,\n submitMessage,\n status,\n error,\n stop,\n };\n}\n","import { FetchFunction } from '@ai-sdk/provider-utils';\nimport type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n IdGenerator,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n prepareAttachmentsForRequest,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport useSWR, { KeyedMutator } from 'swr';\nimport { throttle } from './throttle';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Message[];\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: Message | CreateMessage,\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 * 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: Message[] | ((messages: Message[]) => Message[]),\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 ) => void;\n metadata?: Object;\n /** Whether the API request is in progress */\n isLoading: boolean;\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\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 /** The id of the chat */\n id: string;\n};\n\nconst processResponseStream = async (\n api: string,\n chatRequest: ChatRequest,\n mutate: KeyedMutator<Message[]>,\n mutateStreamData: KeyedMutator<JSONValue[] | undefined>,\n existingDataRef: React.MutableRefObject<JSONValue[] | undefined>,\n extraMetadataRef: React.MutableRefObject<any>,\n messagesRef: React.MutableRefObject<Message[]>,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n generateId: IdGenerator,\n streamProtocol: UseChatOptions['streamProtocol'],\n onFinish: UseChatOptions['onFinish'],\n onResponse: ((response: Response) => void | Promise<void>) | undefined,\n onToolCall: UseChatOptions['onToolCall'] | undefined,\n sendExtraMessageFields: boolean | undefined,\n experimental_prepareRequestBody:\n | ((options: {\n id: string;\n messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue)\n | undefined,\n fetch: FetchFunction | undefined,\n keepLastMessageOnError: boolean,\n id: string,\n) => {\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n mutate(chatRequest.messages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n }),\n );\n\n const existingData = existingDataRef.current;\n\n return await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id,\n messages: chatRequest.messages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id,\n messages: constructedMessagesPayload,\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 restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n mutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged], false);\n if (data?.length) {\n mutateStreamData([...(existingData ?? []), ...data], false);\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n });\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\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 keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\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 messages: Message[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => JSONValue;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\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 a empty array as the initial messages\n // (instead of using a default parameter value that gets re-created each time)\n // to avoid re-renders:\n const [initialMessagesFallback] = useState([]);\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<Message[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: initialMessages ?? initialMessagesFallback },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<Message[]>(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 // We store loading state in another hook to sync loading states across hook invocations\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [chatKey, 'loading'],\n null,\n );\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 (chatRequest: ChatRequest) => {\n const messageCount = messagesRef.current.length;\n\n try {\n mutateLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n await processResponseStream(\n api,\n chatRequest,\n // throttle streamed ui updates:\n throttle(mutate, throttleWaitMs),\n throttle(mutateStreamData, throttleWaitMs),\n streamDataRef,\n extraMetadataRef,\n messagesRef,\n abortControllerRef,\n generateId,\n streamProtocol,\n onFinish,\n onResponse,\n onToolCall,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n fetch,\n keepLastMessageOnError,\n chatId,\n );\n\n abortControllerRef.current = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n } finally {\n mutateLoading(false);\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const messages = messagesRef.current;\n const lastMessage = messages[messages.length - 1];\n if (\n // ensure we actually have new messages (to prevent infinite loops in case of errors):\n messages.length > messageCount &&\n // ensure there is a last message:\n lastMessage != null &&\n // check if the feature is enabled:\n maxSteps > 1 &&\n // check that next step is possible:\n isAssistantMessageWithCompletedToolCalls(lastMessage) &&\n // limit the number of automatic steps:\n countTrailingAssistantMessages(messages) < maxSteps\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n });\n\n return triggerRequest({ messages, headers, body, 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 setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\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 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 attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages =\n !input && !attachmentsForRequest.length && options.allowEmptySubmit\n ? messagesRef.current\n : messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0\n ? attachmentsForRequest\n : undefined,\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\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 = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => {\n const updatedMessages = messagesRef.current.map((message, index, arr) =>\n // update the tool calls in the last assistant message:\n index === arr.length - 1 &&\n message.role === 'assistant' &&\n message.toolInvocations\n ? {\n ...message,\n toolInvocations: message.toolInvocations.map(toolInvocation =>\n toolInvocation.toolCallId === toolCallId\n ? {\n ...toolInvocation,\n result,\n state: 'result' as const,\n }\n : toolInvocation,\n ),\n }\n : message,\n );\n\n mutate(updatedMessages, false);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = updatedMessages[updatedMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: updatedMessages });\n }\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 input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n addToolResult,\n };\n}\n\n/**\nCheck if the message is an assistant message with completed tool calls.\nThe message must have at least one tool invocation and all tool invocations\nmust have a result.\n */\nfunction isAssistantMessageWithCompletedToolCalls(message: Message) {\n return (\n message.role === 'assistant' &&\n message.toolInvocations &&\n message.toolInvocations.length > 0 &&\n message.toolInvocations.every(toolInvocation => 'result' in toolInvocation)\n );\n}\n\n/**\nReturns the number of trailing assistant messages in the array.\n */\nfunction countTrailingAssistantMessages(messages: Message[]) {\n let count = 0;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n count++;\n } else {\n break;\n }\n }\n return count;\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 {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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?: RequestOptions) =>\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-sdk/ui-utils';\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\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}: 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 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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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,SAAS,oBAAoB;AAC7B;AAAA,EAKE;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,QAAQ,gBAAgB;AAG9C,IAAM,mBAAmB,MAAM;AAiFxB,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AACF,GAA6C;AAC3C,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,EAAE;AACrC,QAAM,CAAC,iBAAiB,kBAAkB,IAAI;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA0B,kBAAkB;AACxE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAE/D,QAAM,oBAAoB,CACxB,UAGG;AACH,aAAS,MAAM,OAAO,KAAK;AAAA,EAC7B;AAGA,QAAM,qBAAqB,OAA+B,IAAI;AAE9D,QAAM,OAAO,YAAY,MAAM;AAC7B,QAAI,mBAAmB,SAAS;AAC9B,yBAAmB,QAAQ,MAAM;AACjC,yBAAmB,UAAU;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,QAAM,SAAS,OACb,SACA,mBAGG;AArIP;AAsII,cAAU,aAAa;AAEvB,gBAAY,CAAAC,cAAS;AAxIzB,UAAAC;AAwI4B;AAAA,QACtB,GAAGD;AAAA,QACH;AAAA,UACE,GAAG;AAAA,UACH,KAAIC,MAAA,QAAQ,OAAR,OAAAA,MAAc,WAAW;AAAA,QAC/B;AAAA,MACF;AAAA,KAAC;AAED,aAAS,EAAE;AAEX,UAAM,kBAAkB,IAAI,gBAAgB;AAE5C,QAAI;AACF,yBAAmB,UAAU;AAE7B,YAAM,cAAcF,UAAA,OAAAA,S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I,eAAuB;AAAA,UACzB,MAAM,OAAO;AACX,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,iBAAiB,eAAe;AAClD,kBAAM,gBAAgB;AAEtB,gBAAI,CAAC,gBAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,QAAQ;AACN,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,kBAAkB;AAAA,gBACzC,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,SAASE,QAAO;AACd,UAAIR,cAAaQ,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":["fetch","messages","_a","error","useCallback","useRef","useState","generateId","fetch","useState","useRef","useCallback","messages","headers","body","useCallback","useEffect","useRef","useState","useSWR","fetch","useSWR","useState","useRef","useEffect","useCallback","completion","data","isAbortError","useCallback","useId","useRef","useState","useSWR","getOriginalFetch","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -20,7 +20,7 @@
20
20
  ],
21
21
  "dependencies": {
22
22
  "@ai-sdk/provider-utils": "2.0.7",
23
- "@ai-sdk/ui-utils": "1.0.9",
23
+ "@ai-sdk/ui-utils": "1.0.10",
24
24
  "swr": "^2.2.5",
25
25
  "throttleit": "2.1.0"
26
26
  },