forked from vercel/ai
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-object.ts
230 lines (193 loc) · 5.75 KB
/
use-object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import {
FetchFunction,
isAbortError,
safeValidateTypes,
} from '@ai-sdk/provider-utils';
import {
asSchema,
DeepPartial,
isDeepEqualData,
parsePartialJson,
Schema,
} from '@ai-sdk/ui-utils';
import { useCallback, useId, useRef, useState } from 'react';
import useSWR from 'swr';
import z from 'zod';
// use function to allow for mocking in tests:
const getOriginalFetch = () => fetch;
export type Experimental_UseObjectOptions<RESULT> = {
/**
* The API endpoint. It should stream JSON that matches the schema as chunked text.
*/
api: string;
/**
* A Zod schema that defines the shape of the complete object.
*/
schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
/**
* An unique identifier. If not provided, a random one will be
* generated. When provided, the `useObject` hook with the same `id` will
* have shared states across components.
*/
id?: string;
/**
* An optional value for the initial object.
*/
initialValue?: DeepPartial<RESULT>;
/**
Custom fetch implementation. You can use it as a middleware to intercept requests,
or to provide a custom fetch implementation for e.g. testing.
*/
fetch?: FetchFunction;
/**
Callback that is called when the stream has finished.
*/
onFinish?: (event: {
/**
The generated object (typed according to the schema).
Can be undefined if the final object does not match the schema.
*/
object: RESULT | undefined;
/**
Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
*/
error: Error | undefined;
}) => Promise<void> | void;
/**
* Callback function to be called when an error is encountered.
*/
onError?: (error: Error) => void;
};
export type Experimental_UseObjectHelpers<RESULT, INPUT> = {
/**
* @deprecated Use `submit` instead.
*/
setInput: (input: INPUT) => void;
/**
* Calls the API with the provided input as JSON body.
*/
submit: (input: INPUT) => void;
/**
* The current value for the generated object. Updated as the API streams JSON chunks.
*/
object: DeepPartial<RESULT> | undefined;
/**
* The error object of the API request if any.
*/
error: Error | undefined;
/**
* Flag that indicates whether an API request is in progress.
*/
isLoading: boolean;
/**
* Abort the current request immediately, keep the current partial object if any.
*/
stop: () => void;
};
function useObject<RESULT, INPUT = any>({
api,
id,
schema, // required, in the future we will use it for validation
initialValue,
fetch,
onError,
onFinish,
}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<
RESULT,
INPUT
> {
// Generate an unique id if not provided.
const hookId = useId();
const completionId = id ?? hookId;
// Store the completion state in SWR, using the completionId as the key to share states.
const { data, mutate } = useSWR<DeepPartial<RESULT>>(
[api, completionId],
null,
{ fallbackData: initialValue },
);
const [error, setError] = useState<undefined | Error>(undefined);
const [isLoading, setIsLoading] = useState(false);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
try {
abortControllerRef.current?.abort();
} catch (ignored) {
} finally {
setIsLoading(false);
abortControllerRef.current = null;
}
}, []);
const submit = async (input: INPUT) => {
try {
mutate(undefined); // reset the data
setIsLoading(true);
setError(undefined);
const abortController = new AbortController();
abortControllerRef.current = abortController;
const actualFetch = fetch ?? getOriginalFetch();
const response = await actualFetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: abortController.signal,
body: JSON.stringify(input),
});
if (!response.ok) {
throw new Error(
(await response.text()) ?? 'Failed to fetch the response.',
);
}
if (response.body == null) {
throw new Error('The response body is empty.');
}
let accumulatedText = '';
let latestObject: DeepPartial<RESULT> | undefined = undefined;
await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
new WritableStream<string>({
write(chunk) {
accumulatedText += chunk;
const { value } = parsePartialJson(accumulatedText);
const currentObject = value as DeepPartial<RESULT>;
if (!isDeepEqualData(latestObject, currentObject)) {
latestObject = currentObject;
mutate(currentObject);
}
},
close() {
setIsLoading(false);
abortControllerRef.current = null;
if (onFinish != null) {
const validationResult = safeValidateTypes({
value: latestObject,
schema: asSchema(schema),
});
onFinish(
validationResult.success
? { object: validationResult.value, error: undefined }
: { object: undefined, error: validationResult.error },
);
}
},
}),
);
} catch (error) {
if (isAbortError(error)) {
return;
}
if (onError && error instanceof Error) {
onError(error);
}
setIsLoading(false);
setError(error instanceof Error ? error : new Error(String(error)));
}
};
return {
setInput: submit, // Deprecated
submit,
object: data,
error,
isLoading,
stop,
};
}
export const experimental_useObject = useObject;