@ai-sdk/react 2.0.0-canary.21 → 2.0.0-canary.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n convertFileListToFileUIParts,\n extractMaxToolInvocationStep,\n generateId as generateIdFunc,\n getToolInvocations,\n isAssistantMessageWithCompletedToolCalls,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<MESSAGE_METADATA = unknown> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n readonly status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Current messages in the chat */\n readonly messages: UIMessage<MESSAGE_METADATA>[];\n\n /** The error object of the API request */\n readonly error: undefined | Error;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n *\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: CreateUIMessage<MESSAGE_METADATA>,\n options?: ChatRequestOptions,\n ) => Promise<void>;\n\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 /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => void;\n\n /** The current value of the input */\n input: string;\n\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 handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n};\n\nexport function useChat<MESSAGE_METADATA>({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'ui-message',\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n experimental_throttle: throttleWaitMs,\n messageMetadataSchema,\n}: UseChatOptions<MESSAGE_METADATA> & {\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param id The id of the chat.\n * @param messages The current messages in the chat.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage<MESSAGE_METADATA>[];\n requestBody?: object;\n }) => unknown;\n\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA> {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => stableInitialMessages,\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage<MESSAGE_METADATA>[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage<MESSAGE_METADATA>[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (\n chatRequest: ChatRequestOptions & {\n messages: UIMessage<MESSAGE_METADATA>[];\n },\n requestType: 'generate' | 'resume' = 'generate',\n ) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = chatRequest.messages;\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n getToolInvocations(chatMessages[chatMessages.length - 1]),\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n\n // Do an optimistic update to show the updated messages immediately:\n throttledMutate(chatMessages, false);\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: chatMessages,\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 onUpdate({ message }) {\n mutateStatus('streaming');\n\n const replaceLastMessage =\n message.id === chatMessages[chatMessages.length - 1].id;\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n requestType,\n messageMetadataSchema,\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onFinish,\n onError,\n setError,\n streamProtocol,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n throttleWaitMs,\n chatId,\n messageMetadataSchema,\n ],\n );\n\n const append = useCallback(\n async (\n message: CreateUIMessage<MESSAGE_METADATA>,\n { headers, body }: ChatRequestOptions = {},\n ) => {\n await triggerRequest({\n messages: messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n }),\n headers,\n body,\n });\n },\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ 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 });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const experimental_resume = useCallback(async () => {\n const messages = messagesRef.current;\n\n triggerRequest({ messages }, 'resume');\n }, [triggerRequest]);\n\n const setMessages = useCallback(\n (\n messages:\n | UIMessage<MESSAGE_METADATA>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\n ) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n mutate(messages, false);\n messagesRef.current = messages;\n },\n [mutate],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n if (!input && fileParts.length === 0) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n triggerRequest({\n messages: messagesRef.current.concat({\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n }),\n headers: options.headers,\n body: options.body,\n });\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n {\n ...currentMessages[currentMessages.length - 1],\n // @ts-ignore\n // update the revisionId to trigger a re-render\n revisionId: generateId(),\n },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest, generateId],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n status,\n addToolResult,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,IAAAA,aASO;AACP,IAAAC,gBAAkE;AAClE,iBAAmB;;;AClBnB,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAC,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,gBAAgC;AAChC,mBAAoC;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAY,WAAW;AAEjD,8BAAU,MAAM;AACd,QAAI,KAAC,2BAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,aAAa,KAAK,CAAC;AAEvB,SAAO;AACT;;;AFuGO,SAAS,QAA0B;AAAA,EACxC,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,WAAAC;AAAA,EACb,OAAAC;AAAA,EACA,uBAAuB;AAAA,EACvB;AACF,IAqBI,CAAC,GAAqC;AAExC,QAAM,CAAC,MAAM,QAAI,wBAAS,UAAU;AAGpC,QAAM,SAAS,kBAAM;AACrB,QAAM,UAAU,OAAO,QAAQ,WAAW,CAAC,KAAK,MAAM,IAAI;AAG1D,QAAM,wBAAwB,eAAe,4CAAmB,CAAC,CAAC;AAClE,QAAM,+BAA2B;AAAA,IAC/B,MAAM;AA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AA,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,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["import_ai","import_react","throttleFunction","generateIdFunc","fetch","useSWR","messages","headers","body","import_ai","import_react","import_swr","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/use-completion.ts","../src/throttle.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n ChatStore,\n convertFileListToFileUIParts,\n defaultChatStore,\n generateId as generateIdFunc,\n type ChatRequestOptions,\n type ChatStoreEvent,\n type CreateUIMessage,\n type FileUIPart,\n type UIDataTypes,\n type UIMessage,\n type UseChatOptions,\n} from 'ai';\nimport { useCallback, useRef, useState, useSyncExternalStore } from 'react';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<\n MESSAGE_METADATA = unknown,\n DATA_TYPES extends UIDataTypes = UIDataTypes,\n> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n readonly status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Current messages in the chat */\n readonly messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];\n\n /** The error object of the API request */\n readonly error: undefined | Error;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n *\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: CreateUIMessage<MESSAGE_METADATA, DATA_TYPES>,\n options?: ChatRequestOptions,\n ) => Promise<void>;\n\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 /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA, DATA_TYPES>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[],\n ) => UIMessage<MESSAGE_METADATA, DATA_TYPES>[]),\n ) => void;\n\n /** The current value of the input */\n input: string;\n\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 handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n};\n\nexport function useChat<\n MESSAGE_METADATA = unknown,\n DATA_TYPES extends Record<string, unknown> = Record<string, unknown>,\n>({\n id,\n initialInput = '',\n onToolCall,\n onFinish,\n onError,\n generateId = generateIdFunc,\n experimental_throttle: throttleWaitMs,\n chatStore: chatStoreArg,\n}: UseChatOptions<MESSAGE_METADATA, DATA_TYPES> & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA, DATA_TYPES> {\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\n // chat store setup\n // TODO enable as arg\n const chatStore = useRef(\n chatStoreArg ??\n defaultChatStore<MESSAGE_METADATA, DATA_TYPES>({\n api: '/api/chat',\n generateId,\n }),\n );\n\n // ensure the chat is in the store\n if (!chatStore.current.hasChat(chatId)) {\n chatStore.current.addChat(chatId, []);\n }\n\n const subscribe = useCallback(\n ({\n onStoreChange,\n eventType,\n }: {\n onStoreChange: () => void;\n eventType: ChatStoreEvent['type'];\n }) => {\n return chatStore.current.subscribe({\n onChatChanged: event => {\n if (event.chatId !== chatId || event.type !== eventType) {\n return;\n }\n\n onStoreChange();\n },\n });\n },\n [chatStore, chatId],\n );\n\n const addToolResult = useCallback(\n (\n options: Omit<\n Parameters<ChatStore<MESSAGE_METADATA, DATA_TYPES>['addToolResult']>[0],\n 'chatId'\n >,\n ) => chatStore.current.addToolResult({ chatId, ...options }),\n [chatStore, chatId],\n );\n\n const stopStream = useCallback(() => {\n chatStore.current.stopStream({ chatId });\n }, [chatStore, chatId]);\n\n const error = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getError(chatId),\n () => chatStore.current.getError(chatId),\n );\n\n const status = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getStatus(chatId),\n () => chatStore.current.getStatus(chatId),\n );\n\n const messages = useSyncExternalStore(\n callback => {\n return subscribe({\n onStoreChange: callback,\n eventType: 'chat-messages-changed',\n });\n },\n () => chatStore.current.getMessages(chatId),\n () => chatStore.current.getMessages(chatId),\n );\n\n const append = useCallback(\n (\n message: CreateUIMessage<MESSAGE_METADATA, DATA_TYPES>,\n { headers, body }: ChatRequestOptions = {},\n ) =>\n chatStore.current.submitMessage({\n chatId,\n message,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, chatId, onError, onToolCall, onFinish],\n );\n\n const reload = useCallback(\n async ({ headers, body }: ChatRequestOptions = {}) =>\n chatStore.current.resubmitLastUserMessage({\n chatId,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, chatId, onError, onToolCall, onFinish],\n );\n const stop = useCallback(() => stopStream(), [stopStream]);\n\n const experimental_resume = useCallback(\n async () =>\n chatStore.current.resumeStream({\n chatId,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, chatId, onError, onToolCall, onFinish],\n );\n\n const setMessages = useCallback(\n (\n messagesParam:\n | UIMessage<MESSAGE_METADATA, DATA_TYPES>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[],\n ) => UIMessage<MESSAGE_METADATA, DATA_TYPES>[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(messages);\n }\n\n chatStore.current.setMessages({\n id: chatId,\n messages: messagesParam,\n });\n },\n [chatId, messages],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n ) => {\n event?.preventDefault?.();\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n if (!input && fileParts.length === 0) return;\n\n append(\n {\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n },\n {\n headers: options.headers,\n body: options.body,\n },\n );\n\n setInput('');\n },\n [input, generateId, append],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n return {\n messages,\n id: chatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n status,\n addToolResult,\n };\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import 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 FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAYO;AACP,mBAAoE;AAuG7D,SAAS,QAGd;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,UAAAA;AAAA,EACb,uBAAuB;AAAA,EACvB,WAAW;AACb,IAMI,CAAC,GAAiD;AAEpD,QAAM,CAAC,MAAM,QAAI,uBAAS,UAAU;AAGpC,QAAM,SAAS,kBAAM;AAIrB,QAAM,gBAAY;AAAA,IAChB,0CACE,4BAA+C;AAAA,MAC7C,KAAK;AAAA,MACL;AAAA,IACF,CAAC;AAAA,E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AI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,UAAM,yCAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,YAAQ,qBAAS,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,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["generateIdFunc","import_ai","import_react","throttleFunction","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -1,298 +1,154 @@
1
1
  // src/use-chat.ts
2
2
  import {
3
- callChatApi,
4
3
  convertFileListToFileUIParts,
5
- extractMaxToolInvocationStep,
6
- generateId as generateIdFunc,
7
- getToolInvocations,
8
- isAssistantMessageWithCompletedToolCalls,
9
- shouldResubmitMessages,
10
- updateToolCallResult
4
+ defaultChatStore,
5
+ generateId as generateIdFunc
11
6
  } from "ai";
12
- import { useCallback, useEffect as useEffect2, useMemo, useRef, useState as useState2 } from "react";
13
- import useSWR from "swr";
14
-
15
- // src/throttle.ts
16
- import throttleFunction from "throttleit";
17
- function throttle(fn, waitMs) {
18
- return waitMs != null ? throttleFunction(fn, waitMs) : fn;
19
- }
20
-
21
- // src/util/use-stable-value.ts
22
- import { isDeepEqualData } from "ai";
23
- import { useEffect, useState } from "react";
24
- function useStableValue(latestValue) {
25
- const [value, setValue] = useState(latestValue);
26
- useEffect(() => {
27
- if (!isDeepEqualData(latestValue, value)) {
28
- setValue(latestValue);
29
- }
30
- }, [latestValue, value]);
31
- return value;
32
- }
33
-
34
- // src/use-chat.ts
7
+ import { useCallback, useRef, useState, useSyncExternalStore } from "react";
35
8
  function useChat({
36
- api = "/api/chat",
37
9
  id,
38
- initialMessages,
39
10
  initialInput = "",
40
11
  onToolCall,
41
- experimental_prepareRequestBody,
42
- maxSteps = 1,
43
- streamProtocol = "ui-message",
44
12
  onFinish,
45
13
  onError,
46
- credentials,
47
- headers,
48
- body,
49
14
  generateId = generateIdFunc,
50
- fetch: fetch2,
51
15
  experimental_throttle: throttleWaitMs,
52
- messageMetadataSchema
16
+ chatStore: chatStoreArg
53
17
  } = {}) {
54
- const [hookId] = useState2(generateId);
18
+ const [hookId] = useState(generateId);
55
19
  const chatId = id != null ? id : hookId;
56
- const chatKey = typeof api === "string" ? [api, chatId] : chatId;
57
- const stableInitialMessages = useStableValue(initialMessages != null ? initialMessages : []);
58
- const processedInitialMessages = useMemo(
59
- () => stableInitialMessages,
60
- [stableInitialMessages]
61
- );
62
- const { data: messages, mutate } = useSWR(
63
- [chatKey, "messages"],
64
- null,
65
- { fallbackData: processedInitialMessages }
20
+ const chatStore = useRef(
21
+ chatStoreArg != null ? chatStoreArg : defaultChatStore({
22
+ api: "/api/chat",
23
+ generateId
24
+ })
66
25
  );
67
- const messagesRef = useRef(messages || []);
68
- useEffect2(() => {
69
- messagesRef.current = messages || [];
70
- }, [messages]);
71
- const { data: status = "ready", mutate: mutateStatus } = useSWR([chatKey, "status"], null);
72
- const { data: error = void 0, mutate: setError } = useSWR([chatKey, "error"], null);
73
- const abortControllerRef = useRef(null);
74
- const extraMetadataRef = useRef({
75
- credentials,
76
- headers,
77
- body
78
- });
79
- useEffect2(() => {
80
- extraMetadataRef.current = {
81
- credentials,
82
- headers,
83
- body
84
- };
85
- }, [credentials, headers, body]);
86
- const triggerRequest = useCallback(
87
- async (chatRequest, requestType = "generate") => {
88
- var _a;
89
- mutateStatus("submitted");
90
- setError(void 0);
91
- const chatMessages = chatRequest.messages;
92
- const messageCount = chatMessages.length;
93
- const maxStep = extractMaxToolInvocationStep(
94
- getToolInvocations(chatMessages[chatMessages.length - 1])
95
- );
96
- try {
97
- const abortController = new AbortController();
98
- abortControllerRef.current = abortController;
99
- const throttledMutate = throttle(mutate, throttleWaitMs);
100
- throttledMutate(chatMessages, false);
101
- await callChatApi({
102
- api,
103
- body: (_a = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
104
- id: chatId,
105
- messages: chatMessages,
106
- requestBody: chatRequest.body
107
- })) != null ? _a : {
108
- id: chatId,
109
- messages: chatMessages,
110
- ...extraMetadataRef.current.body,
111
- ...chatRequest.body
112
- },
113
- streamProtocol,
114
- credentials: extraMetadataRef.current.credentials,
115
- headers: {
116
- ...extraMetadataRef.current.headers,
117
- ...chatRequest.headers
118
- },
119
- abortController: () => abortControllerRef.current,
120
- onUpdate({ message }) {
121
- mutateStatus("streaming");
122
- const replaceLastMessage = message.id === chatMessages[chatMessages.length - 1].id;
123
- throttledMutate(
124
- [
125
- ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
126
- message
127
- ],
128
- false
129
- );
130
- },
131
- onToolCall,
132
- onFinish,
133
- generateId,
134
- fetch: fetch2,
135
- lastMessage: chatMessages[chatMessages.length - 1],
136
- requestType,
137
- messageMetadataSchema
138
- });
139
- abortControllerRef.current = null;
140
- mutateStatus("ready");
141
- } catch (err) {
142
- if (err.name === "AbortError") {
143
- abortControllerRef.current = null;
144
- mutateStatus("ready");
145
- return null;
146
- }
147
- if (onError && err instanceof Error) {
148
- onError(err);
26
+ if (!chatStore.current.hasChat(chatId)) {
27
+ chatStore.current.addChat(chatId, []);
28
+ }
29
+ const subscribe = useCallback(
30
+ ({
31
+ onStoreChange,
32
+ eventType
33
+ }) => {
34
+ return chatStore.current.subscribe({
35
+ onChatChanged: (event) => {
36
+ if (event.chatId !== chatId || event.type !== eventType) {
37
+ return;
38
+ }
39
+ onStoreChange();
149
40
  }
150
- setError(err);
151
- mutateStatus("error");
152
- }
153
- const messages2 = messagesRef.current;
154
- if (shouldResubmitMessages({
155
- originalMaxToolInvocationStep: maxStep,
156
- originalMessageCount: messageCount,
157
- maxSteps,
158
- messages: messages2
159
- })) {
160
- await triggerRequest({ messages: messages2 });
161
- }
41
+ });
162
42
  },
163
- [
164
- mutate,
165
- mutateStatus,
166
- api,
167
- extraMetadataRef,
168
- onFinish,
169
- onError,
170
- setError,
171
- streamProtocol,
172
- experimental_prepareRequestBody,
173
- onToolCall,
174
- maxSteps,
175
- messagesRef,
176
- abortControllerRef,
177
- generateId,
178
- fetch2,
179
- throttleWaitMs,
180
- chatId,
181
- messageMetadataSchema
182
- ]
43
+ [chatStore, chatId]
183
44
  );
184
- const append = useCallback(
185
- async (message, { headers: headers2, body: body2 } = {}) => {
186
- var _a;
187
- await triggerRequest({
188
- messages: messagesRef.current.concat({
189
- ...message,
190
- id: (_a = message.id) != null ? _a : generateId()
191
- }),
192
- headers: headers2,
193
- body: body2
45
+ const addToolResult = useCallback(
46
+ (options) => chatStore.current.addToolResult({ chatId, ...options }),
47
+ [chatStore, chatId]
48
+ );
49
+ const stopStream = useCallback(() => {
50
+ chatStore.current.stopStream({ chatId });
51
+ }, [chatStore, chatId]);
52
+ const error = useSyncExternalStore(
53
+ (callback) => subscribe({
54
+ onStoreChange: callback,
55
+ eventType: "chat-status-changed"
56
+ }),
57
+ () => chatStore.current.getError(chatId),
58
+ () => chatStore.current.getError(chatId)
59
+ );
60
+ const status = useSyncExternalStore(
61
+ (callback) => subscribe({
62
+ onStoreChange: callback,
63
+ eventType: "chat-status-changed"
64
+ }),
65
+ () => chatStore.current.getStatus(chatId),
66
+ () => chatStore.current.getStatus(chatId)
67
+ );
68
+ const messages = useSyncExternalStore(
69
+ (callback) => {
70
+ return subscribe({
71
+ onStoreChange: callback,
72
+ eventType: "chat-messages-changed"
194
73
  });
195
74
  },
196
- [triggerRequest, generateId]
75
+ () => chatStore.current.getMessages(chatId),
76
+ () => chatStore.current.getMessages(chatId)
77
+ );
78
+ const append = useCallback(
79
+ (message, { headers, body } = {}) => chatStore.current.submitMessage({
80
+ chatId,
81
+ message,
82
+ headers,
83
+ body,
84
+ onError,
85
+ onToolCall,
86
+ onFinish
87
+ }),
88
+ [chatStore, chatId, onError, onToolCall, onFinish]
197
89
  );
198
90
  const reload = useCallback(
199
- async ({ headers: headers2, body: body2 } = {}) => {
200
- const messages2 = messagesRef.current;
201
- if (messages2.length === 0) {
202
- return null;
203
- }
204
- const lastMessage = messages2[messages2.length - 1];
205
- return triggerRequest({
206
- messages: lastMessage.role === "assistant" ? messages2.slice(0, -1) : messages2,
207
- headers: headers2,
208
- body: body2
209
- });
210
- },
211
- [triggerRequest]
91
+ async ({ headers, body } = {}) => chatStore.current.resubmitLastUserMessage({
92
+ chatId,
93
+ headers,
94
+ body,
95
+ onError,
96
+ onToolCall,
97
+ onFinish
98
+ }),
99
+ [chatStore, chatId, onError, onToolCall, onFinish]
100
+ );
101
+ const stop = useCallback(() => stopStream(), [stopStream]);
102
+ const experimental_resume = useCallback(
103
+ async () => chatStore.current.resumeStream({
104
+ chatId,
105
+ onError,
106
+ onToolCall,
107
+ onFinish
108
+ }),
109
+ [chatStore, chatId, onError, onToolCall, onFinish]
212
110
  );
213
- const stop = useCallback(() => {
214
- if (abortControllerRef.current) {
215
- abortControllerRef.current.abort();
216
- abortControllerRef.current = null;
217
- }
218
- }, []);
219
- const experimental_resume = useCallback(async () => {
220
- const messages2 = messagesRef.current;
221
- triggerRequest({ messages: messages2 }, "resume");
222
- }, [triggerRequest]);
223
111
  const setMessages = useCallback(
224
- (messages2) => {
225
- if (typeof messages2 === "function") {
226
- messages2 = messages2(messagesRef.current);
112
+ (messagesParam) => {
113
+ if (typeof messagesParam === "function") {
114
+ messagesParam = messagesParam(messages);
227
115
  }
228
- mutate(messages2, false);
229
- messagesRef.current = messages2;
116
+ chatStore.current.setMessages({
117
+ id: chatId,
118
+ messages: messagesParam
119
+ });
230
120
  },
231
- [mutate]
121
+ [chatId, messages]
232
122
  );
233
- const [input, setInput] = useState2(initialInput);
123
+ const [input, setInput] = useState(initialInput);
234
124
  const handleSubmit = useCallback(
235
- async (event, options = {}, metadata) => {
125
+ async (event, options = {}) => {
236
126
  var _a;
237
127
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
238
128
  const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await convertFileListToFileUIParts(options == null ? void 0 : options.files);
239
129
  if (!input && fileParts.length === 0)
240
130
  return;
241
- if (metadata) {
242
- extraMetadataRef.current = {
243
- ...extraMetadataRef.current,
244
- ...metadata
245
- };
246
- }
247
- triggerRequest({
248
- messages: messagesRef.current.concat({
131
+ append(
132
+ {
249
133
  id: generateId(),
250
134
  role: "user",
251
135
  metadata: void 0,
252
136
  parts: [...fileParts, { type: "text", text: input }]
253
- }),
254
- headers: options.headers,
255
- body: options.body
256
- });
137
+ },
138
+ {
139
+ headers: options.headers,
140
+ body: options.body
141
+ }
142
+ );
257
143
  setInput("");
258
144
  },
259
- [input, generateId, triggerRequest]
145
+ [input, generateId, append]
260
146
  );
261
147
  const handleInputChange = (e) => {
262
148
  setInput(e.target.value);
263
149
  };
264
- const addToolResult = useCallback(
265
- ({ toolCallId, result }) => {
266
- const currentMessages = messagesRef.current;
267
- updateToolCallResult({
268
- messages: currentMessages,
269
- toolCallId,
270
- toolResult: result
271
- });
272
- mutate(
273
- [
274
- ...currentMessages.slice(0, currentMessages.length - 1),
275
- {
276
- ...currentMessages[currentMessages.length - 1],
277
- // @ts-ignore
278
- // update the revisionId to trigger a re-render
279
- revisionId: generateId()
280
- }
281
- ],
282
- false
283
- );
284
- if (status === "submitted" || status === "streaming") {
285
- return;
286
- }
287
- const lastMessage = currentMessages[currentMessages.length - 1];
288
- if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
289
- triggerRequest({ messages: currentMessages });
290
- }
291
- },
292
- [mutate, status, triggerRequest, generateId]
293
- );
294
150
  return {
295
- messages: messages != null ? messages : [],
151
+ messages,
296
152
  id: chatId,
297
153
  setMessages,
298
154
  error,
@@ -313,8 +169,16 @@ function useChat({
313
169
  import {
314
170
  callCompletionApi
315
171
  } from "ai";
316
- import { useCallback as useCallback2, useEffect as useEffect3, useId, useRef as useRef2, useState as useState3 } from "react";
317
- import useSWR2 from "swr";
172
+ import { useCallback as useCallback2, useEffect, useId, useRef as useRef2, useState as useState2 } from "react";
173
+ import useSWR from "swr";
174
+
175
+ // src/throttle.ts
176
+ import throttleFunction from "throttleit";
177
+ function throttle(fn, waitMs) {
178
+ return waitMs != null ? throttleFunction(fn, waitMs) : fn;
179
+ }
180
+
181
+ // src/use-completion.ts
318
182
  function useCompletion({
319
183
  api = "/api/completion",
320
184
  id,
@@ -331,22 +195,22 @@ function useCompletion({
331
195
  } = {}) {
332
196
  const hookId = useId();
333
197
  const completionId = id || hookId;
334
- const { data, mutate } = useSWR2([api, completionId], null, {
198
+ const { data, mutate } = useSWR([api, completionId], null, {
335
199
  fallbackData: initialCompletion
336
200
  });
337
- const { data: isLoading = false, mutate: mutateLoading } = useSWR2(
201
+ const { data: isLoading = false, mutate: mutateLoading } = useSWR(
338
202
  [completionId, "loading"],
339
203
  null
340
204
  );
341
- const [error, setError] = useState3(void 0);
205
+ const [error, setError] = useState2(void 0);
342
206
  const completion = data;
343
- const [abortController, setAbortController] = useState3(null);
207
+ const [abortController, setAbortController] = useState2(null);
344
208
  const extraMetadataRef = useRef2({
345
209
  credentials,
346
210
  headers,
347
211
  body
348
212
  });
349
- useEffect3(() => {
213
+ useEffect(() => {
350
214
  extraMetadataRef.current = {
351
215
  credentials,
352
216
  headers,
@@ -408,7 +272,7 @@ function useCompletion({
408
272
  },
409
273
  [triggerRequest]
410
274
  );
411
- const [input, setInput] = useState3(initialInput);
275
+ const [input, setInput] = useState2(initialInput);
412
276
  const handleSubmit = useCallback2(
413
277
  (event) => {
414
278
  var _a;
@@ -444,11 +308,11 @@ import {
444
308
  } from "@ai-sdk/provider-utils";
445
309
  import {
446
310
  asSchema,
447
- isDeepEqualData as isDeepEqualData2,
311
+ isDeepEqualData,
448
312
  parsePartialJson
449
313
  } from "ai";
450
- import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState4 } from "react";
451
- import useSWR3 from "swr";
314
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState3 } from "react";
315
+ import useSWR2 from "swr";
452
316
  var getOriginalFetch = () => fetch;
453
317
  function useObject({
454
318
  api,
@@ -464,13 +328,13 @@ function useObject({
464
328
  }) {
465
329
  const hookId = useId2();
466
330
  const completionId = id != null ? id : hookId;
467
- const { data, mutate } = useSWR3(
331
+ const { data, mutate } = useSWR2(
468
332
  [api, completionId],
469
333
  null,
470
334
  { fallbackData: initialValue }
471
335
  );
472
- const [error, setError] = useState4(void 0);
473
- const [isLoading, setIsLoading] = useState4(false);
336
+ const [error, setError] = useState3(void 0);
337
+ const [isLoading, setIsLoading] = useState3(false);
474
338
  const abortControllerRef = useRef3(null);
475
339
  const stop = useCallback3(() => {
476
340
  var _a;
@@ -517,7 +381,7 @@ function useObject({
517
381
  accumulatedText += chunk;
518
382
  const { value } = await parsePartialJson(accumulatedText);
519
383
  const currentObject = value;
520
- if (!isDeepEqualData2(latestObject, currentObject)) {
384
+ if (!isDeepEqualData(latestObject, currentObject)) {
521
385
  latestObject = currentObject;
522
386
  mutate(currentObject);
523
387
  }