@ai-sdk/react 0.0.52 → 0.0.53

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.
@@ -1,213 +0,0 @@
1
- import {
2
- JSONValue,
3
- RequestOptions,
4
- UseCompletionOptions,
5
- callCompletionApi,
6
- } from '@ai-sdk/ui-utils';
7
- import { useCallback, useEffect, useId, useRef, useState } from 'react';
8
- import useSWR from 'swr';
9
-
10
- export type { UseCompletionOptions };
11
-
12
- export type UseCompletionHelpers = {
13
- /** The current completion result */
14
- completion: string;
15
- /**
16
- * Send a new prompt to the API endpoint and update the completion state.
17
- */
18
- complete: (
19
- prompt: string,
20
- options?: RequestOptions,
21
- ) => Promise<string | null | undefined>;
22
- /** The error object of the API request */
23
- error: undefined | Error;
24
- /**
25
- * Abort the current API request but keep the generated tokens.
26
- */
27
- stop: () => void;
28
- /**
29
- * Update the `completion` state locally.
30
- */
31
- setCompletion: (completion: string) => void;
32
- /** The current value of the input */
33
- input: string;
34
- /** setState-powered method to update the input value */
35
- setInput: React.Dispatch<React.SetStateAction<string>>;
36
- /**
37
- * An input/textarea-ready onChange handler to control the value of the input
38
- * @example
39
- * ```jsx
40
- * <input onChange={handleInputChange} value={input} />
41
- * ```
42
- */
43
- handleInputChange: (
44
- event:
45
- | React.ChangeEvent<HTMLInputElement>
46
- | React.ChangeEvent<HTMLTextAreaElement>,
47
- ) => void;
48
-
49
- /**
50
- * Form submission handler to automatically reset input and append a user message
51
- * @example
52
- * ```jsx
53
- * <form onSubmit={handleSubmit}>
54
- * <input onChange={handleInputChange} value={input} />
55
- * </form>
56
- * ```
57
- */
58
- handleSubmit: (event?: { preventDefault?: () => void }) => void;
59
-
60
- /** Whether the API request is in progress */
61
- isLoading: boolean;
62
- /** Additional data added on the server via StreamData */
63
- data?: JSONValue[];
64
- };
65
-
66
- export function useCompletion({
67
- api = '/api/completion',
68
- id,
69
- initialCompletion = '',
70
- initialInput = '',
71
- credentials,
72
- headers,
73
- body,
74
- streamMode,
75
- streamProtocol,
76
- fetch,
77
- onResponse,
78
- onFinish,
79
- onError,
80
- }: UseCompletionOptions = {}): UseCompletionHelpers {
81
- // streamMode is deprecated, use streamProtocol instead.
82
- if (streamMode) {
83
- streamProtocol ??= streamMode === 'text' ? 'text' : undefined;
84
- }
85
-
86
- // Generate an unique id for the completion if not provided.
87
- const hookId = useId();
88
- const completionId = id || hookId;
89
-
90
- // Store the completion state in SWR, using the completionId as the key to share states.
91
- const { data, mutate } = useSWR<string>([api, completionId], null, {
92
- fallbackData: initialCompletion,
93
- });
94
-
95
- const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(
96
- [completionId, 'loading'],
97
- null,
98
- );
99
-
100
- const { data: streamData, mutate: mutateStreamData } = useSWR<
101
- JSONValue[] | undefined
102
- >([completionId, 'streamData'], null);
103
-
104
- const [error, setError] = useState<undefined | Error>(undefined);
105
- const completion = data!;
106
-
107
- // Abort controller to cancel the current API call.
108
- const [abortController, setAbortController] =
109
- useState<AbortController | null>(null);
110
-
111
- const extraMetadataRef = useRef({
112
- credentials,
113
- headers,
114
- body,
115
- });
116
- useEffect(() => {
117
- extraMetadataRef.current = {
118
- credentials,
119
- headers,
120
- body,
121
- };
122
- }, [credentials, headers, body]);
123
-
124
- const triggerRequest = useCallback(
125
- async (prompt: string, options?: RequestOptions) =>
126
- callCompletionApi({
127
- api,
128
- prompt,
129
- credentials: extraMetadataRef.current.credentials,
130
- headers: { ...extraMetadataRef.current.headers, ...options?.headers },
131
- body: {
132
- ...extraMetadataRef.current.body,
133
- ...options?.body,
134
- },
135
- streamProtocol,
136
- fetch,
137
- setCompletion: completion => mutate(completion, false),
138
- setLoading: mutateLoading,
139
- setError,
140
- setAbortController,
141
- onResponse,
142
- onFinish,
143
- onError,
144
- onData: data => {
145
- mutateStreamData([...(streamData || []), ...(data || [])], false);
146
- },
147
- }),
148
- [
149
- mutate,
150
- mutateLoading,
151
- api,
152
- extraMetadataRef,
153
- setAbortController,
154
- onResponse,
155
- onFinish,
156
- onError,
157
- setError,
158
- streamData,
159
- streamProtocol,
160
- fetch,
161
- mutateStreamData,
162
- ],
163
- );
164
-
165
- const stop = useCallback(() => {
166
- if (abortController) {
167
- abortController.abort();
168
- setAbortController(null);
169
- }
170
- }, [abortController]);
171
-
172
- const setCompletion = useCallback(
173
- (completion: string) => {
174
- mutate(completion, false);
175
- },
176
- [mutate],
177
- );
178
-
179
- const complete = useCallback<UseCompletionHelpers['complete']>(
180
- async (prompt, options) => {
181
- return triggerRequest(prompt, options);
182
- },
183
- [triggerRequest],
184
- );
185
-
186
- const [input, setInput] = useState(initialInput);
187
-
188
- const handleSubmit = useCallback(
189
- (event?: { preventDefault?: () => void }) => {
190
- event?.preventDefault?.();
191
- return input ? complete(input) : undefined;
192
- },
193
- [input, complete],
194
- );
195
-
196
- const handleInputChange = (e: any) => {
197
- setInput(e.target.value);
198
- };
199
-
200
- return {
201
- completion,
202
- complete,
203
- error,
204
- setCompletion,
205
- stop,
206
- input,
207
- setInput,
208
- handleInputChange,
209
- handleSubmit,
210
- isLoading,
211
- data: streamData,
212
- };
213
- }
@@ -1,166 +0,0 @@
1
- import {
2
- mockFetchDataStream,
3
- mockFetchDataStreamWithGenerator,
4
- mockFetchError,
5
- } from '@ai-sdk/ui-utils/test';
6
- import '@testing-library/jest-dom/vitest';
7
- import { cleanup, findByText, render, screen } from '@testing-library/react';
8
- import userEvent from '@testing-library/user-event';
9
- import { useCompletion } from './use-completion';
10
-
11
- describe('stream data stream', () => {
12
- let onFinishResult:
13
- | {
14
- prompt: string;
15
- completion: string;
16
- }
17
- | undefined;
18
-
19
- const TestComponent = () => {
20
- const {
21
- completion,
22
- handleSubmit,
23
- error,
24
- handleInputChange,
25
- input,
26
- isLoading,
27
- } = useCompletion({
28
- onFinish(prompt, completion) {
29
- onFinishResult = { prompt, completion };
30
- },
31
- });
32
-
33
- return (
34
- <div>
35
- <div data-testid="loading">{isLoading.toString()}</div>
36
- <div data-testid="error">{error?.toString()}</div>
37
- <div data-testid="completion">{completion}</div>
38
- <form onSubmit={handleSubmit}>
39
- <input
40
- data-testid="input"
41
- value={input}
42
- placeholder="Say something..."
43
- onChange={handleInputChange}
44
- />
45
- </form>
46
- </div>
47
- );
48
- };
49
-
50
- beforeEach(() => {
51
- render(<TestComponent />);
52
- onFinishResult = undefined;
53
- });
54
-
55
- afterEach(() => {
56
- vi.restoreAllMocks();
57
- cleanup();
58
- });
59
-
60
- describe('render simple stream', () => {
61
- beforeEach(async () => {
62
- mockFetchDataStream({
63
- url: 'https://example.com/api/completion',
64
- chunks: ['0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n'],
65
- });
66
-
67
- await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
68
- });
69
-
70
- it('should render stream', async () => {
71
- await screen.findByTestId('completion');
72
- expect(screen.getByTestId('completion')).toHaveTextContent(
73
- 'Hello, world.',
74
- );
75
- });
76
-
77
- it("should call 'onFinish' callback", async () => {
78
- await screen.findByTestId('completion');
79
- expect(onFinishResult).toEqual({
80
- prompt: 'hi',
81
- completion: 'Hello, world.',
82
- });
83
- });
84
- });
85
-
86
- describe('loading state', () => {
87
- it('should show loading state', async () => {
88
- let finishGeneration: ((value?: unknown) => void) | undefined;
89
- const finishGenerationPromise = new Promise(resolve => {
90
- finishGeneration = resolve;
91
- });
92
-
93
- mockFetchDataStreamWithGenerator({
94
- url: 'https://example.com/api/chat',
95
- chunkGenerator: (async function* generate() {
96
- const encoder = new TextEncoder();
97
- yield encoder.encode('0:"Hello"\n');
98
- await finishGenerationPromise;
99
- })(),
100
- });
101
-
102
- await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
103
-
104
- await screen.findByTestId('loading');
105
- expect(screen.getByTestId('loading')).toHaveTextContent('true');
106
-
107
- finishGeneration?.();
108
-
109
- await findByText(await screen.findByTestId('loading'), 'false');
110
- expect(screen.getByTestId('loading')).toHaveTextContent('false');
111
- });
112
-
113
- it('should reset loading state on error', async () => {
114
- mockFetchError({ statusCode: 404, errorMessage: 'Not found' });
115
-
116
- await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
117
-
118
- await screen.findByTestId('loading');
119
- expect(screen.getByTestId('loading')).toHaveTextContent('false');
120
- });
121
- });
122
- });
123
-
124
- describe('text stream', () => {
125
- const TestComponent = () => {
126
- const { completion, handleSubmit, handleInputChange, input } =
127
- useCompletion({ streamProtocol: 'text' });
128
-
129
- return (
130
- <div>
131
- <div data-testid="completion-text-stream">{completion}</div>
132
- <form onSubmit={handleSubmit}>
133
- <input
134
- data-testid="input-text-stream"
135
- value={input}
136
- placeholder="Say something..."
137
- onChange={handleInputChange}
138
- />
139
- </form>
140
- </div>
141
- );
142
- };
143
-
144
- beforeEach(() => {
145
- render(<TestComponent />);
146
- });
147
-
148
- afterEach(() => {
149
- vi.restoreAllMocks();
150
- cleanup();
151
- });
152
-
153
- it('should render stream', async () => {
154
- mockFetchDataStream({
155
- url: 'https://example.com/api/completion',
156
- chunks: ['Hello', ',', ' world', '.'],
157
- });
158
-
159
- await userEvent.type(screen.getByTestId('input-text-stream'), 'hi{enter}');
160
-
161
- await screen.findByTestId('completion-text-stream');
162
- expect(screen.getByTestId('completion-text-stream')).toHaveTextContent(
163
- 'Hello, world.',
164
- );
165
- });
166
- });
package/src/use-object.ts DELETED
@@ -1,229 +0,0 @@
1
- import {
2
- FetchFunction,
3
- isAbortError,
4
- safeValidateTypes,
5
- } from '@ai-sdk/provider-utils';
6
- import {
7
- asSchema,
8
- DeepPartial,
9
- isDeepEqualData,
10
- parsePartialJson,
11
- Schema,
12
- } from '@ai-sdk/ui-utils';
13
- import { useCallback, useId, useRef, useState } from 'react';
14
- import useSWR from 'swr';
15
- import z from 'zod';
16
-
17
- // use function to allow for mocking in tests:
18
- const getOriginalFetch = () => fetch;
19
-
20
- export type Experimental_UseObjectOptions<RESULT> = {
21
- /**
22
- * The API endpoint. It should stream JSON that matches the schema as chunked text.
23
- */
24
- api: string;
25
-
26
- /**
27
- * A Zod schema that defines the shape of the complete object.
28
- */
29
- schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
30
-
31
- /**
32
- * An unique identifier. If not provided, a random one will be
33
- * generated. When provided, the `useObject` hook with the same `id` will
34
- * have shared states across components.
35
- */
36
- id?: string;
37
-
38
- /**
39
- * An optional value for the initial object.
40
- */
41
- initialValue?: DeepPartial<RESULT>;
42
-
43
- /**
44
- Custom fetch implementation. You can use it as a middleware to intercept requests,
45
- or to provide a custom fetch implementation for e.g. testing.
46
- */
47
- fetch?: FetchFunction;
48
-
49
- /**
50
- Callback that is called when the stream has finished.
51
- */
52
- onFinish?: (event: {
53
- /**
54
- The generated object (typed according to the schema).
55
- Can be undefined if the final object does not match the schema.
56
- */
57
- object: RESULT | undefined;
58
-
59
- /**
60
- Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
61
- */
62
- error: Error | undefined;
63
- }) => Promise<void> | void;
64
-
65
- /**
66
- * Callback function to be called when an error is encountered.
67
- */
68
- onError?: (error: Error) => void;
69
- };
70
-
71
- export type Experimental_UseObjectHelpers<RESULT, INPUT> = {
72
- /**
73
- * @deprecated Use `submit` instead.
74
- */
75
- setInput: (input: INPUT) => void;
76
-
77
- /**
78
- * Calls the API with the provided input as JSON body.
79
- */
80
- submit: (input: INPUT) => void;
81
-
82
- /**
83
- * The current value for the generated object. Updated as the API streams JSON chunks.
84
- */
85
- object: DeepPartial<RESULT> | undefined;
86
-
87
- /**
88
- * The error object of the API request if any.
89
- */
90
- error: undefined | unknown;
91
-
92
- /**
93
- * Flag that indicates whether an API request is in progress.
94
- */
95
- isLoading: boolean;
96
-
97
- /**
98
- * Abort the current request immediately, keep the current partial object if any.
99
- */
100
- stop: () => void;
101
- };
102
-
103
- function useObject<RESULT, INPUT = any>({
104
- api,
105
- id,
106
- schema, // required, in the future we will use it for validation
107
- initialValue,
108
- fetch,
109
- onError,
110
- onFinish,
111
- }: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<
112
- RESULT,
113
- INPUT
114
- > {
115
- // Generate an unique id if not provided.
116
- const hookId = useId();
117
- const completionId = id ?? hookId;
118
-
119
- // Store the completion state in SWR, using the completionId as the key to share states.
120
- const { data, mutate } = useSWR<DeepPartial<RESULT>>(
121
- [api, completionId],
122
- null,
123
- { fallbackData: initialValue },
124
- );
125
-
126
- const [error, setError] = useState<undefined | unknown>(undefined);
127
- const [isLoading, setIsLoading] = useState(false);
128
-
129
- // Abort controller to cancel the current API call.
130
- const abortControllerRef = useRef<AbortController | null>(null);
131
-
132
- const stop = useCallback(() => {
133
- try {
134
- abortControllerRef.current?.abort();
135
- } catch (ignored) {
136
- } finally {
137
- setIsLoading(false);
138
- abortControllerRef.current = null;
139
- }
140
- }, []);
141
-
142
- const submit = async (input: INPUT) => {
143
- try {
144
- mutate(undefined); // reset the data
145
- setIsLoading(true);
146
- setError(undefined);
147
-
148
- const abortController = new AbortController();
149
- abortControllerRef.current = abortController;
150
-
151
- const actualFetch = fetch ?? getOriginalFetch();
152
- const response = await actualFetch(api, {
153
- method: 'POST',
154
- headers: { 'Content-Type': 'application/json' },
155
- signal: abortController.signal,
156
- body: JSON.stringify(input),
157
- });
158
-
159
- if (!response.ok) {
160
- throw new Error(
161
- (await response.text()) ?? 'Failed to fetch the response.',
162
- );
163
- }
164
-
165
- if (response.body == null) {
166
- throw new Error('The response body is empty.');
167
- }
168
-
169
- let accumulatedText = '';
170
- let latestObject: DeepPartial<RESULT> | undefined = undefined;
171
-
172
- await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
173
- new WritableStream<string>({
174
- write(chunk) {
175
- accumulatedText += chunk;
176
-
177
- const { value } = parsePartialJson(accumulatedText);
178
- const currentObject = value as DeepPartial<RESULT>;
179
-
180
- if (!isDeepEqualData(latestObject, currentObject)) {
181
- latestObject = currentObject;
182
-
183
- mutate(currentObject);
184
- }
185
- },
186
-
187
- close() {
188
- setIsLoading(false);
189
- abortControllerRef.current = null;
190
-
191
- if (onFinish != null) {
192
- const validationResult = safeValidateTypes({
193
- value: latestObject,
194
- schema: asSchema(schema),
195
- });
196
-
197
- onFinish(
198
- validationResult.success
199
- ? { object: validationResult.value, error: undefined }
200
- : { object: undefined, error: validationResult.error },
201
- );
202
- }
203
- },
204
- }),
205
- );
206
- } catch (error) {
207
- if (isAbortError(error)) {
208
- return;
209
- }
210
-
211
- if (onError && error instanceof Error) {
212
- onError(error);
213
- }
214
-
215
- setError(error);
216
- }
217
- };
218
-
219
- return {
220
- setInput: submit, // Deprecated
221
- submit,
222
- object: data,
223
- error,
224
- isLoading,
225
- stop,
226
- };
227
- }
228
-
229
- export const experimental_useObject = useObject;