@ai-sdk/vue 4.0.0-beta.18 → 4.0.0-beta.181

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.
@@ -0,0 +1,182 @@
1
+ import {
2
+ AbstractChat,
3
+ type ChatInit as BaseChatInit,
4
+ type ChatInit,
5
+ type ChatState,
6
+ type ChatStatus,
7
+ type UIMessage,
8
+ } from 'ai';
9
+ import {
10
+ computed,
11
+ shallowRef,
12
+ toValue,
13
+ triggerRef,
14
+ watch,
15
+ type ComputedRef,
16
+ type MaybeRefOrGetter,
17
+ type ShallowRef,
18
+ } from 'vue';
19
+
20
+ /**
21
+ * @internal
22
+ */
23
+ export class VueChat<
24
+ UI_MESSAGE extends UIMessage,
25
+ > extends AbstractChat<UI_MESSAGE> {
26
+ constructor({
27
+ state,
28
+ ...init
29
+ }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
30
+ state: ChatState<UI_MESSAGE>;
31
+ }) {
32
+ super({
33
+ ...init,
34
+ state,
35
+ });
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Return type of the {@link useChat} composable, which includes the chat
41
+ * instance methods and reactive properties for messages, status, and error.
42
+ */
43
+ export interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<
44
+ AbstractChat<UI_MESSAGE>,
45
+ | 'sendMessage'
46
+ | 'regenerate'
47
+ | 'stop'
48
+ | 'resumeStream'
49
+ | 'addToolOutput'
50
+ | 'addToolApprovalResponse'
51
+ | 'clearError'
52
+ > {
53
+ /**
54
+ * The id of the chat.
55
+ */
56
+ id: ComputedRef<string>;
57
+
58
+ /**
59
+ * The current error state of the chat, if any.
60
+ */
61
+ error: ShallowRef<Error | undefined>;
62
+
63
+ /**
64
+ * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.
65
+ */
66
+ status: ShallowRef<ChatStatus>;
67
+
68
+ /**
69
+ * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.
70
+ */
71
+ messages: ShallowRef<UI_MESSAGE[]>;
72
+ }
73
+
74
+ /**
75
+ * Composable to access messages, status, and other chat properties and
76
+ * methods. Accepts an optional reactive initial configuration object
77
+ *
78
+ * @example
79
+ *
80
+ * ```ts
81
+ * // passing a getter if any reactive properties are used within
82
+ * // the init object
83
+ * const { messages, sendMessage } = useChat(() => ({
84
+ * // ...
85
+ * })
86
+ * ```
87
+ *
88
+ * @see BaseChatInit
89
+ */
90
+ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>(
91
+ init?: MaybeRefOrGetter<BaseChatInit<UI_MESSAGE>>,
92
+ ): UseChatHelpers<UI_MESSAGE> {
93
+ const messages = shallowRef<UI_MESSAGE[]>([]);
94
+ const status = shallowRef<ChatStatus>('ready');
95
+ const error = shallowRef<Error | undefined>();
96
+
97
+ // this wrapper doesn't need to be reactive and can be reused across chat
98
+ // instance changes, because the inner refs are reactive and the wrapper
99
+ // methods trigger updates when needed
100
+ const chatStateWrapper = {
101
+ get messages(): UI_MESSAGE[] {
102
+ return messages.value;
103
+ },
104
+
105
+ set messages(messageList: UI_MESSAGE[]) {
106
+ messages.value = messageList;
107
+ },
108
+
109
+ get status(): ChatStatus {
110
+ return status.value;
111
+ },
112
+
113
+ set status(statusValue: ChatStatus) {
114
+ status.value = statusValue;
115
+ },
116
+
117
+ get error(): Error | undefined {
118
+ return error.value;
119
+ },
120
+
121
+ set error(errorValue: Error | undefined) {
122
+ error.value = errorValue;
123
+ },
124
+
125
+ pushMessage(message: UI_MESSAGE) {
126
+ messages.value.push(message);
127
+ // needed because messagesRef is a shallowRef
128
+ triggerRef(messages);
129
+ },
130
+
131
+ popMessage() {
132
+ messages.value.pop();
133
+ triggerRef(messages);
134
+ },
135
+
136
+ replaceMessage(index: number, message: UI_MESSAGE) {
137
+ // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts
138
+ messages.value[index] = { ...message };
139
+ triggerRef(messages);
140
+ },
141
+
142
+ snapshot: <T>(value: T): T => value,
143
+ } satisfies ChatState<UI_MESSAGE>;
144
+
145
+ // the instance is created right away thanks to immediate: true. We do it this
146
+ // way instead of a computed to ensure all changes to reactive state happen
147
+ // in the same tick
148
+ const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<
149
+ VueChat<UI_MESSAGE>
150
+ >;
151
+
152
+ watch(
153
+ () => toValue(init),
154
+ opts => {
155
+ // reset the initial state
156
+ messages.value = opts?.messages ?? [];
157
+ status.value = 'ready';
158
+ error.value = undefined;
159
+
160
+ chatInstance.value = new VueChat<UI_MESSAGE>({
161
+ ...opts,
162
+ state: chatStateWrapper,
163
+ });
164
+ },
165
+ { immediate: true },
166
+ );
167
+
168
+ return {
169
+ id: computed(() => chatInstance.value.id),
170
+ status,
171
+ messages,
172
+ error,
173
+ addToolApprovalResponse: opts =>
174
+ chatInstance.value.addToolApprovalResponse(opts),
175
+ addToolOutput: opts => chatInstance.value.addToolOutput(opts),
176
+ clearError: () => chatInstance.value.clearError(),
177
+ regenerate: opts => chatInstance.value.regenerate(opts),
178
+ sendMessage: (...args) => chatInstance.value.sendMessage(...args),
179
+ stop: () => chatInstance.value.stop(),
180
+ resumeStream: opts => chatInstance.value.resumeStream(opts),
181
+ };
182
+ }
@@ -1,9 +1,11 @@
1
- import type { CompletionRequestOptions, UseCompletionOptions } from 'ai';
2
- import { callCompletionApi } from 'ai';
1
+ import {
2
+ callCompletionApi,
3
+ type CompletionRequestOptions,
4
+ type UseCompletionOptions,
5
+ } from 'ai';
6
+ import type * as SwrvModule from 'swrv';
3
7
  import swrv from 'swrv';
4
- import type { Ref } from 'vue';
5
- import { ref, unref } from 'vue';
6
-
8
+ import { ref, unref, type Ref } from 'vue';
7
9
  export type { UseCompletionOptions };
8
10
 
9
11
  export type UseCompletionHelpers = {
@@ -45,7 +47,7 @@ export type UseCompletionHelpers = {
45
47
  let uniqueId = 0;
46
48
 
47
49
  // @ts-expect-error - some issues with the default export of useSWRV
48
- const useSWRV = (swrv.default as (typeof import('swrv'))['default']) || swrv;
50
+ const useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;
49
51
  const store: Record<string, any> = {};
50
52
 
51
53
  export function useCompletion({
package/src/use-object.ts CHANGED
@@ -11,9 +11,9 @@ import {
11
11
  type FlexibleSchema,
12
12
  type InferSchema,
13
13
  } from 'ai';
14
+ import type * as SwrvModule from 'swrv';
14
15
  import swrv from 'swrv';
15
16
  import { ref, type Ref } from 'vue';
16
-
17
17
  // use function to allow for mocking in tests
18
18
  const getOriginalFetch = () => fetch;
19
19
 
@@ -75,7 +75,7 @@ export type Experimental_UseObjectHelpers<RESULT, INPUT> = {
75
75
  let uniqueId = 0;
76
76
 
77
77
  // @ts-expect-error - some issues with the default export of useSWRV
78
- const useSWRV = (swrv.default as (typeof import('swrv'))['default']) || swrv;
78
+ const useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;
79
79
  const store: Record<string, any> = {};
80
80
 
81
81
  export const experimental_useObject = function useObject<
package/dist/index.d.mts DELETED
@@ -1,85 +0,0 @@
1
- import { CompletionRequestOptions, UseCompletionOptions, UIMessage, AbstractChat, ChatInit, FlexibleSchema, DeepPartial, InferSchema } from 'ai';
2
- export { UseCompletionOptions } from 'ai';
3
- import { Ref } from 'vue';
4
- import { FetchFunction } from '@ai-sdk/provider-utils';
5
-
6
- type UseCompletionHelpers = {
7
- /** The current completion result */
8
- completion: Ref<string>;
9
- /** The error object of the API request */
10
- error: Ref<undefined | Error>;
11
- /**
12
- * Send a new prompt to the API endpoint and update the completion state.
13
- */
14
- complete: (prompt: string, options?: CompletionRequestOptions) => Promise<string | null | undefined>;
15
- /**
16
- * Abort the current API request but keep the generated tokens.
17
- */
18
- stop: () => void;
19
- /**
20
- * Update the `completion` state locally.
21
- */
22
- setCompletion: (completion: string) => void;
23
- /** The current value of the input */
24
- input: Ref<string>;
25
- /**
26
- * Form submission handler to automatically reset input and append a user message
27
- * @example
28
- * ```jsx
29
- * <form @submit="handleSubmit">
30
- * <input @change="handleInputChange" v-model="input" />
31
- * </form>
32
- * ```
33
- */
34
- handleSubmit: (event?: {
35
- preventDefault?: () => void;
36
- }) => void;
37
- /** Whether the API request is in progress */
38
- isLoading: Ref<boolean | undefined>;
39
- };
40
- declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, onFinish, onError, fetch, }?: UseCompletionOptions): UseCompletionHelpers;
41
-
42
- declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {
43
- constructor({ messages, ...init }: ChatInit<UI_MESSAGE>);
44
- }
45
-
46
- type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {
47
- /** API endpoint that streams JSON chunks matching the schema */
48
- api: string;
49
- /** Schema that defines the final object shape */
50
- schema: SCHEMA;
51
- /** Shared state key. If omitted a random one is generated */
52
- id?: string;
53
- /** Initial partial value */
54
- initialValue?: DeepPartial<RESULT>;
55
- /** Optional custom fetch implementation */
56
- fetch?: FetchFunction;
57
- /** Called when stream ends */
58
- onFinish?: (event: {
59
- object: RESULT | undefined;
60
- error: Error | undefined;
61
- }) => Promise<void> | void;
62
- /** Called on error */
63
- onError?: (error: Error) => void;
64
- /** Extra request headers */
65
- headers?: Record<string, string> | Headers;
66
- /** Request credentials mode. Defaults to 'same-origin' if omitted */
67
- credentials?: RequestCredentials;
68
- };
69
- type Experimental_UseObjectHelpers<RESULT, INPUT> = {
70
- /** POST the input and start streaming */
71
- submit: (input: INPUT) => void;
72
- /** Current partial object, updated as chunks arrive */
73
- object: Ref<DeepPartial<RESULT> | undefined>;
74
- /** Latest error if any */
75
- error: Ref<Error | undefined>;
76
- /** Loading flag for the in-flight request */
77
- isLoading: Ref<boolean | undefined>;
78
- /** Abort the current request. Keeps current partial object. */
79
- stop: () => void;
80
- /** Abort and clear all state */
81
- clear: () => void;
82
- };
83
- declare const experimental_useObject: <SCHEMA extends FlexibleSchema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>) => Experimental_UseObjectHelpers<RESULT, INPUT>;
84
-
85
- export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseCompletionHelpers, experimental_useObject, useCompletion };
package/dist/index.mjs DELETED
@@ -1,290 +0,0 @@
1
- // src/use-completion.ts
2
- import { callCompletionApi } from "ai";
3
- import swrv from "swrv";
4
- import { ref, unref } from "vue";
5
- var uniqueId = 0;
6
- var useSWRV = swrv.default || swrv;
7
- var store = {};
8
- function useCompletion({
9
- api = "/api/completion",
10
- id,
11
- initialCompletion = "",
12
- initialInput = "",
13
- credentials,
14
- headers,
15
- body,
16
- streamProtocol,
17
- onFinish,
18
- onError,
19
- fetch: fetch2
20
- } = {}) {
21
- var _a;
22
- const completionId = id || `completion-${uniqueId++}`;
23
- const key = `${api}|${completionId}`;
24
- const { data, mutate: originalMutate } = useSWRV(
25
- key,
26
- () => store[key] || initialCompletion
27
- );
28
- const { data: isLoading, mutate: mutateLoading } = useSWRV(
29
- `${completionId}-loading`,
30
- null
31
- );
32
- (_a = isLoading.value) != null ? _a : isLoading.value = false;
33
- data.value || (data.value = initialCompletion);
34
- const mutate = (data2) => {
35
- store[key] = data2;
36
- return originalMutate();
37
- };
38
- const completion = data;
39
- const error = ref(void 0);
40
- let abortController = null;
41
- async function triggerRequest(prompt, options) {
42
- return callCompletionApi({
43
- api,
44
- prompt,
45
- credentials,
46
- headers: {
47
- ...headers,
48
- ...options == null ? void 0 : options.headers
49
- },
50
- body: {
51
- ...unref(body),
52
- ...options == null ? void 0 : options.body
53
- },
54
- streamProtocol,
55
- setCompletion: mutate,
56
- setLoading: (loading) => mutateLoading(() => loading),
57
- setError: (err) => {
58
- error.value = err;
59
- },
60
- setAbortController: (controller) => {
61
- abortController = controller;
62
- },
63
- onFinish,
64
- onError,
65
- fetch: fetch2
66
- });
67
- }
68
- const complete = async (prompt, options) => {
69
- return triggerRequest(prompt, options);
70
- };
71
- const stop = () => {
72
- if (abortController) {
73
- abortController.abort();
74
- abortController = null;
75
- }
76
- };
77
- const setCompletion = (completion2) => {
78
- mutate(completion2);
79
- };
80
- const input = ref(initialInput);
81
- const handleSubmit = (event) => {
82
- var _a2;
83
- (_a2 = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a2.call(event);
84
- const inputValue = input.value;
85
- return inputValue ? complete(inputValue) : void 0;
86
- };
87
- return {
88
- completion,
89
- complete,
90
- error,
91
- stop,
92
- setCompletion,
93
- input,
94
- handleSubmit,
95
- isLoading
96
- };
97
- }
98
-
99
- // src/chat.vue.ts
100
- import {
101
- AbstractChat
102
- } from "ai";
103
- import { ref as ref2 } from "vue";
104
- var VueChatState = class {
105
- constructor(messages) {
106
- this.statusRef = ref2("ready");
107
- this.errorRef = ref2(void 0);
108
- this.pushMessage = (message) => {
109
- this.messagesRef.value = [...this.messagesRef.value, message];
110
- };
111
- this.popMessage = () => {
112
- this.messagesRef.value = this.messagesRef.value.slice(0, -1);
113
- };
114
- this.replaceMessage = (index, message) => {
115
- this.messagesRef.value[index] = { ...message };
116
- };
117
- this.snapshot = (value) => value;
118
- this.messagesRef = ref2(messages != null ? messages : []);
119
- }
120
- get messages() {
121
- return this.messagesRef.value;
122
- }
123
- set messages(messages) {
124
- this.messagesRef.value = messages;
125
- }
126
- get status() {
127
- return this.statusRef.value;
128
- }
129
- set status(status) {
130
- this.statusRef.value = status;
131
- }
132
- get error() {
133
- return this.errorRef.value;
134
- }
135
- set error(error) {
136
- this.errorRef.value = error;
137
- }
138
- };
139
- var Chat = class extends AbstractChat {
140
- constructor({ messages, ...init }) {
141
- super({
142
- ...init,
143
- state: new VueChatState(messages)
144
- });
145
- }
146
- };
147
-
148
- // src/use-object.ts
149
- import {
150
- isAbortError,
151
- safeValidateTypes
152
- } from "@ai-sdk/provider-utils";
153
- import {
154
- asSchema,
155
- isDeepEqualData,
156
- parsePartialJson
157
- } from "ai";
158
- import swrv2 from "swrv";
159
- import { ref as ref3 } from "vue";
160
- var getOriginalFetch = () => fetch;
161
- var uniqueId2 = 0;
162
- var useSWRV2 = swrv2.default || swrv2;
163
- var store2 = {};
164
- var experimental_useObject = function useObject({
165
- api,
166
- id,
167
- schema,
168
- initialValue,
169
- fetch: fetch2,
170
- onError,
171
- onFinish,
172
- headers,
173
- credentials
174
- }) {
175
- var _a;
176
- const completionId = id || `completion-${uniqueId2++}`;
177
- const key = `${api}|${completionId}`;
178
- const { data, mutate: originalMutate } = useSWRV2(key, () => key in store2 ? store2[key] : initialValue);
179
- const { data: isLoading, mutate: mutateLoading } = useSWRV2(
180
- `${completionId}-loading`,
181
- null
182
- );
183
- (_a = isLoading.value) != null ? _a : isLoading.value = false;
184
- data.value || (data.value = initialValue);
185
- const mutateObject = (value) => {
186
- store2[key] = value;
187
- return originalMutate();
188
- };
189
- const error = ref3(void 0);
190
- let abortController = null;
191
- const stop = async () => {
192
- if (abortController) {
193
- try {
194
- abortController.abort();
195
- } catch (e) {
196
- } finally {
197
- abortController = null;
198
- }
199
- }
200
- await mutateLoading(() => false);
201
- };
202
- const clearObject = async () => {
203
- error.value = void 0;
204
- await mutateLoading(() => false);
205
- await mutateObject(void 0);
206
- data.value = void 0;
207
- };
208
- const clear = async () => {
209
- await stop();
210
- await clearObject();
211
- };
212
- const submit = async (input) => {
213
- try {
214
- await clearObject();
215
- await mutateLoading(() => true);
216
- abortController = new AbortController();
217
- const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
218
- const response = await actualFetch(api, {
219
- method: "POST",
220
- headers: {
221
- "Content-Type": "application/json",
222
- ...headers
223
- },
224
- credentials: credentials != null ? credentials : "same-origin",
225
- signal: abortController.signal,
226
- body: JSON.stringify(input)
227
- });
228
- if (!response.ok) {
229
- throw new Error(
230
- await response.text() || "Failed to fetch the response."
231
- );
232
- }
233
- if (!response.body) {
234
- throw new Error("The response body is empty.");
235
- }
236
- let accumulatedText = "";
237
- let latestObject = void 0;
238
- await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
239
- new WritableStream({
240
- async write(chunk) {
241
- accumulatedText += chunk;
242
- const { value } = await parsePartialJson(accumulatedText);
243
- const currentObject = value;
244
- if (!isDeepEqualData(latestObject, currentObject)) {
245
- latestObject = currentObject;
246
- await mutateObject(currentObject);
247
- }
248
- },
249
- async close() {
250
- await mutateLoading(() => false);
251
- abortController = null;
252
- if (onFinish) {
253
- const validationResult = await safeValidateTypes({
254
- value: latestObject,
255
- schema: asSchema(schema)
256
- });
257
- onFinish(
258
- validationResult.success ? {
259
- object: validationResult.value,
260
- error: void 0
261
- } : { object: void 0, error: validationResult.error }
262
- );
263
- }
264
- }
265
- })
266
- );
267
- } catch (err) {
268
- if (isAbortError(err))
269
- return;
270
- if (onError && err instanceof Error)
271
- onError(err);
272
- await mutateLoading(() => false);
273
- error.value = err instanceof Error ? err : new Error(String(err));
274
- }
275
- };
276
- return {
277
- submit,
278
- object: data,
279
- error,
280
- isLoading,
281
- stop,
282
- clear
283
- };
284
- };
285
- export {
286
- Chat,
287
- experimental_useObject,
288
- useCompletion
289
- };
290
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/use-completion.ts","../src/chat.vue.ts","../src/use-object.ts"],"sourcesContent":["import type { CompletionRequestOptions, UseCompletionOptions } from 'ai';\nimport { callCompletionApi } from 'ai';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { ref, unref } from 'vue';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: Ref<string>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: Ref<string>;\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form @submit=\"handleSubmit\">\n * <input @change=\"handleInputChange\" v-model=\"input\" />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n /** Whether the API request is in progress */\n isLoading: Ref<boolean | undefined>;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof import('swrv'))['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol,\n onFinish,\n onError,\n fetch,\n}: UseCompletionOptions = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<string>(\n key,\n () => store[key] || initialCompletion,\n );\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n\n // Force the `data` to be `initialCompletion` if it's `undefined`.\n data.value ||= initialCompletion;\n\n const mutate = (data: string) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const completion = data as Ref<string>;\n\n const error = ref<undefined | Error>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n prompt: string,\n options?: CompletionRequestOptions,\n ) {\n return callCompletionApi({\n api,\n prompt,\n credentials,\n headers: {\n ...headers,\n ...options?.headers,\n },\n body: {\n ...unref(body),\n ...options?.body,\n },\n streamProtocol,\n setCompletion: mutate,\n setLoading: loading => mutateLoading(() => loading),\n setError: err => {\n error.value = err;\n },\n setAbortController: controller => {\n abortController = controller;\n },\n onFinish,\n onError,\n fetch,\n });\n }\n\n const complete: UseCompletionHelpers['complete'] = async (\n prompt,\n options,\n ) => {\n return triggerRequest(prompt, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setCompletion = (completion: string) => {\n mutate(completion);\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n const inputValue = input.value;\n return inputValue ? complete(inputValue) : undefined;\n };\n\n return {\n completion,\n complete,\n error,\n stop,\n setCompletion,\n input,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n AbstractChat,\n ChatInit as BaseChatInit,\n ChatState,\n ChatStatus,\n UIMessage,\n} from 'ai';\nimport { Ref, ref } from 'vue';\n\nclass VueChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n private messagesRef: Ref<UI_MESSAGE[]>;\n private statusRef = ref<ChatStatus>('ready');\n private errorRef = ref<Error | undefined>(undefined);\n\n constructor(messages?: UI_MESSAGE[]) {\n this.messagesRef = ref(messages ?? []) as Ref<UI_MESSAGE[]>;\n }\n\n get messages(): UI_MESSAGE[] {\n return this.messagesRef.value;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n this.messagesRef.value = messages;\n }\n\n get status(): ChatStatus {\n return this.statusRef.value;\n }\n\n set status(status: ChatStatus) {\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorRef.value;\n }\n\n set error(error: Error | undefined) {\n this.errorRef.value = error;\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesRef.value = [...this.messagesRef.value, message];\n };\n\n popMessage = () => {\n this.messagesRef.value = this.messagesRef.value.slice(0, -1);\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts\n this.messagesRef.value[index] = { ...message };\n };\n\n snapshot = <T>(value: T): T => value;\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({ messages, ...init }: BaseChatInit<UI_MESSAGE>) {\n super({\n ...init,\n state: new VueChatState(messages),\n });\n }\n}\n","import {\n isAbortError,\n safeValidateTypes,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n isDeepEqualData,\n parsePartialJson,\n type DeepPartial,\n type FlexibleSchema,\n type InferSchema,\n} from 'ai';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /** API endpoint that streams JSON chunks matching the schema */\n api: string;\n\n /** Schema that defines the final object shape */\n schema: SCHEMA;\n\n /** Shared state key. If omitted a random one is generated */\n id?: string;\n\n /** Initial partial value */\n initialValue?: DeepPartial<RESULT>;\n\n /** Optional custom fetch implementation */\n fetch?: FetchFunction;\n\n /** Called when stream ends */\n onFinish?: (event: {\n object: RESULT | undefined;\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /** Called on error */\n onError?: (error: Error) => void;\n\n /** Extra request headers */\n headers?: Record<string, string> | Headers;\n\n /** Request credentials mode. Defaults to 'same-origin' if omitted */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /** POST the input and start streaming */\n submit: (input: INPUT) => void;\n\n /** Current partial object, updated as chunks arrive */\n object: Ref<DeepPartial<RESULT> | undefined>;\n\n /** Latest error if any */\n error: Ref<Error | undefined>;\n\n /** Loading flag for the in-flight request */\n isLoading: Ref<boolean | undefined>;\n\n /** Abort the current request. Keeps current partial object. */\n stop: () => void;\n\n /** Abort and clear all state */\n clear: () => void;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof import('swrv'))['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport const experimental_useObject = function useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema,\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id for the object if not provided.\n const completionId = id || `completion-${uniqueId++}`;\n\n const key = `${api}|${completionId}`;\n const { data, mutate: originalMutate } = useSWRV<\n DeepPartial<RESULT> | undefined\n >(key, () => (key in store ? store[key] : initialValue));\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${completionId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n data.value ||= initialValue as DeepPartial<RESULT> | undefined;\n\n const mutateObject = (value: DeepPartial<RESULT> | undefined) => {\n store[key] = value;\n return originalMutate();\n };\n\n const error = ref<Error | undefined>(undefined);\n let abortController: AbortController | null = null;\n\n const stop = async () => {\n if (abortController) {\n try {\n abortController.abort();\n } catch {\n // ignore\n } finally {\n abortController = null;\n }\n }\n await mutateLoading(() => false);\n };\n\n const clearObject = async () => {\n error.value = undefined;\n await mutateLoading(() => false);\n await mutateObject(undefined);\n // Need to explicitly set the value to undefined to trigger a re-render\n data.value = undefined;\n };\n\n const clear = async () => {\n await stop();\n await clearObject();\n };\n\n const submit = async (input: INPUT) => {\n try {\n await clearObject();\n await mutateLoading(() => true);\n\n abortController = new AbortController();\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(headers as any),\n },\n credentials: credentials ?? 'same-origin',\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) || 'Failed to fetch the response.',\n );\n }\n\n if (!response.body) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n await mutateObject(currentObject);\n }\n },\n async close() {\n await mutateLoading(() => false);\n abortController = null;\n\n if (onFinish) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? {\n object: validationResult.value as RESULT,\n error: undefined,\n }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (err: unknown) {\n if (isAbortError(err)) return;\n\n if (onError && err instanceof Error) onError(err);\n\n await mutateLoading(() => false);\n error.value = err instanceof Error ? err : new Error(String(err));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n};\n"],"mappings":";AACA,SAAS,yBAAyB;AAClC,OAAO,UAAU;AAEjB,SAAS,KAAK,aAAa;AAwC3B,IAAI,WAAW;AAGf,IAAM,UAAW,KAAK,WAAkD;AACxE,IAAM,QAA6B,CAAC;AAE7B,SAAS,cAAc;AAAA,EAC5B,MAAM;AAAA,EACN;AAAA,EACA,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AACF,IAA0B,CAAC,GAAyB;AA9DpD;AAgEE,QAAM,eAAe,MAAM,cAAc,UAAU;AAEnD,QAAM,MAAM,GAAG,GAAG,IAAI,YAAY;AAClC,QAAM,EAAE,MAAM,QAAQ,eAAe,IAAI;AAAA,IACvC;AAAA,IACA,MAAM,MAAM,GAAG,KAAK;AAAA,EACtB;AAEA,QAAM,EAAE,MAAM,WAAW,QAAQ,cAAc,IAAI;AAAA,IACjD,GAAG,YAAY;AAAA,IACf;AAAA,EACF;AAEA,kBAAU,UAAV,sBAAU,QAAU;AAGpB,OAAK,UAAL,KAAK,QAAU;AAEf,QAAM,SAAS,CAACC,UAAiB;AAC/B,UAAM,GAAG,IAAIA;AACb,WAAO,eAAe;AAAA,EACxB;AAGA,QAAM,aAAa;AAEnB,QAAM,QAAQ,IAAuB,MAA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