@ai-sdk/react 2.0.0-canary.22 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 2.0.0-canary.23
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [bedb239]
8
+ - Updated dependencies [507ac1d]
9
+ - Updated dependencies [2b9bbcd]
10
+ - Updated dependencies [f7e8bf4]
11
+ - Updated dependencies [cda32ba]
12
+ - Updated dependencies [50f0362]
13
+ - Updated dependencies [ed675de]
14
+ - Updated dependencies [faf8446]
15
+ - Updated dependencies [64f6d64]
16
+ - ai@5.0.0-canary.24
17
+ - @ai-sdk/provider-utils@3.0.0-canary.19
18
+
3
19
  ## 2.0.0-canary.22
4
20
 
5
21
  ### Major Changes
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIDataTypes, UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
3
  import { FetchFunction } from '@ai-sdk/provider-utils';
4
4
  import z from 'zod';
5
5
 
6
- type UseChatHelpers<MESSAGE_METADATA = unknown> = {
6
+ type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes> = {
7
7
  /**
8
8
  * The id of the chat.
9
9
  */
@@ -18,7 +18,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
18
18
  */
19
19
  readonly status: 'submitted' | 'streaming' | 'ready' | 'error';
20
20
  /** Current messages in the chat */
21
- readonly messages: UIMessage<MESSAGE_METADATA>[];
21
+ readonly messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
22
22
  /** The error object of the API request */
23
23
  readonly error: undefined | Error;
24
24
  /**
@@ -28,7 +28,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
28
28
  * @param message The message to append
29
29
  * @param options Additional options to pass to the API call
30
30
  */
31
- append: (message: CreateUIMessage<MESSAGE_METADATA>, options?: ChatRequestOptions) => Promise<void>;
31
+ append: (message: CreateUIMessage<MESSAGE_METADATA, DATA_TYPES>, options?: ChatRequestOptions) => Promise<void>;
32
32
  /**
33
33
  * Reload the last AI chat response for the given chat history. If the last
34
34
  * message isn't from the assistant, it will request the API to generate a
@@ -48,7 +48,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
48
48
  * edit the messages on the client, and then trigger the `reload` method
49
49
  * manually to regenerate the AI response.
50
50
  */
51
- setMessages: (messages: UIMessage<MESSAGE_METADATA>[] | ((messages: UIMessage<MESSAGE_METADATA>[]) => UIMessage<MESSAGE_METADATA>[])) => void;
51
+ setMessages: (messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[] | ((messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) => UIMessage<MESSAGE_METADATA, DATA_TYPES>[])) => void;
52
52
  /** The current value of the input */
53
53
  input: string;
54
54
  /** setState-powered method to update the input value */
@@ -66,13 +66,13 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
66
66
  result: any;
67
67
  }) => void;
68
68
  };
69
- declare function useChat<MESSAGE_METADATA>({ id, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA> & {
69
+ declare function useChat<MESSAGE_METADATA = unknown, DATA_TYPES extends Record<string, unknown> = Record<string, unknown>>({ id, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA, DATA_TYPES> & {
70
70
  /**
71
71
  Custom throttle wait in ms for the chat messages and data updates.
72
72
  Default is undefined, which disables throttling.
73
73
  */
74
74
  experimental_throttle?: number;
75
- }): UseChatHelpers<MESSAGE_METADATA>;
75
+ }): UseChatHelpers<MESSAGE_METADATA, DATA_TYPES>;
76
76
 
77
77
  type UseCompletionHelpers = {
78
78
  /** The current completion result */
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIDataTypes, UIMessage, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
3
  import { FetchFunction } from '@ai-sdk/provider-utils';
4
4
  import z from 'zod';
5
5
 
6
- type UseChatHelpers<MESSAGE_METADATA = unknown> = {
6
+ type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes> = {
7
7
  /**
8
8
  * The id of the chat.
9
9
  */
@@ -18,7 +18,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
18
18
  */
19
19
  readonly status: 'submitted' | 'streaming' | 'ready' | 'error';
20
20
  /** Current messages in the chat */
21
- readonly messages: UIMessage<MESSAGE_METADATA>[];
21
+ readonly messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
22
22
  /** The error object of the API request */
23
23
  readonly error: undefined | Error;
24
24
  /**
@@ -28,7 +28,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
28
28
  * @param message The message to append
29
29
  * @param options Additional options to pass to the API call
30
30
  */
31
- append: (message: CreateUIMessage<MESSAGE_METADATA>, options?: ChatRequestOptions) => Promise<void>;
31
+ append: (message: CreateUIMessage<MESSAGE_METADATA, DATA_TYPES>, options?: ChatRequestOptions) => Promise<void>;
32
32
  /**
33
33
  * Reload the last AI chat response for the given chat history. If the last
34
34
  * message isn't from the assistant, it will request the API to generate a
@@ -48,7 +48,7 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
48
48
  * edit the messages on the client, and then trigger the `reload` method
49
49
  * manually to regenerate the AI response.
50
50
  */
51
- setMessages: (messages: UIMessage<MESSAGE_METADATA>[] | ((messages: UIMessage<MESSAGE_METADATA>[]) => UIMessage<MESSAGE_METADATA>[])) => void;
51
+ setMessages: (messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[] | ((messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) => UIMessage<MESSAGE_METADATA, DATA_TYPES>[])) => void;
52
52
  /** The current value of the input */
53
53
  input: string;
54
54
  /** setState-powered method to update the input value */
@@ -66,13 +66,13 @@ type UseChatHelpers<MESSAGE_METADATA = unknown> = {
66
66
  result: any;
67
67
  }) => void;
68
68
  };
69
- declare function useChat<MESSAGE_METADATA>({ id, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA> & {
69
+ declare function useChat<MESSAGE_METADATA = unknown, DATA_TYPES extends Record<string, unknown> = Record<string, unknown>>({ id, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA, DATA_TYPES> & {
70
70
  /**
71
71
  Custom throttle wait in ms for the chat messages and data updates.
72
72
  Default is undefined, which disables throttling.
73
73
  */
74
74
  experimental_throttle?: number;
75
- }): UseChatHelpers<MESSAGE_METADATA>;
75
+ }): UseChatHelpers<MESSAGE_METADATA, DATA_TYPES>;
76
76
 
77
77
  type UseCompletionHelpers = {
78
78
  /** The current completion result */
package/dist/index.js CHANGED
@@ -176,7 +176,7 @@ function useChat({
176
176
  );
177
177
  setInput("");
178
178
  },
179
- [input, generateId, append, messages]
179
+ [input, generateId, append]
180
180
  );
181
181
  const handleInputChange = (e) => {
182
182
  setInput(e.target.value);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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 type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n ChatStore,\n convertFileListToFileUIParts,\n defaultChatStore,\n generateId as generateIdFunc,\n type ChatStoreEvent,\n} from 'ai';\nimport { useCallback, useRef, useState, useSyncExternalStore } from 'react';\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 id,\n initialInput = '',\n onToolCall,\n onFinish,\n onError,\n generateId = generateIdFunc,\n experimental_throttle: throttleWaitMs,\n chatStore: chatStoreArg,\n}: UseChatOptions<MESSAGE_METADATA> & {\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\n // chat store setup\n // TODO enable as arg\n const chatStore = useRef(\n chatStoreArg ??\n defaultChatStore<MESSAGE_METADATA>({\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>['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>,\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>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\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, messages],\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":";;;;;;;;;;;;;;;;;;;;;;;;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C/C;AAEA,UAAI,kBAAkB;AACtB,UAAI,eAAgD;AAEpD,YAAM,SAAS,KAAK,YAAY,IAAI,kBAAkB,CAAC,EAAE;AAAA,QACvD,IAAI,eAAuB;AAAA,UACzB,MAAM,MAAM,OAAO;AACjB,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,UAAM,6BAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,KAAC,4BAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,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"]}
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 {\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A,QAC7B;AAAA,MACF;AAEA,UAAI,SAAS,QAAQ,MAAM;AACzB,cAAM,IAAI,MAAM,6BAA6B;AAAA,MAC/C;AAEA,UAAI,kBAAkB;AACtB,UAAI,eAAgD;AAEpD,YAAM,SAAS,KAAK,YAAY,IAAI,kBAAkB,CAAC,EAAE;AAAA,QACvD,IAAI,eAAuB;AAAA,UACzB,MAAM,MAAM,OAAO;AACjB,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,UAAM,6BAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,KAAC,4BAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,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
@@ -142,7 +142,7 @@ function useChat({
142
142
  );
143
143
  setInput("");
144
144
  },
145
- [input, generateId, append, messages]
145
+ [input, generateId, append]
146
146
  );
147
147
  const handleInputChange = (e) => {
148
148
  setInput(e.target.value);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/use-completion.ts","../src/throttle.ts","../src/use-object.ts"],"sourcesContent":["import type {\n ChatRequestOptions,\n CreateUIMessage,\n FileUIPart,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n ChatStore,\n convertFileListToFileUIParts,\n defaultChatStore,\n generateId as generateIdFunc,\n type ChatStoreEvent,\n} from 'ai';\nimport { useCallback, useRef, useState, useSyncExternalStore } from 'react';\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 id,\n initialInput = '',\n onToolCall,\n onFinish,\n onError,\n generateId = generateIdFunc,\n experimental_throttle: throttleWaitMs,\n chatStore: chatStoreArg,\n}: UseChatOptions<MESSAGE_METADATA> & {\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\n // chat store setup\n // TODO enable as arg\n const chatStore = useRef(\n chatStoreArg ??\n defaultChatStore<MESSAGE_METADATA>({\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>['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>,\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>[]\n | ((\n messages: UIMessage<MESSAGE_METADATA>[],\n ) => UIMessage<MESSAGE_METADATA>[]),\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, messages],\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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A,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useRef","useState","fetch","useState","useRef","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/use-completion.ts","../src/throttle.ts","../src/use-object.ts"],"sourcesContent":["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,EAEE;AAAA,EACA;AAAA,EACA,cAAc;AAAA,OAQT;AACP,SAAS,aAAa,QAAQ,UAAU,4BAA4B;AAuG7D,SAAS,QAGd;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,WAAW;AACb,IAMI,CAAC,GAAiD;AAEpD,QAAM,CAAC,MAAM,IAAI,SAAS,UAAU;AAGpC,QAAM,SAAS,kBAAM;AAIrB,QAAM,YAAY;AAAA,IAChB,sCACE,iBAA+C;AAAA,MAC7C,KAAK;AAAA,MACL;AAAA,IACF,CAAC;AAAA,EACL;AAGA,MAAI,CAAC,UAAU,QAAQ,QAAQ,MAAM,GAAG;AACtC,cAAU,QAAQ,QAAQ,QAAQ,CAAC,CAAC;AAAA,EACtC;AAEA,QAAM,YAAY;AAAA,IAChB,CAAC;AAAA,MACC;AAAA,MACA;AAAA,IACF,MAGM;AACJ,aAAO,UAAU,QAAQ,UAAU;AAAA,QACjC,eAAe,WAAS;AACtB,cAAI,MAAM,WAAW,UAAU,MAAM,SAAS,WAAW;AACvD;AAAA,UACF;AAEA,wBAAc;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,CAAC,WAAW,MAAM;AAAA,EACpB;AAEA,QAAM,gBAAgB;AAAA,IACpB,CACE,YAIG,UAAU,QAAQ,cAAc,EAAE,QAAQ,GAAG,QAAQ,CAAC;AAAA,IAC3D,CAAC,WAAW,MAAM;AAAA,EACpB;AAEA,QAAM,aAAa,YAAY,MAAM;AACnC,cAAU,QAAQ,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AClB,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":["useCallback","useRef","useState","fetch","useState","useRef","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "2.0.0-canary.22",
3
+ "version": "2.0.0-canary.23",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "swr": "^2.2.5",
23
23
  "throttleit": "2.1.0",
24
- "ai": "5.0.0-canary.23",
25
- "@ai-sdk/provider-utils": "3.0.0-canary.18"
24
+ "ai": "5.0.0-canary.24",
25
+ "@ai-sdk/provider-utils": "3.0.0-canary.19"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@testing-library/jest-dom": "^6.6.3",
@@ -37,7 +37,7 @@
37
37
  "react-dom": "^18",
38
38
  "tsup": "^7.2.0",
39
39
  "typescript": "5.8.3",
40
- "zod": "3.23.8",
40
+ "zod": "3.24.4",
41
41
  "@vercel/ai-tsconfig": "0.0.0",
42
42
  "eslint-config-vercel-ai": "0.0.0"
43
43
  },