@ai-sdk/vue 4.0.107 → 4.0.108
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.
- package/CHANGELOG.md +11 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +196 -39
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +1 -1
- package/src/use-chat.ts +290 -56
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @ai-sdk/vue
|
|
2
2
|
|
|
3
|
+
## 4.0.108
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 73ec701: feat(vue): add configurable useChat message update throttling
|
|
8
|
+
- Updated dependencies [3f6852a]
|
|
9
|
+
- Updated dependencies [6317504]
|
|
10
|
+
- Updated dependencies [3cb2dcd]
|
|
11
|
+
- Updated dependencies [ccf98e7]
|
|
12
|
+
- ai@7.0.108
|
|
13
|
+
|
|
3
14
|
## 4.0.107
|
|
4
15
|
|
|
5
16
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -108,6 +108,14 @@ interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<AbstractChat
|
|
|
108
108
|
*/
|
|
109
109
|
messages: ShallowRef<UI_MESSAGE[]>;
|
|
110
110
|
}
|
|
111
|
+
type UseChatOptions<UI_MESSAGE extends UIMessage> = ChatInit<UI_MESSAGE> & {
|
|
112
|
+
/**
|
|
113
|
+
* Custom throttle wait time in milliseconds for reactive message updates.
|
|
114
|
+
* Positive values enable throttling. Defaults to undefined, which disables
|
|
115
|
+
* throttling.
|
|
116
|
+
*/
|
|
117
|
+
throttle?: number;
|
|
118
|
+
};
|
|
111
119
|
/**
|
|
112
120
|
* Composable to access messages, status, and other chat properties and
|
|
113
121
|
* methods. Accepts an optional reactive initial configuration object
|
|
@@ -124,7 +132,7 @@ interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<AbstractChat
|
|
|
124
132
|
*
|
|
125
133
|
* @see BaseChatInit
|
|
126
134
|
*/
|
|
127
|
-
declare function useChat<UI_MESSAGE extends UIMessage = UIMessage>(init?: MaybeRefOrGetter<
|
|
135
|
+
declare function useChat<UI_MESSAGE extends UIMessage = UIMessage>(init?: MaybeRefOrGetter<UseChatOptions<UI_MESSAGE>>): UseChatHelpers<UI_MESSAGE>;
|
|
128
136
|
|
|
129
137
|
/**
|
|
130
138
|
* @deprecated Use `useObject` instead.
|
|
@@ -139,4 +147,4 @@ type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema$1, RESULT> = Us
|
|
|
139
147
|
*/
|
|
140
148
|
type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<RESULT, INPUT>;
|
|
141
149
|
|
|
142
|
-
export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseCompletionHelpers, UseObjectHelpers, UseObjectOptions, experimental_useObject, useChat, useCompletion, useObject };
|
|
150
|
+
export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseChatOptions, UseCompletionHelpers, UseObjectHelpers, UseObjectOptions, experimental_useObject, useChat, useCompletion, useObject };
|
package/dist/index.js
CHANGED
|
@@ -294,11 +294,178 @@ import {
|
|
|
294
294
|
} from "ai";
|
|
295
295
|
import {
|
|
296
296
|
computed,
|
|
297
|
+
getCurrentScope,
|
|
298
|
+
onScopeDispose,
|
|
297
299
|
shallowRef,
|
|
298
300
|
toValue,
|
|
299
|
-
triggerRef,
|
|
300
301
|
watch
|
|
301
302
|
} from "vue";
|
|
303
|
+
function cloneMetadata(metadata) {
|
|
304
|
+
if (Array.isArray(metadata)) {
|
|
305
|
+
return [...metadata];
|
|
306
|
+
}
|
|
307
|
+
if (metadata != null && typeof metadata === "object" && (Object.getPrototypeOf(metadata) === Object.prototype || Object.getPrototypeOf(metadata) === null)) {
|
|
308
|
+
return { ...metadata };
|
|
309
|
+
}
|
|
310
|
+
return metadata;
|
|
311
|
+
}
|
|
312
|
+
function snapshotValue(value) {
|
|
313
|
+
if (value == null || typeof value !== "object" || !("parts" in value) || !Array.isArray(value.parts)) {
|
|
314
|
+
return value;
|
|
315
|
+
}
|
|
316
|
+
const message = value;
|
|
317
|
+
const snapshot = {
|
|
318
|
+
...message,
|
|
319
|
+
parts: message.parts.map((part) => ({ ...part }))
|
|
320
|
+
};
|
|
321
|
+
if ("metadata" in message) {
|
|
322
|
+
snapshot.metadata = cloneMetadata(message.metadata);
|
|
323
|
+
}
|
|
324
|
+
return snapshot;
|
|
325
|
+
}
|
|
326
|
+
var VueChatState2 = class {
|
|
327
|
+
constructor({
|
|
328
|
+
initialMessages,
|
|
329
|
+
messagesRef,
|
|
330
|
+
statusRef,
|
|
331
|
+
errorRef,
|
|
332
|
+
throttleWaitMs
|
|
333
|
+
}) {
|
|
334
|
+
this.publishedMessages = [];
|
|
335
|
+
this.publishedMessageSources = [];
|
|
336
|
+
this.dirtyMessageIndices = /* @__PURE__ */ new Set();
|
|
337
|
+
this.statusValue = "ready";
|
|
338
|
+
this.hasPendingPublication = false;
|
|
339
|
+
this.isActive = true;
|
|
340
|
+
this.isPublishing = false;
|
|
341
|
+
this.pushMessage = (message) => {
|
|
342
|
+
this.messagesValue.push(message);
|
|
343
|
+
this.dirtyMessageIndices.add(this.messagesValue.length - 1);
|
|
344
|
+
this.schedulePublication();
|
|
345
|
+
};
|
|
346
|
+
this.popMessage = () => {
|
|
347
|
+
this.messagesValue.pop();
|
|
348
|
+
this.schedulePublication();
|
|
349
|
+
};
|
|
350
|
+
this.replaceMessage = (index, message) => {
|
|
351
|
+
this.messagesValue[index] = message;
|
|
352
|
+
this.dirtyMessageIndices.add(index);
|
|
353
|
+
this.schedulePublication();
|
|
354
|
+
};
|
|
355
|
+
this.snapshot = snapshotValue;
|
|
356
|
+
this.handleIntervalEnd = () => {
|
|
357
|
+
this.timeout = void 0;
|
|
358
|
+
if (!this.isActive || !this.hasPendingPublication) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
this.hasPendingPublication = false;
|
|
362
|
+
this.publishMessages();
|
|
363
|
+
this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);
|
|
364
|
+
};
|
|
365
|
+
this.messagesValue = initialMessages;
|
|
366
|
+
this.messagesRef = messagesRef;
|
|
367
|
+
this.statusRef = statusRef;
|
|
368
|
+
this.errorRef = errorRef;
|
|
369
|
+
this.throttleWaitMs = throttleWaitMs != null && Number.isFinite(throttleWaitMs) && throttleWaitMs > 0 ? throttleWaitMs : void 0;
|
|
370
|
+
}
|
|
371
|
+
get messages() {
|
|
372
|
+
return this.messagesValue;
|
|
373
|
+
}
|
|
374
|
+
set messages(messages) {
|
|
375
|
+
const previousMessages = this.messagesValue;
|
|
376
|
+
this.messagesValue = messages;
|
|
377
|
+
for (let index = 0; index < messages.length; index++) {
|
|
378
|
+
if (messages[index] !== previousMessages[index]) {
|
|
379
|
+
this.dirtyMessageIndices.add(index);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
this.schedulePublication();
|
|
383
|
+
}
|
|
384
|
+
get status() {
|
|
385
|
+
return this.statusValue;
|
|
386
|
+
}
|
|
387
|
+
set status(status) {
|
|
388
|
+
this.statusValue = status;
|
|
389
|
+
if (!this.isActive) {
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (status === "ready" || status === "error") {
|
|
393
|
+
this.flushPublication();
|
|
394
|
+
}
|
|
395
|
+
this.statusRef.value = status;
|
|
396
|
+
}
|
|
397
|
+
get error() {
|
|
398
|
+
return this.errorValue;
|
|
399
|
+
}
|
|
400
|
+
set error(error) {
|
|
401
|
+
this.errorValue = error;
|
|
402
|
+
if (this.isActive) {
|
|
403
|
+
this.errorRef.value = error;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
publishInitialState() {
|
|
407
|
+
this.publishMessages();
|
|
408
|
+
this.statusRef.value = this.statusValue;
|
|
409
|
+
this.errorRef.value = this.errorValue;
|
|
410
|
+
}
|
|
411
|
+
setMessagesFromConsumer(messages) {
|
|
412
|
+
this.messagesValue = messages;
|
|
413
|
+
this.publishedMessages = messages;
|
|
414
|
+
this.publishedMessageSources = messages;
|
|
415
|
+
this.dirtyMessageIndices.clear();
|
|
416
|
+
}
|
|
417
|
+
dispose() {
|
|
418
|
+
this.isActive = false;
|
|
419
|
+
this.hasPendingPublication = false;
|
|
420
|
+
this.dirtyMessageIndices.clear();
|
|
421
|
+
this.publishedMessages = [];
|
|
422
|
+
this.publishedMessageSources = [];
|
|
423
|
+
if (this.timeout != null) {
|
|
424
|
+
clearTimeout(this.timeout);
|
|
425
|
+
this.timeout = void 0;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
schedulePublication() {
|
|
429
|
+
if (!this.isActive) {
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (this.throttleWaitMs == null) {
|
|
433
|
+
this.publishMessages();
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
if (this.timeout == null) {
|
|
437
|
+
this.publishMessages();
|
|
438
|
+
this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);
|
|
439
|
+
} else {
|
|
440
|
+
this.hasPendingPublication = true;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
flushPublication() {
|
|
444
|
+
if (this.timeout != null) {
|
|
445
|
+
clearTimeout(this.timeout);
|
|
446
|
+
this.timeout = void 0;
|
|
447
|
+
}
|
|
448
|
+
this.hasPendingPublication = false;
|
|
449
|
+
this.publishMessages();
|
|
450
|
+
}
|
|
451
|
+
publishMessages() {
|
|
452
|
+
if (!this.isActive) {
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const publishedMessages = this.messagesValue.map(
|
|
456
|
+
(message, index) => this.dirtyMessageIndices.has(index) || this.publishedMessageSources[index] !== message ? snapshotValue(message) : this.publishedMessages[index]
|
|
457
|
+
);
|
|
458
|
+
this.publishedMessages = publishedMessages;
|
|
459
|
+
this.publishedMessageSources = [...this.messagesValue];
|
|
460
|
+
this.dirtyMessageIndices.clear();
|
|
461
|
+
this.isPublishing = true;
|
|
462
|
+
try {
|
|
463
|
+
this.messagesRef.value = publishedMessages;
|
|
464
|
+
} finally {
|
|
465
|
+
this.isPublishing = false;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
};
|
|
302
469
|
var VueChat = class extends AbstractChat2 {
|
|
303
470
|
constructor({
|
|
304
471
|
state,
|
|
@@ -314,54 +481,44 @@ function useChat(init) {
|
|
|
314
481
|
const messages = shallowRef([]);
|
|
315
482
|
const status = shallowRef("ready");
|
|
316
483
|
const error = shallowRef();
|
|
317
|
-
const chatStateWrapper = {
|
|
318
|
-
get messages() {
|
|
319
|
-
return messages.value;
|
|
320
|
-
},
|
|
321
|
-
set messages(messageList) {
|
|
322
|
-
messages.value = messageList;
|
|
323
|
-
},
|
|
324
|
-
get status() {
|
|
325
|
-
return status.value;
|
|
326
|
-
},
|
|
327
|
-
set status(statusValue) {
|
|
328
|
-
status.value = statusValue;
|
|
329
|
-
},
|
|
330
|
-
get error() {
|
|
331
|
-
return error.value;
|
|
332
|
-
},
|
|
333
|
-
set error(errorValue) {
|
|
334
|
-
error.value = errorValue;
|
|
335
|
-
},
|
|
336
|
-
pushMessage(message) {
|
|
337
|
-
messages.value.push(message);
|
|
338
|
-
triggerRef(messages);
|
|
339
|
-
},
|
|
340
|
-
popMessage() {
|
|
341
|
-
messages.value.pop();
|
|
342
|
-
triggerRef(messages);
|
|
343
|
-
},
|
|
344
|
-
replaceMessage(index, message) {
|
|
345
|
-
messages.value[index] = { ...message };
|
|
346
|
-
triggerRef(messages);
|
|
347
|
-
},
|
|
348
|
-
snapshot: (value) => value
|
|
349
|
-
};
|
|
350
484
|
const chatInstance = shallowRef();
|
|
485
|
+
let chatState;
|
|
486
|
+
watch(
|
|
487
|
+
messages,
|
|
488
|
+
(messageList) => {
|
|
489
|
+
if (chatState != null && !chatState.isPublishing) {
|
|
490
|
+
chatState.setMessagesFromConsumer(messageList);
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
{ flush: "sync" }
|
|
494
|
+
);
|
|
351
495
|
watch(
|
|
352
496
|
() => toValue(init),
|
|
353
497
|
(opts) => {
|
|
354
498
|
var _a;
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
499
|
+
chatState == null ? void 0 : chatState.dispose();
|
|
500
|
+
const { throttle, ...chatInit } = opts != null ? opts : {};
|
|
501
|
+
const nextChatState = new VueChatState2({
|
|
502
|
+
initialMessages: (_a = chatInit.messages) != null ? _a : [],
|
|
503
|
+
messagesRef: messages,
|
|
504
|
+
statusRef: status,
|
|
505
|
+
errorRef: error,
|
|
506
|
+
throttleWaitMs: throttle
|
|
507
|
+
});
|
|
508
|
+
chatState = nextChatState;
|
|
509
|
+
nextChatState.publishInitialState();
|
|
358
510
|
chatInstance.value = new VueChat({
|
|
359
|
-
...
|
|
360
|
-
state:
|
|
511
|
+
...chatInit,
|
|
512
|
+
state: nextChatState
|
|
361
513
|
});
|
|
362
514
|
},
|
|
363
515
|
{ immediate: true }
|
|
364
516
|
);
|
|
517
|
+
if (getCurrentScope() != null) {
|
|
518
|
+
onScopeDispose(() => {
|
|
519
|
+
chatState == null ? void 0 : chatState.dispose();
|
|
520
|
+
});
|
|
521
|
+
}
|
|
365
522
|
return {
|
|
366
523
|
id: computed(() => chatInstance.value.id),
|
|
367
524
|
status,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"sourcesContent":["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 type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\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 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 SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport 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}: UseObjectOptions<SCHEMA, RESULT>): 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","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, unref, type Ref } from 'vue';\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\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<BODY>,\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 SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion<BODY extends object = object>({\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<NoInfer<BODY>> = {}): UseCompletionHelpers<BODY> {\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<BODY>,\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<BODY>['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 type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { ref, type Ref } from 'vue';\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\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\n/**\n * @deprecated Use the {@link useChat} composable instead. It exposes reactive\n * refs and automatically recreates the chat when its init object changes.\n */\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n super({\n ...init,\n state: new VueChatState(messages),\n });\n }\n}\n","import {\n AbstractChat,\n type ChatInit as BaseChatInit,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport {\n computed,\n shallowRef,\n toValue,\n triggerRef,\n watch,\n type ComputedRef,\n type MaybeRefOrGetter,\n type ShallowRef,\n} from 'vue';\n\n/**\n * @internal\n */\nexport class VueChat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({\n state,\n ...init\n }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n state: ChatState<UI_MESSAGE>;\n }) {\n super({\n ...init,\n state,\n });\n }\n}\n\n/**\n * Return type of the {@link useChat} composable, which includes the chat\n * instance methods and reactive properties for messages, status, and error.\n */\nexport interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'clearError'\n> {\n /**\n * The id of the chat.\n */\n id: ComputedRef<string>;\n\n /**\n * The current error state of the chat, if any.\n */\n error: ShallowRef<Error | undefined>;\n\n /**\n * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.\n */\n status: ShallowRef<ChatStatus>;\n\n /**\n * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.\n */\n messages: ShallowRef<UI_MESSAGE[]>;\n}\n\n/**\n * Composable to access messages, status, and other chat properties and\n * methods. Accepts an optional reactive initial configuration object\n *\n * @example\n *\n * ```ts\n * // passing a getter if any reactive properties are used within\n * // the init object\n * const { messages, sendMessage } = useChat(() => ({\n * // ...\n * })\n * ```\n *\n * @see BaseChatInit\n */\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>(\n init?: MaybeRefOrGetter<BaseChatInit<UI_MESSAGE>>,\n): UseChatHelpers<UI_MESSAGE> {\n const messages = shallowRef<UI_MESSAGE[]>([]);\n const status = shallowRef<ChatStatus>('ready');\n const error = shallowRef<Error | undefined>();\n\n // this wrapper doesn't need to be reactive and can be reused across chat\n // instance changes, because the inner refs are reactive and the wrapper\n // methods trigger updates when needed\n const chatStateWrapper = {\n get messages(): UI_MESSAGE[] {\n return messages.value;\n },\n\n set messages(messageList: UI_MESSAGE[]) {\n messages.value = messageList;\n },\n\n get status(): ChatStatus {\n return status.value;\n },\n\n set status(statusValue: ChatStatus) {\n status.value = statusValue;\n },\n\n get error(): Error | undefined {\n return error.value;\n },\n\n set error(errorValue: Error | undefined) {\n error.value = errorValue;\n },\n\n pushMessage(message: UI_MESSAGE) {\n messages.value.push(message);\n // needed because messagesRef is a shallowRef\n triggerRef(messages);\n },\n\n popMessage() {\n messages.value.pop();\n triggerRef(messages);\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 messages.value[index] = { ...message };\n triggerRef(messages);\n },\n\n snapshot: <T>(value: T): T => value,\n } satisfies ChatState<UI_MESSAGE>;\n\n // the instance is created right away thanks to immediate: true. We do it this\n // way instead of a computed to ensure all changes to reactive state happen\n // in the same tick\n const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<\n VueChat<UI_MESSAGE>\n >;\n\n watch(\n () => toValue(init),\n opts => {\n // reset the initial state\n messages.value = opts?.messages ?? [];\n status.value = 'ready';\n error.value = undefined;\n\n chatInstance.value = new VueChat<UI_MESSAGE>({\n ...opts,\n state: chatStateWrapper,\n });\n },\n { immediate: true },\n );\n\n return {\n id: computed(() => chatInstance.value.id),\n status,\n messages,\n error,\n addToolApprovalResponse: opts =>\n chatInstance.value.addToolApprovalResponse(opts),\n addToolOutput: opts => chatInstance.value.addToolOutput(opts),\n clearError: () => chatInstance.value.clearError(),\n regenerate: opts => chatInstance.value.regenerate(opts),\n sendMessage: (...args) => chatInstance.value.sendMessage(...args),\n stop: () => chatInstance.value.stop(),\n resumeStream: opts => chatInstance.value.resumeStream(opts),\n };\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-completion';\nexport { Chat } from './chat.vue';\nexport { useChat, type UseChatHelpers } from './use-chat';\nexport * from './use-object';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type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AoB;AAAA,QAC3C,GAAG;AAAA,QACH,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,IACA,EAAE,WAAW,KAAK;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,IAAI,SAAS,MAAM,aAAa,MAAM,EAAE;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA,yBAAyB,UACvB,aAAa,MAAM,wBAAwB,IAAI;AAAA,IACjD,eAAe,UAAQ,aAAa,MAAM,cAAc,IAAI;AAAA,IAC5D,YAAY,MAAM,aAAa,MAAM,WAAW;AAAA,IAChD,YAAY,UAAQ,aAAa,MAAM,WAAW,IAAI;AAAA,IACtD,aAAa,IAAI,SAAS,aAAa,MAAM,YAAY,GAAG,IAAI;AAAA,IAChE,MAAM,MAAM,aAAa,MAAM,KAAK;AAAA,IACpC,cAAc,UAAQ,aAAa,MAAM,aAAa,IAAI;AAAA,EAC5D;AACF;;;AClKO,IAAM,yBAAyB;","names":["fetch","swrv","ref","uniqueId","useSWRV","store","fetch","_a","data","completion","ref","AbstractChat"]}
|
|
1
|
+
{"version":3,"sources":["../src/use-object.ts","../src/use-completion.ts","../src/chat.vue.ts","../src/use-chat.ts","../src/index.ts"],"sourcesContent":["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 type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\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 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 SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport 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}: UseObjectOptions<SCHEMA, RESULT>): 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","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, unref, type Ref } from 'vue';\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\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<BODY>,\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 SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion<BODY extends object = object>({\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<NoInfer<BODY>> = {}): UseCompletionHelpers<BODY> {\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<BODY>,\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<BODY>['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 type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { ref, type Ref } from 'vue';\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\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\n/**\n * @deprecated Use the {@link useChat} composable instead. It exposes reactive\n * refs and automatically recreates the chat when its init object changes.\n */\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n super({\n ...init,\n state: new VueChatState(messages),\n });\n }\n}\n","import {\n AbstractChat,\n type ChatInit as BaseChatInit,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport {\n computed,\n getCurrentScope,\n onScopeDispose,\n shallowRef,\n toValue,\n watch,\n type ComputedRef,\n type MaybeRefOrGetter,\n type ShallowRef,\n} from 'vue';\n\nfunction cloneMetadata<METADATA>(metadata: METADATA): METADATA {\n if (Array.isArray(metadata)) {\n return [...metadata] as METADATA;\n }\n\n if (\n metadata != null &&\n typeof metadata === 'object' &&\n (Object.getPrototypeOf(metadata) === Object.prototype ||\n Object.getPrototypeOf(metadata) === null)\n ) {\n return { ...metadata } as METADATA;\n }\n\n return metadata;\n}\n\nfunction snapshotValue<T>(value: T): T {\n if (\n value == null ||\n typeof value !== 'object' ||\n !('parts' in value) ||\n !Array.isArray(value.parts)\n ) {\n return value;\n }\n\n const message = value as unknown as UIMessage;\n const snapshot = {\n ...message,\n parts: message.parts.map(part => ({ ...part })),\n };\n\n if ('metadata' in message) {\n snapshot.metadata = cloneMetadata(message.metadata);\n }\n\n return snapshot as T;\n}\n\nclass VueChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n private messagesValue: UI_MESSAGE[];\n private publishedMessages: UI_MESSAGE[] = [];\n private publishedMessageSources: UI_MESSAGE[] = [];\n private readonly dirtyMessageIndices = new Set<number>();\n private statusValue: ChatStatus = 'ready';\n private errorValue: Error | undefined;\n private readonly throttleWaitMs: number | undefined;\n private timeout: ReturnType<typeof setTimeout> | undefined;\n private hasPendingPublication = false;\n private isActive = true;\n\n isPublishing = false;\n\n constructor({\n initialMessages,\n messagesRef,\n statusRef,\n errorRef,\n throttleWaitMs,\n }: {\n initialMessages: UI_MESSAGE[];\n messagesRef: ShallowRef<UI_MESSAGE[]>;\n statusRef: ShallowRef<ChatStatus>;\n errorRef: ShallowRef<Error | undefined>;\n throttleWaitMs?: number;\n }) {\n this.messagesValue = initialMessages;\n this.messagesRef = messagesRef;\n this.statusRef = statusRef;\n this.errorRef = errorRef;\n this.throttleWaitMs =\n throttleWaitMs != null &&\n Number.isFinite(throttleWaitMs) &&\n throttleWaitMs > 0\n ? throttleWaitMs\n : undefined;\n }\n\n private readonly messagesRef: ShallowRef<UI_MESSAGE[]>;\n private readonly statusRef: ShallowRef<ChatStatus>;\n private readonly errorRef: ShallowRef<Error | undefined>;\n\n get messages(): UI_MESSAGE[] {\n return this.messagesValue;\n }\n\n set messages(messages: UI_MESSAGE[]) {\n const previousMessages = this.messagesValue;\n this.messagesValue = messages;\n\n for (let index = 0; index < messages.length; index++) {\n if (messages[index] !== previousMessages[index]) {\n this.dirtyMessageIndices.add(index);\n }\n }\n\n this.schedulePublication();\n }\n\n get status(): ChatStatus {\n return this.statusValue;\n }\n\n set status(status: ChatStatus) {\n this.statusValue = status;\n\n if (!this.isActive) {\n return;\n }\n\n if (status === 'ready' || status === 'error') {\n // Terminal states must never become observable before the final message.\n this.flushPublication();\n }\n\n this.statusRef.value = status;\n }\n\n get error(): Error | undefined {\n return this.errorValue;\n }\n\n set error(error: Error | undefined) {\n this.errorValue = error;\n\n if (this.isActive) {\n this.errorRef.value = error;\n }\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.messagesValue.push(message);\n this.dirtyMessageIndices.add(this.messagesValue.length - 1);\n this.schedulePublication();\n };\n\n popMessage = () => {\n this.messagesValue.pop();\n this.schedulePublication();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.messagesValue[index] = message;\n this.dirtyMessageIndices.add(index);\n this.schedulePublication();\n };\n\n snapshot = snapshotValue;\n\n publishInitialState() {\n this.publishMessages();\n this.statusRef.value = this.statusValue;\n this.errorRef.value = this.errorValue;\n }\n\n setMessagesFromConsumer(messages: UI_MESSAGE[]) {\n this.messagesValue = messages;\n this.publishedMessages = messages;\n this.publishedMessageSources = messages;\n this.dirtyMessageIndices.clear();\n }\n\n dispose() {\n this.isActive = false;\n this.hasPendingPublication = false;\n this.dirtyMessageIndices.clear();\n this.publishedMessages = [];\n this.publishedMessageSources = [];\n\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n }\n\n private schedulePublication() {\n if (!this.isActive) {\n return;\n }\n\n if (this.throttleWaitMs == null) {\n this.publishMessages();\n return;\n }\n\n if (this.timeout == null) {\n // Publish the leading update immediately, then coalesce updates until\n // the next interval boundary.\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n } else {\n this.hasPendingPublication = true;\n }\n }\n\n private readonly handleIntervalEnd = () => {\n this.timeout = undefined;\n\n if (!this.isActive || !this.hasPendingPublication) {\n return;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n };\n\n private flushPublication() {\n if (this.timeout != null) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n\n this.hasPendingPublication = false;\n this.publishMessages();\n }\n\n private publishMessages() {\n if (!this.isActive) {\n return;\n }\n\n const publishedMessages = this.messagesValue.map((message, index) =>\n this.dirtyMessageIndices.has(index) ||\n this.publishedMessageSources[index] !== message\n ? snapshotValue(message)\n : this.publishedMessages[index],\n );\n\n this.publishedMessages = publishedMessages;\n this.publishedMessageSources = [...this.messagesValue];\n this.dirtyMessageIndices.clear();\n\n this.isPublishing = true;\n try {\n this.messagesRef.value = publishedMessages;\n } finally {\n this.isPublishing = false;\n }\n }\n}\n\n/**\n * @internal\n */\nexport class VueChat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n constructor({\n state,\n ...init\n }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n state: ChatState<UI_MESSAGE>;\n }) {\n super({\n ...init,\n state,\n });\n }\n}\n\n/**\n * Return type of the {@link useChat} composable, which includes the chat\n * instance methods and reactive properties for messages, status, and error.\n */\nexport interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'clearError'\n> {\n /**\n * The id of the chat.\n */\n id: ComputedRef<string>;\n\n /**\n * The current error state of the chat, if any.\n */\n error: ShallowRef<Error | undefined>;\n\n /**\n * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.\n */\n status: ShallowRef<ChatStatus>;\n\n /**\n * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.\n */\n messages: ShallowRef<UI_MESSAGE[]>;\n}\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> =\n BaseChatInit<UI_MESSAGE> & {\n /**\n * Custom throttle wait time in milliseconds for reactive message updates.\n * Positive values enable throttling. Defaults to undefined, which disables\n * throttling.\n */\n throttle?: number;\n };\n\n/**\n * Composable to access messages, status, and other chat properties and\n * methods. Accepts an optional reactive initial configuration object\n *\n * @example\n *\n * ```ts\n * // passing a getter if any reactive properties are used within\n * // the init object\n * const { messages, sendMessage } = useChat(() => ({\n * // ...\n * })\n * ```\n *\n * @see BaseChatInit\n */\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>(\n init?: MaybeRefOrGetter<UseChatOptions<UI_MESSAGE>>,\n): UseChatHelpers<UI_MESSAGE> {\n const messages = shallowRef<UI_MESSAGE[]>([]);\n const status = shallowRef<ChatStatus>('ready');\n const error = shallowRef<Error | undefined>();\n\n // the instance is created right away thanks to immediate: true. We do it this\n // way instead of a computed to ensure all changes to reactive state happen\n // in the same tick\n const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<\n VueChat<UI_MESSAGE>\n >;\n let chatState: VueChatState<UI_MESSAGE> | undefined;\n\n watch(\n messages,\n messageList => {\n if (chatState != null && !chatState.isPublishing) {\n chatState.setMessagesFromConsumer(messageList);\n }\n },\n { flush: 'sync' },\n );\n\n watch(\n () => toValue(init),\n opts => {\n chatState?.dispose();\n\n const { throttle, ...chatInit } = opts ?? {};\n const nextChatState = new VueChatState<UI_MESSAGE>({\n initialMessages: chatInit.messages ?? [],\n messagesRef: messages,\n statusRef: status,\n errorRef: error,\n throttleWaitMs: throttle,\n });\n\n chatState = nextChatState;\n nextChatState.publishInitialState();\n\n chatInstance.value = new VueChat<UI_MESSAGE>({\n ...chatInit,\n state: nextChatState,\n });\n },\n { immediate: true },\n );\n\n if (getCurrentScope() != null) {\n onScopeDispose(() => {\n chatState?.dispose();\n });\n }\n\n return {\n id: computed(() => chatInstance.value.id),\n status,\n messages,\n error,\n addToolApprovalResponse: opts =>\n chatInstance.value.addToolApprovalResponse(opts),\n addToolOutput: opts => chatInstance.value.addToolOutput(opts),\n clearError: () => chatInstance.value.clearError(),\n regenerate: opts => chatInstance.value.regenerate(opts),\n sendMessage: (...args) => chatInstance.value.sendMessage(...args),\n stop: () => chatInstance.value.stop(),\n resumeStream: opts => chatInstance.value.resumeStream(opts),\n };\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-completion';\nexport { Chat } from './chat.vue';\nexport { useChat, type UseChatHelpers, type UseChatOptions } from './use-chat';\nexport * from './use-object';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n RESULT,\n INPUT\n>;\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,OAAO,UAAU;AACjB,SAAS,WAAqB;AAE9B,IAAM,mBAAmB,MAAM;AAsD/B,IAAI,WAAW;AAGf,IAAM,UAAW,KAAK,WAA8C;AACpE,IAAM,QAA6B,CAAC;AAE7B,SAAS,UAId;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAsE;AA3FtE;AA6FE,QAAM,eAAe,MAAM,cAAc,UAAU;AAEnD,QAAM,MAAM,GAAG,GAAG,IAAI,YAAY;AAClC,QAAM,EAAE,MAAM,QAAQ,eAAe,IAAI,QAEvC,KAAK,MAAO,OAAO,QAAQ,MAAM,GAAG,IAAI,YAAa;AAEvD,QAAM,EAAE,MAAM,WAAW,QAAQ,cAAc,IAAI;AAAA,IACjD,GAAG,YAAY;AAAA,IACf;AAAA,EACF;AAEA,kBAAU,UAAV,sBAAU,QAAU;AACpB,OAAK,UAAL,KAAK,QAAU;AAEf,QAAM,eAAe,CAAC,UAA2C;AAC/D,UAAM,GAAG,IAAI;AACb,WAAO,eAAe;AAAA,EACxB;AAEA,QAAM,QAAQ,IAAuB,MAAS;AAC9C,MAAI,kBA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;AAAA,QACvC,aAAa;AAAA,QACb,WAAW;AAAA,QACX,UAAU;AAAA,QACV,gBAAgB;AAAA,MAClB,CAAC;AAED,kBAAY;AACZ,oBAAc,oBAAoB;AAElC,mBAAa,QAAQ,IAAI,QAAoB;AAAA,QAC3C,GAAG;AAAA,QACH,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,IACA,EAAE,WAAW,KAAK;AAAA,EACpB;AAEA,MAAI,gBAAgB,KAAK,MAAM;AAC7B,mBAAe,MAAM;AACnB,6CAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,IAAI,SAAS,MAAM,aAAa,MAAM,EAAE;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA,yBAAyB,UACvB,aAAa,MAAM,wBAAwB,IAAI;AAAA,IACjD,eAAe,UAAQ,aAAa,MAAM,cAAc,IAAI;AAAA,IAC5D,YAAY,MAAM,aAAa,MAAM,WAAW;AAAA,IAChD,YAAY,UAAQ,aAAa,MAAM,WAAW,IAAI;AAAA,IACtD,aAAa,IAAI,SAAS,aAAa,MAAM,YAAY,GAAG,IAAI;AAAA,IAChE,MAAM,MAAM,aAAa,MAAM,KAAK;AAAA,IACpC,cAAc,UAAQ,aAAa,MAAM,aAAa,IAAI;AAAA,EAC5D;AACF;;;AC5YO,IAAM,yBAAyB;","names":["fetch","swrv","ref","uniqueId","useSWRV","store","fetch","_a","data","completion","ref","AbstractChat","VueChatState"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/vue",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.108",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@ai-sdk/provider-utils": "5.0.45",
|
|
30
|
-
"ai": "7.0.
|
|
30
|
+
"ai": "7.0.108",
|
|
31
31
|
"swrv": "^1.2.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
|
|
8
8
|
export * from './use-completion';
|
|
9
9
|
export { Chat } from './chat.vue';
|
|
10
|
-
export { useChat, type UseChatHelpers } from './use-chat';
|
|
10
|
+
export { useChat, type UseChatHelpers, type UseChatOptions } from './use-chat';
|
|
11
11
|
export * from './use-object';
|
|
12
12
|
|
|
13
13
|
// deprecated aliases
|
package/src/use-chat.ts
CHANGED
|
@@ -8,15 +8,261 @@ import {
|
|
|
8
8
|
} from 'ai';
|
|
9
9
|
import {
|
|
10
10
|
computed,
|
|
11
|
+
getCurrentScope,
|
|
12
|
+
onScopeDispose,
|
|
11
13
|
shallowRef,
|
|
12
14
|
toValue,
|
|
13
|
-
triggerRef,
|
|
14
15
|
watch,
|
|
15
16
|
type ComputedRef,
|
|
16
17
|
type MaybeRefOrGetter,
|
|
17
18
|
type ShallowRef,
|
|
18
19
|
} from 'vue';
|
|
19
20
|
|
|
21
|
+
function cloneMetadata<METADATA>(metadata: METADATA): METADATA {
|
|
22
|
+
if (Array.isArray(metadata)) {
|
|
23
|
+
return [...metadata] as METADATA;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (
|
|
27
|
+
metadata != null &&
|
|
28
|
+
typeof metadata === 'object' &&
|
|
29
|
+
(Object.getPrototypeOf(metadata) === Object.prototype ||
|
|
30
|
+
Object.getPrototypeOf(metadata) === null)
|
|
31
|
+
) {
|
|
32
|
+
return { ...metadata } as METADATA;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return metadata;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function snapshotValue<T>(value: T): T {
|
|
39
|
+
if (
|
|
40
|
+
value == null ||
|
|
41
|
+
typeof value !== 'object' ||
|
|
42
|
+
!('parts' in value) ||
|
|
43
|
+
!Array.isArray(value.parts)
|
|
44
|
+
) {
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const message = value as unknown as UIMessage;
|
|
49
|
+
const snapshot = {
|
|
50
|
+
...message,
|
|
51
|
+
parts: message.parts.map(part => ({ ...part })),
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
if ('metadata' in message) {
|
|
55
|
+
snapshot.metadata = cloneMetadata(message.metadata);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return snapshot as T;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class VueChatState<
|
|
62
|
+
UI_MESSAGE extends UIMessage,
|
|
63
|
+
> implements ChatState<UI_MESSAGE> {
|
|
64
|
+
private messagesValue: UI_MESSAGE[];
|
|
65
|
+
private publishedMessages: UI_MESSAGE[] = [];
|
|
66
|
+
private publishedMessageSources: UI_MESSAGE[] = [];
|
|
67
|
+
private readonly dirtyMessageIndices = new Set<number>();
|
|
68
|
+
private statusValue: ChatStatus = 'ready';
|
|
69
|
+
private errorValue: Error | undefined;
|
|
70
|
+
private readonly throttleWaitMs: number | undefined;
|
|
71
|
+
private timeout: ReturnType<typeof setTimeout> | undefined;
|
|
72
|
+
private hasPendingPublication = false;
|
|
73
|
+
private isActive = true;
|
|
74
|
+
|
|
75
|
+
isPublishing = false;
|
|
76
|
+
|
|
77
|
+
constructor({
|
|
78
|
+
initialMessages,
|
|
79
|
+
messagesRef,
|
|
80
|
+
statusRef,
|
|
81
|
+
errorRef,
|
|
82
|
+
throttleWaitMs,
|
|
83
|
+
}: {
|
|
84
|
+
initialMessages: UI_MESSAGE[];
|
|
85
|
+
messagesRef: ShallowRef<UI_MESSAGE[]>;
|
|
86
|
+
statusRef: ShallowRef<ChatStatus>;
|
|
87
|
+
errorRef: ShallowRef<Error | undefined>;
|
|
88
|
+
throttleWaitMs?: number;
|
|
89
|
+
}) {
|
|
90
|
+
this.messagesValue = initialMessages;
|
|
91
|
+
this.messagesRef = messagesRef;
|
|
92
|
+
this.statusRef = statusRef;
|
|
93
|
+
this.errorRef = errorRef;
|
|
94
|
+
this.throttleWaitMs =
|
|
95
|
+
throttleWaitMs != null &&
|
|
96
|
+
Number.isFinite(throttleWaitMs) &&
|
|
97
|
+
throttleWaitMs > 0
|
|
98
|
+
? throttleWaitMs
|
|
99
|
+
: undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private readonly messagesRef: ShallowRef<UI_MESSAGE[]>;
|
|
103
|
+
private readonly statusRef: ShallowRef<ChatStatus>;
|
|
104
|
+
private readonly errorRef: ShallowRef<Error | undefined>;
|
|
105
|
+
|
|
106
|
+
get messages(): UI_MESSAGE[] {
|
|
107
|
+
return this.messagesValue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
set messages(messages: UI_MESSAGE[]) {
|
|
111
|
+
const previousMessages = this.messagesValue;
|
|
112
|
+
this.messagesValue = messages;
|
|
113
|
+
|
|
114
|
+
for (let index = 0; index < messages.length; index++) {
|
|
115
|
+
if (messages[index] !== previousMessages[index]) {
|
|
116
|
+
this.dirtyMessageIndices.add(index);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
this.schedulePublication();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
get status(): ChatStatus {
|
|
124
|
+
return this.statusValue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
set status(status: ChatStatus) {
|
|
128
|
+
this.statusValue = status;
|
|
129
|
+
|
|
130
|
+
if (!this.isActive) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (status === 'ready' || status === 'error') {
|
|
135
|
+
// Terminal states must never become observable before the final message.
|
|
136
|
+
this.flushPublication();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
this.statusRef.value = status;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
get error(): Error | undefined {
|
|
143
|
+
return this.errorValue;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
set error(error: Error | undefined) {
|
|
147
|
+
this.errorValue = error;
|
|
148
|
+
|
|
149
|
+
if (this.isActive) {
|
|
150
|
+
this.errorRef.value = error;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
pushMessage = (message: UI_MESSAGE) => {
|
|
155
|
+
this.messagesValue.push(message);
|
|
156
|
+
this.dirtyMessageIndices.add(this.messagesValue.length - 1);
|
|
157
|
+
this.schedulePublication();
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
popMessage = () => {
|
|
161
|
+
this.messagesValue.pop();
|
|
162
|
+
this.schedulePublication();
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
replaceMessage = (index: number, message: UI_MESSAGE) => {
|
|
166
|
+
this.messagesValue[index] = message;
|
|
167
|
+
this.dirtyMessageIndices.add(index);
|
|
168
|
+
this.schedulePublication();
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
snapshot = snapshotValue;
|
|
172
|
+
|
|
173
|
+
publishInitialState() {
|
|
174
|
+
this.publishMessages();
|
|
175
|
+
this.statusRef.value = this.statusValue;
|
|
176
|
+
this.errorRef.value = this.errorValue;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
setMessagesFromConsumer(messages: UI_MESSAGE[]) {
|
|
180
|
+
this.messagesValue = messages;
|
|
181
|
+
this.publishedMessages = messages;
|
|
182
|
+
this.publishedMessageSources = messages;
|
|
183
|
+
this.dirtyMessageIndices.clear();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
dispose() {
|
|
187
|
+
this.isActive = false;
|
|
188
|
+
this.hasPendingPublication = false;
|
|
189
|
+
this.dirtyMessageIndices.clear();
|
|
190
|
+
this.publishedMessages = [];
|
|
191
|
+
this.publishedMessageSources = [];
|
|
192
|
+
|
|
193
|
+
if (this.timeout != null) {
|
|
194
|
+
clearTimeout(this.timeout);
|
|
195
|
+
this.timeout = undefined;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private schedulePublication() {
|
|
200
|
+
if (!this.isActive) {
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (this.throttleWaitMs == null) {
|
|
205
|
+
this.publishMessages();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (this.timeout == null) {
|
|
210
|
+
// Publish the leading update immediately, then coalesce updates until
|
|
211
|
+
// the next interval boundary.
|
|
212
|
+
this.publishMessages();
|
|
213
|
+
this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);
|
|
214
|
+
} else {
|
|
215
|
+
this.hasPendingPublication = true;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private readonly handleIntervalEnd = () => {
|
|
220
|
+
this.timeout = undefined;
|
|
221
|
+
|
|
222
|
+
if (!this.isActive || !this.hasPendingPublication) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
this.hasPendingPublication = false;
|
|
227
|
+
this.publishMessages();
|
|
228
|
+
this.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
private flushPublication() {
|
|
232
|
+
if (this.timeout != null) {
|
|
233
|
+
clearTimeout(this.timeout);
|
|
234
|
+
this.timeout = undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
this.hasPendingPublication = false;
|
|
238
|
+
this.publishMessages();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private publishMessages() {
|
|
242
|
+
if (!this.isActive) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const publishedMessages = this.messagesValue.map((message, index) =>
|
|
247
|
+
this.dirtyMessageIndices.has(index) ||
|
|
248
|
+
this.publishedMessageSources[index] !== message
|
|
249
|
+
? snapshotValue(message)
|
|
250
|
+
: this.publishedMessages[index],
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
this.publishedMessages = publishedMessages;
|
|
254
|
+
this.publishedMessageSources = [...this.messagesValue];
|
|
255
|
+
this.dirtyMessageIndices.clear();
|
|
256
|
+
|
|
257
|
+
this.isPublishing = true;
|
|
258
|
+
try {
|
|
259
|
+
this.messagesRef.value = publishedMessages;
|
|
260
|
+
} finally {
|
|
261
|
+
this.isPublishing = false;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
20
266
|
/**
|
|
21
267
|
* @internal
|
|
22
268
|
*/
|
|
@@ -71,6 +317,16 @@ export interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<
|
|
|
71
317
|
messages: ShallowRef<UI_MESSAGE[]>;
|
|
72
318
|
}
|
|
73
319
|
|
|
320
|
+
export type UseChatOptions<UI_MESSAGE extends UIMessage> =
|
|
321
|
+
BaseChatInit<UI_MESSAGE> & {
|
|
322
|
+
/**
|
|
323
|
+
* Custom throttle wait time in milliseconds for reactive message updates.
|
|
324
|
+
* Positive values enable throttling. Defaults to undefined, which disables
|
|
325
|
+
* throttling.
|
|
326
|
+
*/
|
|
327
|
+
throttle?: number;
|
|
328
|
+
};
|
|
329
|
+
|
|
74
330
|
/**
|
|
75
331
|
* Composable to access messages, status, and other chat properties and
|
|
76
332
|
* methods. Accepts an optional reactive initial configuration object
|
|
@@ -88,83 +344,61 @@ export interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<
|
|
|
88
344
|
* @see BaseChatInit
|
|
89
345
|
*/
|
|
90
346
|
export function useChat<UI_MESSAGE extends UIMessage = UIMessage>(
|
|
91
|
-
init?: MaybeRefOrGetter<
|
|
347
|
+
init?: MaybeRefOrGetter<UseChatOptions<UI_MESSAGE>>,
|
|
92
348
|
): UseChatHelpers<UI_MESSAGE> {
|
|
93
349
|
const messages = shallowRef<UI_MESSAGE[]>([]);
|
|
94
350
|
const status = shallowRef<ChatStatus>('ready');
|
|
95
351
|
const error = shallowRef<Error | undefined>();
|
|
96
352
|
|
|
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
353
|
// the instance is created right away thanks to immediate: true. We do it this
|
|
146
354
|
// way instead of a computed to ensure all changes to reactive state happen
|
|
147
355
|
// in the same tick
|
|
148
356
|
const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<
|
|
149
357
|
VueChat<UI_MESSAGE>
|
|
150
358
|
>;
|
|
359
|
+
let chatState: VueChatState<UI_MESSAGE> | undefined;
|
|
360
|
+
|
|
361
|
+
watch(
|
|
362
|
+
messages,
|
|
363
|
+
messageList => {
|
|
364
|
+
if (chatState != null && !chatState.isPublishing) {
|
|
365
|
+
chatState.setMessagesFromConsumer(messageList);
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
{ flush: 'sync' },
|
|
369
|
+
);
|
|
151
370
|
|
|
152
371
|
watch(
|
|
153
372
|
() => toValue(init),
|
|
154
373
|
opts => {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
374
|
+
chatState?.dispose();
|
|
375
|
+
|
|
376
|
+
const { throttle, ...chatInit } = opts ?? {};
|
|
377
|
+
const nextChatState = new VueChatState<UI_MESSAGE>({
|
|
378
|
+
initialMessages: chatInit.messages ?? [],
|
|
379
|
+
messagesRef: messages,
|
|
380
|
+
statusRef: status,
|
|
381
|
+
errorRef: error,
|
|
382
|
+
throttleWaitMs: throttle,
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
chatState = nextChatState;
|
|
386
|
+
nextChatState.publishInitialState();
|
|
159
387
|
|
|
160
388
|
chatInstance.value = new VueChat<UI_MESSAGE>({
|
|
161
|
-
...
|
|
162
|
-
state:
|
|
389
|
+
...chatInit,
|
|
390
|
+
state: nextChatState,
|
|
163
391
|
});
|
|
164
392
|
},
|
|
165
393
|
{ immediate: true },
|
|
166
394
|
);
|
|
167
395
|
|
|
396
|
+
if (getCurrentScope() != null) {
|
|
397
|
+
onScopeDispose(() => {
|
|
398
|
+
chatState?.dispose();
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
168
402
|
return {
|
|
169
403
|
id: computed(() => chatInstance.value.id),
|
|
170
404
|
status,
|