@ai-sdk/react 0.0.0-9477ebb9-20250403064906

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/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023 Vercel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # AI SDK: React provider
2
+
3
+ [React](https://react.dev/) UI components for the [AI SDK](https://sdk.vercel.ai/docs):
4
+
5
+ - [`useChat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat) hook
6
+ - [`useCompletion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion) hook
7
+ - [`useObject`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-object) hook
@@ -0,0 +1,238 @@
1
+ import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from '@ai-sdk/ui-utils';
2
+ export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
+ import { FetchFunction } from '@ai-sdk/provider-utils';
4
+ import z from 'zod';
5
+
6
+ type UseChatHelpers = {
7
+ /** Current messages in the chat */
8
+ messages: UIMessage[];
9
+ /** The error object of the API request */
10
+ error: undefined | Error;
11
+ /**
12
+ * Append a user message to the chat list. This triggers the API call to fetch
13
+ * the assistant's response.
14
+ * @param message The message to append
15
+ * @param options Additional options to pass to the API call
16
+ */
17
+ append: (message: Message | CreateMessage, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
18
+ /**
19
+ * Reload the last AI chat response for the given chat history. If the last
20
+ * message isn't from the assistant, it will request the API to generate a
21
+ * new response.
22
+ */
23
+ reload: (chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
24
+ /**
25
+ * Abort the current request immediately, keep the generated tokens if any.
26
+ */
27
+ stop: () => void;
28
+ /**
29
+ * Update the `messages` state locally. This is useful when you want to
30
+ * edit the messages on the client, and then trigger the `reload` method
31
+ * manually to regenerate the AI response.
32
+ */
33
+ setMessages: (messages: Message[] | ((messages: Message[]) => Message[])) => void;
34
+ /** The current value of the input */
35
+ input: string;
36
+ /** setState-powered method to update the input value */
37
+ setInput: React.Dispatch<React.SetStateAction<string>>;
38
+ /** An input/textarea-ready onChange handler to control the value of the input */
39
+ handleInputChange: (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
40
+ /** Form submission handler to automatically reset input and append a user message */
41
+ handleSubmit: (event?: {
42
+ preventDefault?: () => void;
43
+ }, chatRequestOptions?: ChatRequestOptions) => void;
44
+ metadata?: Object;
45
+ /**
46
+ * Whether the API request is in progress
47
+ *
48
+ * @deprecated use `status` instead
49
+ */
50
+ isLoading: boolean;
51
+ /**
52
+ * Hook status:
53
+ *
54
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
55
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
56
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
57
+ * - `error`: An error occurred during the API request, preventing successful completion.
58
+ */
59
+ status: 'submitted' | 'streaming' | 'ready' | 'error';
60
+ /** Additional data added on the server via StreamData. */
61
+ data?: JSONValue[];
62
+ /** Set the data of the chat. You can use this to transform or clear the chat data. */
63
+ setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
64
+ /** The id of the chat */
65
+ id: string;
66
+ };
67
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, experimental_throttle: throttleWaitMs, }?: UseChatOptions & {
68
+ key?: string;
69
+ /**
70
+ * Experimental (React only). When a function is provided, it will be used
71
+ * to prepare the request body for the chat API. This can be useful for
72
+ * customizing the request body based on the messages and data in the chat.
73
+ *
74
+ * @param messages The current messages in the chat.
75
+ * @param requestData The data object passed in the chat request.
76
+ * @param requestBody The request body object passed in the chat request.
77
+ */
78
+ experimental_prepareRequestBody?: (options: {
79
+ id: string;
80
+ messages: UIMessage[];
81
+ requestData?: JSONValue;
82
+ requestBody?: object;
83
+ }) => unknown;
84
+ /**
85
+ Custom throttle wait in ms for the chat messages and data updates.
86
+ Default is undefined, which disables throttling.
87
+ */
88
+ experimental_throttle?: number;
89
+ /**
90
+ Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
91
+ Must be at least 1.
92
+
93
+ A maximum number is required to prevent infinite loops in the case of misconfigured tools.
94
+
95
+ By default, it's set to 1, which means that only a single LLM call is made.
96
+ */
97
+ maxSteps?: number;
98
+ }): UseChatHelpers & {
99
+ addToolResult: ({ toolCallId, result, }: {
100
+ toolCallId: string;
101
+ result: any;
102
+ }) => void;
103
+ };
104
+
105
+ type UseCompletionHelpers = {
106
+ /** The current completion result */
107
+ completion: string;
108
+ /**
109
+ * Send a new prompt to the API endpoint and update the completion state.
110
+ */
111
+ complete: (prompt: string, options?: RequestOptions) => Promise<string | null | undefined>;
112
+ /** The error object of the API request */
113
+ error: undefined | Error;
114
+ /**
115
+ * Abort the current API request but keep the generated tokens.
116
+ */
117
+ stop: () => void;
118
+ /**
119
+ * Update the `completion` state locally.
120
+ */
121
+ setCompletion: (completion: string) => void;
122
+ /** The current value of the input */
123
+ input: string;
124
+ /** setState-powered method to update the input value */
125
+ setInput: React.Dispatch<React.SetStateAction<string>>;
126
+ /**
127
+ * An input/textarea-ready onChange handler to control the value of the input
128
+ * @example
129
+ * ```jsx
130
+ * <input onChange={handleInputChange} value={input} />
131
+ * ```
132
+ */
133
+ handleInputChange: (event: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
134
+ /**
135
+ * Form submission handler to automatically reset input and append a user message
136
+ * @example
137
+ * ```jsx
138
+ * <form onSubmit={handleSubmit}>
139
+ * <input onChange={handleInputChange} value={input} />
140
+ * </form>
141
+ * ```
142
+ */
143
+ handleSubmit: (event?: {
144
+ preventDefault?: () => void;
145
+ }) => void;
146
+ /** Whether the API request is in progress */
147
+ isLoading: boolean;
148
+ /** Additional data added on the server via StreamData */
149
+ data?: JSONValue[];
150
+ };
151
+ declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onResponse, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
152
+ /**
153
+ * Custom throttle wait in ms for the completion and data updates.
154
+ * Default is undefined, which disables throttling.
155
+ */
156
+ experimental_throttle?: number;
157
+ }): UseCompletionHelpers;
158
+
159
+ type Experimental_UseObjectOptions<RESULT> = {
160
+ /**
161
+ * The API endpoint. It should stream JSON that matches the schema as chunked text.
162
+ */
163
+ api: string;
164
+ /**
165
+ * A Zod schema that defines the shape of the complete object.
166
+ */
167
+ schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
168
+ /**
169
+ * An unique identifier. If not provided, a random one will be
170
+ * generated. When provided, the `useObject` hook with the same `id` will
171
+ * have shared states across components.
172
+ */
173
+ id?: string;
174
+ /**
175
+ * An optional value for the initial object.
176
+ */
177
+ initialValue?: DeepPartial<RESULT>;
178
+ /**
179
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
180
+ or to provide a custom fetch implementation for e.g. testing.
181
+ */
182
+ fetch?: FetchFunction;
183
+ /**
184
+ Callback that is called when the stream has finished.
185
+ */
186
+ onFinish?: (event: {
187
+ /**
188
+ The generated object (typed according to the schema).
189
+ Can be undefined if the final object does not match the schema.
190
+ */
191
+ object: RESULT | undefined;
192
+ /**
193
+ Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
194
+ */
195
+ error: Error | undefined;
196
+ }) => Promise<void> | void;
197
+ /**
198
+ * Callback function to be called when an error is encountered.
199
+ */
200
+ onError?: (error: Error) => void;
201
+ /**
202
+ * Additional HTTP headers to be included in the request.
203
+ */
204
+ headers?: Record<string, string> | Headers;
205
+ /**
206
+ * The credentials mode to be used for the fetch request.
207
+ * Possible values are: 'omit', 'same-origin', 'include'.
208
+ * Defaults to 'same-origin'.
209
+ */
210
+ credentials?: RequestCredentials;
211
+ };
212
+ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
213
+ /**
214
+ * Calls the API with the provided input as JSON body.
215
+ */
216
+ submit: (input: INPUT) => void;
217
+ /**
218
+ * The current value for the generated object. Updated as the API streams JSON chunks.
219
+ */
220
+ object: DeepPartial<RESULT> | undefined;
221
+ /**
222
+ * The error object of the API request if any.
223
+ */
224
+ error: Error | undefined;
225
+ /**
226
+ * Flag that indicates whether an API request is in progress.
227
+ */
228
+ isLoading: boolean;
229
+ /**
230
+ * Abort the current request immediately, keep the current partial object if any.
231
+ */
232
+ stop: () => void;
233
+ };
234
+ declare function useObject<RESULT, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
235
+ initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
236
+ declare const experimental_useObject: typeof useObject;
237
+
238
+ export { Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
@@ -0,0 +1,238 @@
1
+ import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from '@ai-sdk/ui-utils';
2
+ export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
+ import { FetchFunction } from '@ai-sdk/provider-utils';
4
+ import z from 'zod';
5
+
6
+ type UseChatHelpers = {
7
+ /** Current messages in the chat */
8
+ messages: UIMessage[];
9
+ /** The error object of the API request */
10
+ error: undefined | Error;
11
+ /**
12
+ * Append a user message to the chat list. This triggers the API call to fetch
13
+ * the assistant's response.
14
+ * @param message The message to append
15
+ * @param options Additional options to pass to the API call
16
+ */
17
+ append: (message: Message | CreateMessage, chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
18
+ /**
19
+ * Reload the last AI chat response for the given chat history. If the last
20
+ * message isn't from the assistant, it will request the API to generate a
21
+ * new response.
22
+ */
23
+ reload: (chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
24
+ /**
25
+ * Abort the current request immediately, keep the generated tokens if any.
26
+ */
27
+ stop: () => void;
28
+ /**
29
+ * Update the `messages` state locally. This is useful when you want to
30
+ * edit the messages on the client, and then trigger the `reload` method
31
+ * manually to regenerate the AI response.
32
+ */
33
+ setMessages: (messages: Message[] | ((messages: Message[]) => Message[])) => void;
34
+ /** The current value of the input */
35
+ input: string;
36
+ /** setState-powered method to update the input value */
37
+ setInput: React.Dispatch<React.SetStateAction<string>>;
38
+ /** An input/textarea-ready onChange handler to control the value of the input */
39
+ handleInputChange: (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
40
+ /** Form submission handler to automatically reset input and append a user message */
41
+ handleSubmit: (event?: {
42
+ preventDefault?: () => void;
43
+ }, chatRequestOptions?: ChatRequestOptions) => void;
44
+ metadata?: Object;
45
+ /**
46
+ * Whether the API request is in progress
47
+ *
48
+ * @deprecated use `status` instead
49
+ */
50
+ isLoading: boolean;
51
+ /**
52
+ * Hook status:
53
+ *
54
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
55
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
56
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
57
+ * - `error`: An error occurred during the API request, preventing successful completion.
58
+ */
59
+ status: 'submitted' | 'streaming' | 'ready' | 'error';
60
+ /** Additional data added on the server via StreamData. */
61
+ data?: JSONValue[];
62
+ /** Set the data of the chat. You can use this to transform or clear the chat data. */
63
+ setData: (data: JSONValue[] | undefined | ((data: JSONValue[] | undefined) => JSONValue[] | undefined)) => void;
64
+ /** The id of the chat */
65
+ id: string;
66
+ };
67
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onToolCall, experimental_prepareRequestBody, maxSteps, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, experimental_throttle: throttleWaitMs, }?: UseChatOptions & {
68
+ key?: string;
69
+ /**
70
+ * Experimental (React only). When a function is provided, it will be used
71
+ * to prepare the request body for the chat API. This can be useful for
72
+ * customizing the request body based on the messages and data in the chat.
73
+ *
74
+ * @param messages The current messages in the chat.
75
+ * @param requestData The data object passed in the chat request.
76
+ * @param requestBody The request body object passed in the chat request.
77
+ */
78
+ experimental_prepareRequestBody?: (options: {
79
+ id: string;
80
+ messages: UIMessage[];
81
+ requestData?: JSONValue;
82
+ requestBody?: object;
83
+ }) => unknown;
84
+ /**
85
+ Custom throttle wait in ms for the chat messages and data updates.
86
+ Default is undefined, which disables throttling.
87
+ */
88
+ experimental_throttle?: number;
89
+ /**
90
+ Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
91
+ Must be at least 1.
92
+
93
+ A maximum number is required to prevent infinite loops in the case of misconfigured tools.
94
+
95
+ By default, it's set to 1, which means that only a single LLM call is made.
96
+ */
97
+ maxSteps?: number;
98
+ }): UseChatHelpers & {
99
+ addToolResult: ({ toolCallId, result, }: {
100
+ toolCallId: string;
101
+ result: any;
102
+ }) => void;
103
+ };
104
+
105
+ type UseCompletionHelpers = {
106
+ /** The current completion result */
107
+ completion: string;
108
+ /**
109
+ * Send a new prompt to the API endpoint and update the completion state.
110
+ */
111
+ complete: (prompt: string, options?: RequestOptions) => Promise<string | null | undefined>;
112
+ /** The error object of the API request */
113
+ error: undefined | Error;
114
+ /**
115
+ * Abort the current API request but keep the generated tokens.
116
+ */
117
+ stop: () => void;
118
+ /**
119
+ * Update the `completion` state locally.
120
+ */
121
+ setCompletion: (completion: string) => void;
122
+ /** The current value of the input */
123
+ input: string;
124
+ /** setState-powered method to update the input value */
125
+ setInput: React.Dispatch<React.SetStateAction<string>>;
126
+ /**
127
+ * An input/textarea-ready onChange handler to control the value of the input
128
+ * @example
129
+ * ```jsx
130
+ * <input onChange={handleInputChange} value={input} />
131
+ * ```
132
+ */
133
+ handleInputChange: (event: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
134
+ /**
135
+ * Form submission handler to automatically reset input and append a user message
136
+ * @example
137
+ * ```jsx
138
+ * <form onSubmit={handleSubmit}>
139
+ * <input onChange={handleInputChange} value={input} />
140
+ * </form>
141
+ * ```
142
+ */
143
+ handleSubmit: (event?: {
144
+ preventDefault?: () => void;
145
+ }) => void;
146
+ /** Whether the API request is in progress */
147
+ isLoading: boolean;
148
+ /** Additional data added on the server via StreamData */
149
+ data?: JSONValue[];
150
+ };
151
+ declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onResponse, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
152
+ /**
153
+ * Custom throttle wait in ms for the completion and data updates.
154
+ * Default is undefined, which disables throttling.
155
+ */
156
+ experimental_throttle?: number;
157
+ }): UseCompletionHelpers;
158
+
159
+ type Experimental_UseObjectOptions<RESULT> = {
160
+ /**
161
+ * The API endpoint. It should stream JSON that matches the schema as chunked text.
162
+ */
163
+ api: string;
164
+ /**
165
+ * A Zod schema that defines the shape of the complete object.
166
+ */
167
+ schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
168
+ /**
169
+ * An unique identifier. If not provided, a random one will be
170
+ * generated. When provided, the `useObject` hook with the same `id` will
171
+ * have shared states across components.
172
+ */
173
+ id?: string;
174
+ /**
175
+ * An optional value for the initial object.
176
+ */
177
+ initialValue?: DeepPartial<RESULT>;
178
+ /**
179
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
180
+ or to provide a custom fetch implementation for e.g. testing.
181
+ */
182
+ fetch?: FetchFunction;
183
+ /**
184
+ Callback that is called when the stream has finished.
185
+ */
186
+ onFinish?: (event: {
187
+ /**
188
+ The generated object (typed according to the schema).
189
+ Can be undefined if the final object does not match the schema.
190
+ */
191
+ object: RESULT | undefined;
192
+ /**
193
+ Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
194
+ */
195
+ error: Error | undefined;
196
+ }) => Promise<void> | void;
197
+ /**
198
+ * Callback function to be called when an error is encountered.
199
+ */
200
+ onError?: (error: Error) => void;
201
+ /**
202
+ * Additional HTTP headers to be included in the request.
203
+ */
204
+ headers?: Record<string, string> | Headers;
205
+ /**
206
+ * The credentials mode to be used for the fetch request.
207
+ * Possible values are: 'omit', 'same-origin', 'include'.
208
+ * Defaults to 'same-origin'.
209
+ */
210
+ credentials?: RequestCredentials;
211
+ };
212
+ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
213
+ /**
214
+ * Calls the API with the provided input as JSON body.
215
+ */
216
+ submit: (input: INPUT) => void;
217
+ /**
218
+ * The current value for the generated object. Updated as the API streams JSON chunks.
219
+ */
220
+ object: DeepPartial<RESULT> | undefined;
221
+ /**
222
+ * The error object of the API request if any.
223
+ */
224
+ error: Error | undefined;
225
+ /**
226
+ * Flag that indicates whether an API request is in progress.
227
+ */
228
+ isLoading: boolean;
229
+ /**
230
+ * Abort the current request immediately, keep the current partial object if any.
231
+ */
232
+ stop: () => void;
233
+ };
234
+ declare function useObject<RESULT, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
235
+ initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
236
+ declare const experimental_useObject: typeof useObject;
237
+
238
+ export { Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };