forked from vercel/ai
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-completion.ts
182 lines (159 loc) · 4.37 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
import type {
JSONValue,
RequestOptions,
UseCompletionOptions,
} from '@ai-sdk/ui-utils';
import { callCompletionApi } from '@ai-sdk/ui-utils';
import { useSWR } from 'sswr';
import { Readable, Writable, derived, get, writable } from 'svelte/store';
export type { UseCompletionOptions };
export type UseCompletionHelpers = {
/** The current completion result */
completion: Readable<string>;
/** The error object of the API request */
error: Readable<undefined | Error>;
/**
* Send a new prompt to the API endpoint and update the completion state.
*/
complete: (
prompt: string,
options?: RequestOptions,
) => Promise<string | null | undefined>;
/**
* 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: Writable<string>;
/**
* 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: Readable<boolean | undefined>;
/** Additional data added on the server via StreamData */
data: Readable<JSONValue[] | undefined>;
};
let uniqueId = 0;
const store: Record<string, any> = {};
/**
* @deprecated Use `useCompletion` from `@ai-sdk/svelte` instead.
*/
export function useCompletion({
api = '/api/completion',
id,
initialCompletion = '',
initialInput = '',
credentials,
headers,
body,
streamMode,
streamProtocol,
onResponse,
onFinish,
onError,
fetch,
}: 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 completionId = id || `completion-${uniqueId++}`;
const key = `${api}|${completionId}`;
const {
data,
mutate: originalMutate,
isLoading: isSWRLoading,
} = useSWR<string>(key, {
fetcher: () => store[key] || initialCompletion,
fallbackData: initialCompletion,
});
const streamData = writable<JSONValue[] | undefined>(undefined);
const loading = writable<boolean>(false);
// Force the `data` to be `initialCompletion` if it's `undefined`.
data.set(initialCompletion);
const mutate = (data: string) => {
store[key] = data;
return originalMutate(data);
};
// Because of the `fallbackData` option, the `data` will never be `undefined`.
const completion = data as Writable<string>;
const error = writable<undefined | Error>(undefined);
let abortController: AbortController | null = null;
const complete: UseCompletionHelpers['complete'] = async (
prompt: string,
options?: RequestOptions,
) => {
const existingData = get(streamData);
return callCompletionApi({
api,
prompt,
credentials,
headers: {
...headers,
...options?.headers,
},
body: {
...body,
...options?.body,
},
streamProtocol,
setCompletion: mutate,
setLoading: loadingState => loading.set(loadingState),
setError: err => error.set(err),
setAbortController: controller => {
abortController = controller;
},
onResponse,
onFinish,
onError,
onData(data) {
streamData.set([...(existingData || []), ...(data || [])]);
},
fetch,
});
};
const stop = () => {
if (abortController) {
abortController.abort();
abortController = null;
}
};
const setCompletion = (completion: string) => {
mutate(completion);
};
const input = writable(initialInput);
const handleSubmit = (event?: { preventDefault?: () => void }) => {
event?.preventDefault?.();
const inputValue = get(input);
return inputValue ? complete(inputValue) : undefined;
};
const isLoading = derived(
[isSWRLoading, loading],
([$isSWRLoading, $loading]) => {
return $isSWRLoading || $loading;
},
);
return {
completion,
complete,
error,
stop,
setCompletion,
input,
handleSubmit,
isLoading,
data: streamData,
};
}