forked from vercel/ai
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-completion.ts
213 lines (193 loc) · 5.15 KB
/
use-completion.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
import {
JSONValue,
RequestOptions,
UseCompletionOptions,
callCompletionApi,
} from '@ai-sdk/ui-utils';
import { useCallback, useEffect, useId, useRef, useState } from 'react';
import useSWR from 'swr';
export type { UseCompletionOptions };
export type UseCompletionHelpers = {
/** The current completion result */
completion: string;
/**
* Send a new prompt to the API endpoint and update the completion state.
*/
complete: (
prompt: string,
options?: RequestOptions,
) => Promise<string | null | undefined>;
/** The error object of the API request */
error: undefined | Error;
/**
* Abort the current API request but keep the generated tokens.
*/
stop: () => void;
/**
* Update the `completion` state locally.
*/
setCompletion: (completion: string) => void;
/** The current value of the input */
input: string;
/** setState-powered method to update the input value */
setInput: React.Dispatch<React.SetStateAction<string>>;
/**
* An input/textarea-ready onChange handler to control the value of the input
* @example
* ```jsx
* <input onChange={handleInputChange} value={input} />
* ```
*/
handleInputChange: (
event:
| React.ChangeEvent<HTMLInputElement>
| React.ChangeEvent<HTMLTextAreaElement>,
) => void;
/**
* Form submission handler to automatically reset input and append a user message
* @example
* ```jsx
* <form onSubmit={handleSubmit}>
* <input onChange={handleInputChange} value={input} />
* </form>
* ```
*/
handleSubmit: (event?: { preventDefault?: () => void }) => void;
/** Whether the API request is in progress */
isLoading: boolean;
/** Additional data added on the server via StreamData */
data?: JSONValue[];
};
export function useCompletion({
api = '/api/completion',
id,
initialCompletion = '',
initialInput = '',
credentials,
headers,
body,
streamMode,
streamProtocol,
fetch,
onResponse,
onFinish,
onError,
}: UseCompletionOptions = {}): UseCompletionHelpers {
// streamMode is deprecated, use streamProtocol instead.
if (streamMode) {
streamProtocol ??= streamMode === 'text' ? 'text' : undefined;
}
// Generate an unique id for the completion 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<string>([api, completionId], null, {
fallbackData: initialCompletion,
});
const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(
[completionId, 'loading'],
null,
);
const { data: streamData, mutate: mutateStreamData } = useSWR<
JSONValue[] | undefined
>([completionId, 'streamData'], null);
const [error, setError] = useState<undefined | Error>(undefined);
const completion = data!;
// Abort controller to cancel the current API call.
const [abortController, setAbortController] =
useState<AbortController | null>(null);
const extraMetadataRef = useRef({
credentials,
headers,
body,
});
useEffect(() => {
extraMetadataRef.current = {
credentials,
headers,
body,
};
}, [credentials, headers, body]);
const triggerRequest = useCallback(
async (prompt: string, options?: RequestOptions) =>
callCompletionApi({
api,
prompt,
credentials: extraMetadataRef.current.credentials,
headers: { ...extraMetadataRef.current.headers, ...options?.headers },
body: {
...extraMetadataRef.current.body,
...options?.body,
},
streamProtocol,
fetch,
setCompletion: completion => mutate(completion, false),
setLoading: mutateLoading,
setError,
setAbortController,
onResponse,
onFinish,
onError,
onData: data => {
mutateStreamData([...(streamData || []), ...(data || [])], false);
},
}),
[
mutate,
mutateLoading,
api,
extraMetadataRef,
setAbortController,
onResponse,
onFinish,
onError,
setError,
streamData,
streamProtocol,
fetch,
mutateStreamData,
],
);
const stop = useCallback(() => {
if (abortController) {
abortController.abort();
setAbortController(null);
}
}, [abortController]);
const setCompletion = useCallback(
(completion: string) => {
mutate(completion, false);
},
[mutate],
);
const complete = useCallback<UseCompletionHelpers['complete']>(
async (prompt, options) => {
return triggerRequest(prompt, options);
},
[triggerRequest],
);
const [input, setInput] = useState(initialInput);
const handleSubmit = useCallback(
(event?: { preventDefault?: () => void }) => {
event?.preventDefault?.();
return input ? complete(input) : undefined;
},
[input, complete],
);
const handleInputChange = (e: any) => {
setInput(e.target.value);
};
return {
completion,
complete,
error,
setCompletion,
stop,
input,
setInput,
handleInputChange,
handleSubmit,
isLoading,
data: streamData,
};
}