@ai-sdk/vue 1.2.3 → 2.0.0-canary.0

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 CHANGED
@@ -1,5 +1,28 @@
1
1
  # @ai-sdk/vue
2
2
 
3
+ ## 2.0.0-canary.0
4
+
5
+ ### Major Changes
6
+
7
+ - d5f588f: AI SDK 5
8
+ - 9477ebb: chore (ui): remove useAssistant hook (**breaking change**)
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [d5f588f]
13
+ - Updated dependencies [9477ebb]
14
+ - @ai-sdk/provider-utils@3.0.0-canary.0
15
+ - @ai-sdk/ui-utils@2.0.0-canary.0
16
+
17
+ ## 1.2.4
18
+
19
+ ### Patch Changes
20
+
21
+ - a043b14: fix (ui): prevent early addToolResult submission
22
+ - Updated dependencies [28be004]
23
+ - @ai-sdk/provider-utils@2.2.3
24
+ - @ai-sdk/ui-utils@1.2.4
25
+
3
26
  ## 1.2.3
4
27
 
5
28
  ### Patch Changes
package/README.md CHANGED
@@ -4,4 +4,3 @@
4
4
 
5
5
  - [`useChat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat) composable
6
6
  - [`useCompletion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion) composable
7
- - [`useAssistant`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-assistant) composable
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
1
+ import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
2
2
  export { CreateMessage, Message, UIMessage, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
- import { Ref, ComputedRef } from 'vue';
3
+ import { Ref } from 'vue';
4
4
 
5
5
  type UseChatHelpers = {
6
6
  /** Current messages in the chat */
@@ -123,69 +123,4 @@ type UseCompletionHelpers = {
123
123
  };
124
124
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, onResponse, onFinish, onError, fetch, }?: UseCompletionOptions): UseCompletionHelpers;
125
125
 
126
- /**
127
- * A vue.js composable function to interact with the assistant API.
128
- */
129
-
130
- type UseAssistantHelpers = {
131
- /**
132
- * The current array of chat messages.
133
- */
134
- messages: Ref<Message[]>;
135
- /**
136
- * Update the message store with a new array of messages.
137
- */
138
- setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;
139
- /**
140
- * The current thread ID.
141
- */
142
- threadId: Ref<string | undefined>;
143
- /**
144
- * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.
145
- */
146
- setThreadId: (threadId: string | undefined) => void;
147
- /**
148
- * The current value of the input field.
149
- */
150
- input: Ref<string>;
151
- /**
152
- * Append a user message to the chat list. This triggers the API call to fetch
153
- * the assistant's response.
154
- * @param message The message to append
155
- * @param requestOptions Additional options to pass to the API call
156
- */
157
- append: (message: Message | CreateMessage, requestOptions?: {
158
- data?: Record<string, string>;
159
- }) => Promise<void>;
160
- /**
161
- * Abort the current request immediately, keep the generated tokens if any.
162
- */
163
- stop: ComputedRef<() => void>;
164
- /**
165
- * Handler for the `onChange` event of the input field to control the input's value.
166
- */
167
- handleInputChange: (e: Event & {
168
- target: HTMLInputElement;
169
- }) => void;
170
- /**
171
- * Handler for the `onSubmit` event of the form to append a user message and reset the input.
172
- */
173
- handleSubmit: (e: Event & {
174
- target: HTMLFormElement;
175
- }) => void;
176
- /**
177
- * Whether the assistant is currently sending a message.
178
- */
179
- isSending: ComputedRef<boolean>;
180
- /**
181
- * The current status of the assistant.
182
- */
183
- status: Ref<AssistantStatus>;
184
- /**
185
- * The current error, if any.
186
- */
187
- error: Ref<Error | undefined>;
188
- };
189
- declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, }: UseAssistantOptions): UseAssistantHelpers;
190
-
191
- export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, useAssistant, useChat, useCompletion };
126
+ export { UseChatHelpers, UseCompletionHelpers, useChat, useCompletion };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
1
+ import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
2
2
  export { CreateMessage, Message, UIMessage, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
- import { Ref, ComputedRef } from 'vue';
3
+ import { Ref } from 'vue';
4
4
 
5
5
  type UseChatHelpers = {
6
6
  /** Current messages in the chat */
@@ -123,69 +123,4 @@ type UseCompletionHelpers = {
123
123
  };
124
124
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, onResponse, onFinish, onError, fetch, }?: UseCompletionOptions): UseCompletionHelpers;
125
125
 
126
- /**
127
- * A vue.js composable function to interact with the assistant API.
128
- */
129
-
130
- type UseAssistantHelpers = {
131
- /**
132
- * The current array of chat messages.
133
- */
134
- messages: Ref<Message[]>;
135
- /**
136
- * Update the message store with a new array of messages.
137
- */
138
- setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;
139
- /**
140
- * The current thread ID.
141
- */
142
- threadId: Ref<string | undefined>;
143
- /**
144
- * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.
145
- */
146
- setThreadId: (threadId: string | undefined) => void;
147
- /**
148
- * The current value of the input field.
149
- */
150
- input: Ref<string>;
151
- /**
152
- * Append a user message to the chat list. This triggers the API call to fetch
153
- * the assistant's response.
154
- * @param message The message to append
155
- * @param requestOptions Additional options to pass to the API call
156
- */
157
- append: (message: Message | CreateMessage, requestOptions?: {
158
- data?: Record<string, string>;
159
- }) => Promise<void>;
160
- /**
161
- * Abort the current request immediately, keep the generated tokens if any.
162
- */
163
- stop: ComputedRef<() => void>;
164
- /**
165
- * Handler for the `onChange` event of the input field to control the input's value.
166
- */
167
- handleInputChange: (e: Event & {
168
- target: HTMLInputElement;
169
- }) => void;
170
- /**
171
- * Handler for the `onSubmit` event of the form to append a user message and reset the input.
172
- */
173
- handleSubmit: (e: Event & {
174
- target: HTMLFormElement;
175
- }) => void;
176
- /**
177
- * Whether the assistant is currently sending a message.
178
- */
179
- isSending: ComputedRef<boolean>;
180
- /**
181
- * The current status of the assistant.
182
- */
183
- status: Ref<AssistantStatus>;
184
- /**
185
- * The current error, if any.
186
- */
187
- error: Ref<Error | undefined>;
188
- };
189
- declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, }: UseAssistantOptions): UseAssistantHelpers;
190
-
191
- export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, useAssistant, useChat, useCompletion };
126
+ export { UseChatHelpers, UseCompletionHelpers, useChat, useCompletion };
package/dist/index.js CHANGED
@@ -30,7 +30,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- useAssistant: () => useAssistant,
34
33
  useChat: () => useChat,
35
34
  useCompletion: () => useCompletion
36
35
  });
@@ -55,9 +54,9 @@ function useChat({
55
54
  credentials,
56
55
  headers: metadataHeaders,
57
56
  body: metadataBody,
58
- generateId: generateId2 = import_ui_utils.generateId,
57
+ generateId = import_ui_utils.generateId,
59
58
  onToolCall,
60
- fetch: fetch2,
59
+ fetch,
61
60
  keepLastMessageOnError = true,
62
61
  maxSteps = 1,
63
62
  experimental_prepareRequestBody
@@ -65,7 +64,7 @@ function useChat({
65
64
  maxSteps: 1
66
65
  }) {
67
66
  var _a, _b;
68
- const chatId = id != null ? id : generateId2();
67
+ const chatId = id != null ? id : generateId();
69
68
  const key = `${api}|${chatId}`;
70
69
  const { data: messagesData, mutate: originalMutate } = useSWRV(
71
70
  key,
@@ -159,9 +158,9 @@ function useChat({
159
158
  mutate(previousMessages);
160
159
  }
161
160
  },
162
- generateId: generateId2,
161
+ generateId,
163
162
  onToolCall,
164
- fetch: fetch2,
163
+ fetch,
165
164
  // enabled use of structured clone in processChatResponse:
166
165
  lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1])
167
166
  });
@@ -197,7 +196,7 @@ function useChat({
197
196
  return triggerRequest(
198
197
  messages.value.concat({
199
198
  ...message,
200
- id: (_a2 = message.id) != null ? _a2 : generateId2(),
199
+ id: (_a2 = message.id) != null ? _a2 : generateId(),
201
200
  createdAt: (_b2 = message.createdAt) != null ? _b2 : /* @__PURE__ */ new Date(),
202
201
  experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
203
202
  parts: (0, import_ui_utils.getMessageParts)(message)
@@ -245,7 +244,7 @@ function useChat({
245
244
  );
246
245
  triggerRequest(
247
246
  messages.value.concat({
248
- id: generateId2(),
247
+ id: generateId(),
249
248
  createdAt: /* @__PURE__ */ new Date(),
250
249
  content: inputValue,
251
250
  role: "user",
@@ -267,6 +266,9 @@ function useChat({
267
266
  toolResult: result
268
267
  });
269
268
  mutate(currentMessages);
269
+ if (status.value === "submitted" || status.value === "streaming") {
270
+ return;
271
+ }
270
272
  const lastMessage = currentMessages[currentMessages.length - 1];
271
273
  if ((0, import_ui_utils.isAssistantMessageWithCompletedToolCalls)(lastMessage)) {
272
274
  triggerRequest(currentMessages);
@@ -324,7 +326,7 @@ function useCompletion({
324
326
  onResponse,
325
327
  onFinish,
326
328
  onError,
327
- fetch: fetch2
329
+ fetch
328
330
  } = {}) {
329
331
  var _a;
330
332
  const completionId = id || `completion-${uniqueId++}`;
@@ -377,7 +379,7 @@ function useCompletion({
377
379
  onData: (data2) => {
378
380
  mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
379
381
  },
380
- fetch: fetch2
382
+ fetch
381
383
  });
382
384
  }
383
385
  const complete = async (prompt, options) => {
@@ -411,178 +413,8 @@ function useCompletion({
411
413
  data: streamData
412
414
  };
413
415
  }
414
-
415
- // src/use-assistant.ts
416
- var import_provider_utils = require("@ai-sdk/provider-utils");
417
- var import_ui_utils3 = require("@ai-sdk/ui-utils");
418
- var import_vue3 = require("vue");
419
- function useAssistant({
420
- api,
421
- threadId: threadIdParam,
422
- credentials,
423
- headers,
424
- body,
425
- onError
426
- }) {
427
- const messages = (0, import_vue3.ref)([]);
428
- const input = (0, import_vue3.ref)("");
429
- const currentThreadId = (0, import_vue3.ref)(void 0);
430
- const status = (0, import_vue3.ref)("awaiting_message");
431
- const error = (0, import_vue3.ref)(void 0);
432
- const setMessages = (messageFactory) => {
433
- messages.value = messageFactory(messages.value);
434
- };
435
- const setCurrentThreadId = (newThreadId) => {
436
- currentThreadId.value = newThreadId;
437
- messages.value = [];
438
- };
439
- const handleInputChange = (event) => {
440
- var _a;
441
- input.value = (_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value;
442
- };
443
- const isSending = (0, import_vue3.computed)(() => status.value === "in_progress");
444
- const abortController = (0, import_vue3.ref)(null);
445
- const stop = (0, import_vue3.computed)(() => {
446
- return () => {
447
- if (abortController.value) {
448
- abortController.value.abort();
449
- abortController.value = null;
450
- }
451
- };
452
- });
453
- const append = async (message, requestOptions) => {
454
- var _a, _b, _c, _d;
455
- status.value = "in_progress";
456
- const newMessage = {
457
- ...message,
458
- id: (_a = message.id) != null ? _a : (0, import_ui_utils3.generateId)()
459
- };
460
- setMessages((messages2) => [...messages2, newMessage]);
461
- input.value = "";
462
- const controller = new AbortController();
463
- try {
464
- abortController.value = controller;
465
- const response = await fetch(api, {
466
- method: "POST",
467
- headers: {
468
- "Content-Type": "application/json",
469
- ...headers
470
- },
471
- body: JSON.stringify({
472
- ...body,
473
- // Message Content
474
- message: message.content,
475
- // Always Use User Provided Thread ID When Available
476
- threadId: (_b = threadIdParam != null ? threadIdParam : currentThreadId.value) != null ? _b : null,
477
- // Optional Request Data
478
- ...(requestOptions == null ? void 0 : requestOptions.data) && { data: requestOptions == null ? void 0 : requestOptions.data }
479
- }),
480
- signal: controller.signal,
481
- credentials
482
- });
483
- if (!response.ok) {
484
- throw new Error(
485
- (_c = response.statusText) != null ? _c : "An error occurred while sending the message"
486
- );
487
- }
488
- if (!response.body) {
489
- throw new Error("The response body is empty");
490
- }
491
- await (0, import_ui_utils3.processAssistantStream)({
492
- stream: response.body,
493
- onAssistantMessagePart(value) {
494
- messages.value = [
495
- ...messages.value,
496
- {
497
- id: value.id,
498
- content: value.content[0].text.value,
499
- role: value.role,
500
- parts: []
501
- }
502
- ];
503
- },
504
- onTextPart(value) {
505
- setMessages((messages2) => {
506
- const lastMessage = messages2[messages2.length - 1];
507
- lastMessage.content += value;
508
- return [...messages2.slice(0, -1), lastMessage];
509
- });
510
- },
511
- onAssistantControlDataPart(value) {
512
- if (value.threadId) {
513
- currentThreadId.value = value.threadId;
514
- }
515
- setMessages((messages2) => {
516
- const lastMessage = messages2[messages2.length - 1];
517
- lastMessage.id = value.messageId;
518
- return [...messages2.slice(0, -1), lastMessage];
519
- });
520
- },
521
- onDataMessagePart(value) {
522
- setMessages((messages2) => {
523
- var _a2;
524
- return [
525
- ...messages2,
526
- {
527
- id: (_a2 = value.id) != null ? _a2 : (0, import_ui_utils3.generateId)(),
528
- role: "data",
529
- content: "",
530
- data: value.data,
531
- parts: []
532
- }
533
- ];
534
- });
535
- },
536
- onErrorPart(value) {
537
- error.value = new Error(value);
538
- }
539
- });
540
- } catch (err) {
541
- if ((0, import_provider_utils.isAbortError)(err) && ((_d = abortController.value) == null ? void 0 : _d.signal.aborted)) {
542
- abortController.value = null;
543
- return;
544
- }
545
- if (onError && err instanceof Error) {
546
- onError(err);
547
- }
548
- error.value = err;
549
- } finally {
550
- abortController.value = null;
551
- status.value = "awaiting_message";
552
- }
553
- };
554
- const submitMessage = async (event, requestOptions) => {
555
- var _a;
556
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
557
- if (!input.value)
558
- return;
559
- append(
560
- {
561
- role: "user",
562
- content: input.value,
563
- parts: []
564
- },
565
- requestOptions
566
- );
567
- };
568
- return {
569
- append,
570
- messages,
571
- setMessages,
572
- threadId: (0, import_vue3.readonly)(currentThreadId),
573
- setThreadId: setCurrentThreadId,
574
- input,
575
- handleInputChange,
576
- handleSubmit: submitMessage,
577
- isSending,
578
- status,
579
- error,
580
- stop
581
- };
582
- }
583
416
  // Annotate the CommonJS export names for ESM import in node:
584
417
  0 && (module.exports = {
585
- useAssistant,
586
418
  useChat,
587
419
  useCompletion
588
420
  });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/use-completion.ts","../src/use-assistant.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-assistant';\n","import type {\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { computed, ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<UIMessage[]>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: Message[] | ((messages: Message[]) => Message[]),\n ) => void;\n /** The current value of the input */\n input: Ref<string>;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: Ref<boolean>;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: Ref<'submitted' | 'streaming' | 'ready' | 'error'>;\n\n /** Additional data added on the server via StreamData. */\n data: Ref<JSONValue[] | undefined>;\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\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, UIMessage[] | undefined> = {};\n\nexport function useChat(\n {\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers: metadataHeaders,\n body: metadataBody,\n generateId = generateIdFunc,\n onToolCall,\n fetch,\n keepLastMessageOnError = true,\n maxSteps = 1,\n experimental_prepareRequestBody,\n }: UseChatOptions & {\n /**\n * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n * A maximum number is required to prevent infinite loops in the case of misconfigured tools.\n * By default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n\n /**\n * Experimental (Vue only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param id The chat ID\n * @param messages The current messages in the chat\n * @param requestData The data object passed in the chat request\n * @param requestBody The request body object passed in the chat request\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n } = {\n maxSteps: 1,\n },\n): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id ?? generateId();\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<UIMessage[]>(\n key,\n () => store[key] ?? fillMessageParts(initialMessages),\n );\n\n const { data: status, mutate: mutateStatus } = useSWRV<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >(`${chatId}-status`, null);\n\n status.value ??= 'ready';\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= fillMessageParts(initialMessages);\n\n const mutate = (data?: UIMessage[]) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const messages = messagesData as Ref<UIMessage[]>;\n\n const error = ref<undefined | Error>(undefined);\n // cannot use JSONValue[] in ref because of infinite Typescript recursion:\n const streamData = ref<undefined | unknown[]>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n messagesSnapshot: Message[],\n { data, headers, body }: ChatRequestOptions = {},\n ) {\n error.value = undefined;\n mutateStatus(() => 'submitted');\n\n const messageCount = messages.value.length;\n const maxStep = extractMaxToolInvocationStep(\n messages.value[messages.value.length - 1]?.toolInvocations,\n );\n\n try {\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = fillMessageParts(messagesSnapshot);\n const chatMessages = previousMessages;\n mutate(chatMessages);\n\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: data,\n requestBody: body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data,\n ...unref(metadataBody), // Use unref to unwrap the ref value\n ...body,\n },\n streamProtocol,\n headers: {\n ...metadataHeaders,\n ...headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus(() => 'streaming');\n\n mutate([\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ]);\n if (data?.length) {\n streamData.value = [...existingData, ...data];\n }\n },\n onFinish,\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n generateId,\n onToolCall,\n fetch,\n // enabled use of structured clone in processChatResponse:\n lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1]),\n });\n\n mutateStatus(() => 'ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n mutateStatus(() => 'ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n mutateStatus(() => 'error');\n } finally {\n abortController = null;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages: messages.value,\n })\n ) {\n await triggerRequest(messages.value);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options?.experimental_attachments,\n );\n\n return triggerRequest(\n messages.value.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n }),\n options,\n );\n };\n\n const reload: UseChatHelpers['reload'] = async options => {\n const messagesSnapshot = messages.value;\n if (messagesSnapshot.length === 0) return null;\n\n const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];\n if (lastMessage.role === 'assistant') {\n return triggerRequest(messagesSnapshot.slice(0, -1), options);\n }\n\n return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (\n messagesArg: Message[] | ((messages: Message[]) => Message[]),\n ) => {\n if (typeof messagesArg === 'function') {\n messagesArg = messagesArg(messages.value);\n }\n\n mutate(fillMessageParts(messagesArg));\n };\n\n const setData = (\n dataArg:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof dataArg === 'function') {\n dataArg = dataArg(streamData.value as JSONValue[] | undefined);\n }\n\n streamData.value = dataArg;\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n if (!inputValue && !options.allowEmptySubmit) return;\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n triggerRequest(\n messages.value.concat({\n id: generateId(),\n createdAt: new Date(),\n content: inputValue,\n role: 'user',\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: inputValue }],\n }),\n options,\n );\n\n input.value = '';\n };\n\n const addToolResult = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: unknown;\n }) => {\n const currentMessages = messages.value;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n mutate(currentMessages);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest(currentMessages);\n }\n };\n\n return {\n id: chatId,\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading: computed(\n () => status.value === 'submitted' || status.value === 'streaming',\n ),\n status: status as Ref<'submitted' | 'streaming' | 'ready' | 'error'>,\n data: streamData as Ref<undefined | JSONValue[]>,\n setData,\n addToolResult,\n };\n}\n\n// required for use of structured clone\nfunction recursiveToRaw<T>(inputValue: T): T {\n if (Array.isArray(inputValue)) {\n return [...inputValue.map(recursiveToRaw)] as T;\n } else if (typeof inputValue === 'object' && inputValue !== null) {\n const clone: any = {};\n for (const [key, value] of Object.entries(inputValue)) {\n clone[key] = recursiveToRaw(value);\n }\n return clone;\n } else {\n return inputValue;\n }\n}\n","import type {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n} from '@ai-sdk/ui-utils';\nimport { callCompletionApi } from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data: Ref<JSONValue[] | 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 onResponse,\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 const { data: streamData, mutate: mutateStreamData } = useSWRV<\n JSONValue[] | undefined\n >(`${completionId}-data`, null);\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(prompt: string, options?: RequestOptions) {\n const existingData = (streamData.value ?? []) as JSONValue[];\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 onResponse,\n onFinish,\n onError,\n onData: data => {\n mutateStreamData(() => [...existingData, ...(data ?? [])]);\n },\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 data: streamData,\n };\n}\n","/**\n * A vue.js composable function to interact with the assistant API.\n */\n\nimport { isAbortError } from '@ai-sdk/provider-utils';\nimport type {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n} from '@ai-sdk/ui-utils';\nimport { generateId, processAssistantStream } from '@ai-sdk/ui-utils';\nimport type { ComputedRef, Ref } from 'vue';\nimport { computed, readonly, ref } from 'vue';\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Ref<Message[]>;\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;\n\n /**\n * The current thread ID.\n */\n threadId: Ref<string | undefined>;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n /**\n * The current value of the input field.\n */\n input: Ref<string>;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: ComputedRef<() => void>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (e: Event & { target: HTMLInputElement }) => void;\n\n /**\n * Handler for the `onSubmit` event of the form to append a user message and reset the input.\n */\n handleSubmit: (e: Event & { target: HTMLFormElement }) => void;\n\n /**\n * Whether the assistant is currently sending a message.\n */\n isSending: ComputedRef<boolean>;\n\n /**\n * The current status of the assistant.\n */\n status: Ref<AssistantStatus>;\n\n /**\n * The current error, if any.\n */\n error: Ref<Error | undefined>;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n}: UseAssistantOptions): UseAssistantHelpers {\n const messages: Ref<Message[]> = ref([]);\n const input: Ref<string> = ref('');\n const currentThreadId: Ref<string | undefined> = ref(undefined);\n const status: Ref<AssistantStatus> = ref('awaiting_message');\n const error: Ref<undefined | Error> = ref(undefined);\n\n const setMessages = (messageFactory: (messages: Message[]) => Message[]) => {\n messages.value = messageFactory(messages.value);\n };\n\n const setCurrentThreadId = (newThreadId: string | undefined) => {\n currentThreadId.value = newThreadId;\n messages.value = [];\n };\n\n const handleInputChange = (event: Event & { target: HTMLInputElement }) => {\n input.value = event?.target?.value;\n };\n\n const isSending = computed(() => status.value === 'in_progress');\n\n // Abort controller to cancel the current API call when required\n const abortController = ref<AbortController | null>(null);\n\n // memoized function to stop the current request when required\n const stop = computed(() => {\n return () => {\n if (abortController.value) {\n abortController.value.abort();\n abortController.value = null;\n }\n };\n });\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n status.value = 'in_progress';\n\n // Append the new message to the current list of messages\n const newMessage: Message = {\n ...message,\n id: message.id ?? generateId(),\n };\n\n // Update the messages list with the new message\n setMessages(messages => [...messages, newMessage]);\n\n input.value = '';\n\n const controller = new AbortController();\n\n try {\n // Assign the new controller to the abortController ref\n abortController.value = controller;\n\n const response = await fetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({\n ...body,\n // Message Content\n message: message.content,\n\n // Always Use User Provided Thread ID When Available\n threadId: threadIdParam ?? currentThreadId.value ?? null,\n\n // Optional Request Data\n ...(requestOptions?.data && { data: requestOptions?.data }),\n }),\n signal: controller.signal,\n credentials,\n });\n\n if (!response.ok) {\n throw new Error(\n response.statusText ?? 'An error occurred while sending the message',\n );\n }\n\n if (!response.body) {\n throw new Error('The response body is empty');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n messages.value = [\n ...messages.value,\n {\n id: value.id,\n content: value.content[0].text.value,\n role: value.role,\n parts: [],\n },\n ];\n },\n onTextPart(value) {\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.content += value;\n\n return [...messages.slice(0, -1), lastMessage];\n });\n },\n onAssistantControlDataPart(value) {\n if (value.threadId) {\n currentThreadId.value = value.threadId;\n }\n\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n\n return [...messages.slice(0, -1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n parts: [],\n },\n ]);\n },\n onErrorPart(value) {\n error.value = new Error(value);\n },\n });\n } catch (err) {\n // If the error is an AbortError and the signal is aborted, reset the abortController and do nothing.\n if (isAbortError(err) && abortController.value?.signal.aborted) {\n abortController.value = null;\n return;\n }\n\n // If an error handler is provided, call it with the error\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n } finally {\n // Reset the status to 'awaiting_message' after the request is complete\n abortController.value = null;\n status.value = 'awaiting_message';\n }\n };\n\n const submitMessage = async (\n event: Event & { target: HTMLFormElement },\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (!input.value) return;\n\n append(\n {\n role: 'user',\n content: input.value,\n parts: [],\n },\n requestOptions,\n );\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: readonly(currentThreadId),\n setThreadId: setCurrentThreadId,\n input,\n handleInputChange,\n handleSubmit: submitMessage,\n isSending,\n status,\n error,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,sBAUO;AACP,kBAAiB;AAEjB,iBAAqC;AAqFrC,IAAM,UAAW,YAAAA,QAAK,WAAkD,YAAAA;AACxE,IAAM,QAAiD,CAAC;AAEjD,SAAS,QACd;AAAA,EACE,MAAM;AAAA,EACN;AAAA,EACA,kBAAkB,CAAC;AAAA,EACnB,eAAe;AAAA,EACf;AAAA,EACA,iBAAiB;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT,MAAM;AAAA,EACN,YAAAC,cAAa,gBAAAC;AAAA,EACb;AAAA,EACA,OAAAC;AAAA,EACA,yBAAyB;AAAA,EACzB,WAAW;AAAA,EACX;AACF,IAwBI;AAAA,EACF,UAAU;AACZ,GACgB;AA5JlB;AA8JE,QAAM,SAAS,kBAAMF,YAAW;AAEhC,QAAM,MAAM,GAAG,GAAG,IAAI,MAAM;AAC5B,QAAM,EAAE,MAAM,cAAc,QAAQ,eAAe,IAAI;AAAA,IACrD;AAAA,IACA,MAAG;AAnKP,UAAAG;AAmKU,cAAAA,MAAA,MAAM,GAAG,MAAT,OAAAA,UAAc,kCAAiB,eAAe;AAAA;AAAA,EACtD;AAEA,QAAM,EAAE,MAAM,QAAQ,QAAQ,aAAa,IAAI,QAE7C,GAAG,MAAM,WAAW,IAAI;AAE1B,eAAO,UAAP,mBAAO,QAAU;AAGjB,qBAAa,UAAb,yBAAa,YAAU,kCAAiB,eA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QACH;AAAA,QACA,kBAAkB,OAAO;AACvB,sBAAY,CAAAA,cAAS;AAxN/B,gBAAAC;AAwNkC;AAAA,cACtB,GAAGD;AAAA,cACH;AAAA,gBACE,KAAIC,MAAA,MAAM,OAAN,OAAAA,UAAY,6BAAW;AAAA,gBAC3B,MAAM;AAAA,gBACN,SAAS;AAAA,gBACT,MAAM,MAAM;AAAA,gBACZ,OAAO,CAAC;AAAA,cACV;AAAA,YACF;AAAA,WAAC;AAAA,QACH;AAAA,QACA,YAAY,OAAO;AACjB,gBAAM,QAAQ,IAAI,MAAM,KAAK;AAAA,QAC/B;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AAEZ,cAAI,oCAAa,GAAG,OAAK,qBAAgB,UAAhB,mBAAuB,OAAO,UAAS;AAC9D,wBAAgB,QAAQ;AACxB;AAAA,MACF;AAGA,UAAI,WAAW,eAAe,OAAO;AACnC,gBAAQ,GAAG;AAAA,MACb;AAEA,YAAM,QAAQ;AAAA,IAChB,UAAE;AAEA,sBAAgB,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,gBAAgB,OACpB,OACA,mBAGG;AAhQP;AAiQI,yCAAO,mBAAP;AAEA,QAAI,CAAC,MAAM;AAAO;AAElB;AAAA,MACE;AAAA,QACE,MAAM;AAAA,QACN,SAAS,MAAM;AAAA,QACf,OAAO,CAAC;AAAA,MACV;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAU,sBAAS,eAAe;AAAA,IAClC,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["swrv","generateId","generateIdFunc","fetch","_a","_b","data","import_ui_utils","import_swrv","import_vue","useSWRV","swrv","store","fetch","data","_a","completion","import_ui_utils","import_vue","messages","_a"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/use-completion.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\n","import type {\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { computed, ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<UIMessage[]>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: Message[] | ((messages: Message[]) => Message[]),\n ) => void;\n /** The current value of the input */\n input: Ref<string>;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: Ref<boolean>;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: Ref<'submitted' | 'streaming' | 'ready' | 'error'>;\n\n /** Additional data added on the server via StreamData. */\n data: Ref<JSONValue[] | undefined>;\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\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, UIMessage[] | undefined> = {};\n\nexport function useChat(\n {\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers: metadataHeaders,\n body: metadataBody,\n generateId = generateIdFunc,\n onToolCall,\n fetch,\n keepLastMessageOnError = true,\n maxSteps = 1,\n experimental_prepareRequestBody,\n }: UseChatOptions & {\n /**\n * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n * A maximum number is required to prevent infinite loops in the case of misconfigured tools.\n * By default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n\n /**\n * Experimental (Vue only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param id The chat ID\n * @param messages The current messages in the chat\n * @param requestData The data object passed in the chat request\n * @param requestBody The request body object passed in the chat request\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n } = {\n maxSteps: 1,\n },\n): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id ?? generateId();\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<UIMessage[]>(\n key,\n () => store[key] ?? fillMessageParts(initialMessages),\n );\n\n const { data: status, mutate: mutateStatus } = useSWRV<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >(`${chatId}-status`, null);\n\n status.value ??= 'ready';\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= fillMessageParts(initialMessages);\n\n const mutate = (data?: UIMessage[]) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const messages = messagesData as Ref<UIMessage[]>;\n\n const error = ref<undefined | Error>(undefined);\n // cannot use JSONValue[] in ref because of infinite Typescript recursion:\n const streamData = ref<undefined | unknown[]>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n messagesSnapshot: Message[],\n { data, headers, body }: ChatRequestOptions = {},\n ) {\n error.value = undefined;\n mutateStatus(() => 'submitted');\n\n const messageCount = messages.value.length;\n const maxStep = extractMaxToolInvocationStep(\n messages.value[messages.value.length - 1]?.toolInvocations,\n );\n\n try {\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = fillMessageParts(messagesSnapshot);\n const chatMessages = previousMessages;\n mutate(chatMessages);\n\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: data,\n requestBody: body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data,\n ...unref(metadataBody), // Use unref to unwrap the ref value\n ...body,\n },\n streamProtocol,\n headers: {\n ...metadataHeaders,\n ...headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus(() => 'streaming');\n\n mutate([\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ]);\n if (data?.length) {\n streamData.value = [...existingData, ...data];\n }\n },\n onFinish,\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n generateId,\n onToolCall,\n fetch,\n // enabled use of structured clone in processChatResponse:\n lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1]),\n });\n\n mutateStatus(() => 'ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n mutateStatus(() => 'ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n mutateStatus(() => 'error');\n } finally {\n abortController = null;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages: messages.value,\n })\n ) {\n await triggerRequest(messages.value);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options?.experimental_attachments,\n );\n\n return triggerRequest(\n messages.value.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n }),\n options,\n );\n };\n\n const reload: UseChatHelpers['reload'] = async options => {\n const messagesSnapshot = messages.value;\n if (messagesSnapshot.length === 0) return null;\n\n const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];\n if (lastMessage.role === 'assistant') {\n return triggerRequest(messagesSnapshot.slice(0, -1), options);\n }\n\n return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (\n messagesArg: Message[] | ((messages: Message[]) => Message[]),\n ) => {\n if (typeof messagesArg === 'function') {\n messagesArg = messagesArg(messages.value);\n }\n\n mutate(fillMessageParts(messagesArg));\n };\n\n const setData = (\n dataArg:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof dataArg === 'function') {\n dataArg = dataArg(streamData.value as JSONValue[] | undefined);\n }\n\n streamData.value = dataArg;\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n if (!inputValue && !options.allowEmptySubmit) return;\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n triggerRequest(\n messages.value.concat({\n id: generateId(),\n createdAt: new Date(),\n content: inputValue,\n role: 'user',\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: inputValue }],\n }),\n options,\n );\n\n input.value = '';\n };\n\n const addToolResult = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: unknown;\n }) => {\n const currentMessages = messages.value;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n mutate(currentMessages);\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status.value === 'submitted' || status.value === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest(currentMessages);\n }\n };\n\n return {\n id: chatId,\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading: computed(\n () => status.value === 'submitted' || status.value === 'streaming',\n ),\n status: status as Ref<'submitted' | 'streaming' | 'ready' | 'error'>,\n data: streamData as Ref<undefined | JSONValue[]>,\n setData,\n addToolResult,\n };\n}\n\n// required for use of structured clone\nfunction recursiveToRaw<T>(inputValue: T): T {\n if (Array.isArray(inputValue)) {\n return [...inputValue.map(recursiveToRaw)] as T;\n } else if (typeof inputValue === 'object' && inputValue !== null) {\n const clone: any = {};\n for (const [key, value] of Object.entries(inputValue)) {\n clone[key] = recursiveToRaw(value);\n }\n return clone;\n } else {\n return inputValue;\n }\n}\n","import type {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n} from '@ai-sdk/ui-utils';\nimport { callCompletionApi } from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data: Ref<JSONValue[] | 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 onResponse,\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 const { data: streamData, mutate: mutateStreamData } = useSWRV<\n JSONValue[] | undefined\n >(`${completionId}-data`, null);\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(prompt: string, options?: RequestOptions) {\n const existingData = (streamData.value ?? []) as JSONValue[];\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 onResponse,\n onFinish,\n onError,\n onData: data => {\n mutateStreamData(() => [...existingData, ...(data ?? [])]);\n },\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,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b,GAAG,mCAAS;AAAA,MACd;AAAA,MACA;AAAA,MACA,eAAe;AAAA,MACf,YAAY,aAAW,cAAc,MAAM,OAAO;AAAA,MAClD,UAAU,SAAO;AACf,cAAM,QAAQ;AAAA,MAChB;AAAA,MACA,oBAAoB,gBAAc;AAChC,0BAAkB;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,CAAAD,UAAQ;AACd,yBAAiB,MAAM,CAAC,GAAG,cAAc,GAAIA,SAAA,OAAAA,QAAQ,CAAC,CAAE,CAAC;AAAA,MAC3D;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA6C,OACjD,QACA,YACG;AACH,WAAO,eAAe,QAAQ,OAAO;AAAA,EACvC;AAEA,QAAM,OAAO,MAAM;AACjB,QAAI,iBAAiB;AACnB,sBAAgB,MAAM;AACtB,wBAAkB;AAAA,IACpB;AAAA,EACF;AAEA,QAAM,gBAAgB,CAACE,gBAAuB;AAC5C,WAAOA,WAAU;AAAA,EACnB;AAEA,QAAM,YAAQ,iBAAI,YAAY;AAE9B,QAAM,eAAe,CAAC,UAA4C;AA/JpE,QAAAD;AAgKI,KAAAA,MAAA,+BAAO,mBAAP,gBAAAA,IAAA;AACA,UAAM,aAAa,MAAM;AACzB,WAAO,aAAa,SAAS,UAAU,IAAI;AAAA,EAC7C;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR;AACF;","names":["swrv","generateIdFunc","_a","_b","data","import_ui_utils","import_swrv","import_vue","useSWRV","swrv","store","data","_a","completion"]}
package/dist/index.mjs CHANGED
@@ -27,9 +27,9 @@ function useChat({
27
27
  credentials,
28
28
  headers: metadataHeaders,
29
29
  body: metadataBody,
30
- generateId: generateId2 = generateIdFunc,
30
+ generateId = generateIdFunc,
31
31
  onToolCall,
32
- fetch: fetch2,
32
+ fetch,
33
33
  keepLastMessageOnError = true,
34
34
  maxSteps = 1,
35
35
  experimental_prepareRequestBody
@@ -37,7 +37,7 @@ function useChat({
37
37
  maxSteps: 1
38
38
  }) {
39
39
  var _a, _b;
40
- const chatId = id != null ? id : generateId2();
40
+ const chatId = id != null ? id : generateId();
41
41
  const key = `${api}|${chatId}`;
42
42
  const { data: messagesData, mutate: originalMutate } = useSWRV(
43
43
  key,
@@ -131,9 +131,9 @@ function useChat({
131
131
  mutate(previousMessages);
132
132
  }
133
133
  },
134
- generateId: generateId2,
134
+ generateId,
135
135
  onToolCall,
136
- fetch: fetch2,
136
+ fetch,
137
137
  // enabled use of structured clone in processChatResponse:
138
138
  lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1])
139
139
  });
@@ -169,7 +169,7 @@ function useChat({
169
169
  return triggerRequest(
170
170
  messages.value.concat({
171
171
  ...message,
172
- id: (_a2 = message.id) != null ? _a2 : generateId2(),
172
+ id: (_a2 = message.id) != null ? _a2 : generateId(),
173
173
  createdAt: (_b2 = message.createdAt) != null ? _b2 : /* @__PURE__ */ new Date(),
174
174
  experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
175
175
  parts: getMessageParts(message)
@@ -217,7 +217,7 @@ function useChat({
217
217
  );
218
218
  triggerRequest(
219
219
  messages.value.concat({
220
- id: generateId2(),
220
+ id: generateId(),
221
221
  createdAt: /* @__PURE__ */ new Date(),
222
222
  content: inputValue,
223
223
  role: "user",
@@ -239,6 +239,9 @@ function useChat({
239
239
  toolResult: result
240
240
  });
241
241
  mutate(currentMessages);
242
+ if (status.value === "submitted" || status.value === "streaming") {
243
+ return;
244
+ }
242
245
  const lastMessage = currentMessages[currentMessages.length - 1];
243
246
  if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
244
247
  triggerRequest(currentMessages);
@@ -296,7 +299,7 @@ function useCompletion({
296
299
  onResponse,
297
300
  onFinish,
298
301
  onError,
299
- fetch: fetch2
302
+ fetch
300
303
  } = {}) {
301
304
  var _a;
302
305
  const completionId = id || `completion-${uniqueId++}`;
@@ -349,7 +352,7 @@ function useCompletion({
349
352
  onData: (data2) => {
350
353
  mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
351
354
  },
352
- fetch: fetch2
355
+ fetch
353
356
  });
354
357
  }
355
358
  const complete = async (prompt, options) => {
@@ -383,177 +386,7 @@ function useCompletion({
383
386
  data: streamData
384
387
  };
385
388
  }
386
-
387
- // src/use-assistant.ts
388
- import { isAbortError } from "@ai-sdk/provider-utils";
389
- import { generateId, processAssistantStream } from "@ai-sdk/ui-utils";
390
- import { computed as computed2, readonly, ref as ref3 } from "vue";
391
- function useAssistant({
392
- api,
393
- threadId: threadIdParam,
394
- credentials,
395
- headers,
396
- body,
397
- onError
398
- }) {
399
- const messages = ref3([]);
400
- const input = ref3("");
401
- const currentThreadId = ref3(void 0);
402
- const status = ref3("awaiting_message");
403
- const error = ref3(void 0);
404
- const setMessages = (messageFactory) => {
405
- messages.value = messageFactory(messages.value);
406
- };
407
- const setCurrentThreadId = (newThreadId) => {
408
- currentThreadId.value = newThreadId;
409
- messages.value = [];
410
- };
411
- const handleInputChange = (event) => {
412
- var _a;
413
- input.value = (_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value;
414
- };
415
- const isSending = computed2(() => status.value === "in_progress");
416
- const abortController = ref3(null);
417
- const stop = computed2(() => {
418
- return () => {
419
- if (abortController.value) {
420
- abortController.value.abort();
421
- abortController.value = null;
422
- }
423
- };
424
- });
425
- const append = async (message, requestOptions) => {
426
- var _a, _b, _c, _d;
427
- status.value = "in_progress";
428
- const newMessage = {
429
- ...message,
430
- id: (_a = message.id) != null ? _a : generateId()
431
- };
432
- setMessages((messages2) => [...messages2, newMessage]);
433
- input.value = "";
434
- const controller = new AbortController();
435
- try {
436
- abortController.value = controller;
437
- const response = await fetch(api, {
438
- method: "POST",
439
- headers: {
440
- "Content-Type": "application/json",
441
- ...headers
442
- },
443
- body: JSON.stringify({
444
- ...body,
445
- // Message Content
446
- message: message.content,
447
- // Always Use User Provided Thread ID When Available
448
- threadId: (_b = threadIdParam != null ? threadIdParam : currentThreadId.value) != null ? _b : null,
449
- // Optional Request Data
450
- ...(requestOptions == null ? void 0 : requestOptions.data) && { data: requestOptions == null ? void 0 : requestOptions.data }
451
- }),
452
- signal: controller.signal,
453
- credentials
454
- });
455
- if (!response.ok) {
456
- throw new Error(
457
- (_c = response.statusText) != null ? _c : "An error occurred while sending the message"
458
- );
459
- }
460
- if (!response.body) {
461
- throw new Error("The response body is empty");
462
- }
463
- await processAssistantStream({
464
- stream: response.body,
465
- onAssistantMessagePart(value) {
466
- messages.value = [
467
- ...messages.value,
468
- {
469
- id: value.id,
470
- content: value.content[0].text.value,
471
- role: value.role,
472
- parts: []
473
- }
474
- ];
475
- },
476
- onTextPart(value) {
477
- setMessages((messages2) => {
478
- const lastMessage = messages2[messages2.length - 1];
479
- lastMessage.content += value;
480
- return [...messages2.slice(0, -1), lastMessage];
481
- });
482
- },
483
- onAssistantControlDataPart(value) {
484
- if (value.threadId) {
485
- currentThreadId.value = value.threadId;
486
- }
487
- setMessages((messages2) => {
488
- const lastMessage = messages2[messages2.length - 1];
489
- lastMessage.id = value.messageId;
490
- return [...messages2.slice(0, -1), lastMessage];
491
- });
492
- },
493
- onDataMessagePart(value) {
494
- setMessages((messages2) => {
495
- var _a2;
496
- return [
497
- ...messages2,
498
- {
499
- id: (_a2 = value.id) != null ? _a2 : generateId(),
500
- role: "data",
501
- content: "",
502
- data: value.data,
503
- parts: []
504
- }
505
- ];
506
- });
507
- },
508
- onErrorPart(value) {
509
- error.value = new Error(value);
510
- }
511
- });
512
- } catch (err) {
513
- if (isAbortError(err) && ((_d = abortController.value) == null ? void 0 : _d.signal.aborted)) {
514
- abortController.value = null;
515
- return;
516
- }
517
- if (onError && err instanceof Error) {
518
- onError(err);
519
- }
520
- error.value = err;
521
- } finally {
522
- abortController.value = null;
523
- status.value = "awaiting_message";
524
- }
525
- };
526
- const submitMessage = async (event, requestOptions) => {
527
- var _a;
528
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
529
- if (!input.value)
530
- return;
531
- append(
532
- {
533
- role: "user",
534
- content: input.value,
535
- parts: []
536
- },
537
- requestOptions
538
- );
539
- };
540
- return {
541
- append,
542
- messages,
543
- setMessages,
544
- threadId: readonly(currentThreadId),
545
- setThreadId: setCurrentThreadId,
546
- input,
547
- handleInputChange,
548
- handleSubmit: submitMessage,
549
- isSending,
550
- status,
551
- error,
552
- stop
553
- };
554
- }
555
389
  export {
556
- useAssistant,
557
390
  useChat,
558
391
  useCompletion
559
392
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/use-completion.ts","../src/use-assistant.ts"],"sourcesContent":["import type {\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { computed, ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<UIMessage[]>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: Message[] | ((messages: Message[]) => Message[]),\n ) => void;\n /** The current value of the input */\n input: Ref<string>;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: Ref<boolean>;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: Ref<'submitted' | 'streaming' | 'ready' | 'error'>;\n\n /** Additional data added on the server via StreamData. */\n data: Ref<JSONValue[] | undefined>;\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\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, UIMessage[] | undefined> = {};\n\nexport function useChat(\n {\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers: metadataHeaders,\n body: metadataBody,\n generateId = generateIdFunc,\n onToolCall,\n fetch,\n keepLastMessageOnError = true,\n maxSteps = 1,\n experimental_prepareRequestBody,\n }: UseChatOptions & {\n /**\n * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n * A maximum number is required to prevent infinite loops in the case of misconfigured tools.\n * By default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n\n /**\n * Experimental (Vue only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param id The chat ID\n * @param messages The current messages in the chat\n * @param requestData The data object passed in the chat request\n * @param requestBody The request body object passed in the chat request\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n } = {\n maxSteps: 1,\n },\n): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id ?? generateId();\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<UIMessage[]>(\n key,\n () => store[key] ?? fillMessageParts(initialMessages),\n );\n\n const { data: status, mutate: mutateStatus } = useSWRV<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >(`${chatId}-status`, null);\n\n status.value ??= 'ready';\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= fillMessageParts(initialMessages);\n\n const mutate = (data?: UIMessage[]) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const messages = messagesData as Ref<UIMessage[]>;\n\n const error = ref<undefined | Error>(undefined);\n // cannot use JSONValue[] in ref because of infinite Typescript recursion:\n const streamData = ref<undefined | unknown[]>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n messagesSnapshot: Message[],\n { data, headers, body }: ChatRequestOptions = {},\n ) {\n error.value = undefined;\n mutateStatus(() => 'submitted');\n\n const messageCount = messages.value.length;\n const maxStep = extractMaxToolInvocationStep(\n messages.value[messages.value.length - 1]?.toolInvocations,\n );\n\n try {\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = fillMessageParts(messagesSnapshot);\n const chatMessages = previousMessages;\n mutate(chatMessages);\n\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: data,\n requestBody: body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data,\n ...unref(metadataBody), // Use unref to unwrap the ref value\n ...body,\n },\n streamProtocol,\n headers: {\n ...metadataHeaders,\n ...headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus(() => 'streaming');\n\n mutate([\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ]);\n if (data?.length) {\n streamData.value = [...existingData, ...data];\n }\n },\n onFinish,\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n generateId,\n onToolCall,\n fetch,\n // enabled use of structured clone in processChatResponse:\n lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1]),\n });\n\n mutateStatus(() => 'ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n mutateStatus(() => 'ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n mutateStatus(() => 'error');\n } finally {\n abortController = null;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages: messages.value,\n })\n ) {\n await triggerRequest(messages.value);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options?.experimental_attachments,\n );\n\n return triggerRequest(\n messages.value.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n }),\n options,\n );\n };\n\n const reload: UseChatHelpers['reload'] = async options => {\n const messagesSnapshot = messages.value;\n if (messagesSnapshot.length === 0) return null;\n\n const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];\n if (lastMessage.role === 'assistant') {\n return triggerRequest(messagesSnapshot.slice(0, -1), options);\n }\n\n return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (\n messagesArg: Message[] | ((messages: Message[]) => Message[]),\n ) => {\n if (typeof messagesArg === 'function') {\n messagesArg = messagesArg(messages.value);\n }\n\n mutate(fillMessageParts(messagesArg));\n };\n\n const setData = (\n dataArg:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof dataArg === 'function') {\n dataArg = dataArg(streamData.value as JSONValue[] | undefined);\n }\n\n streamData.value = dataArg;\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n if (!inputValue && !options.allowEmptySubmit) return;\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n triggerRequest(\n messages.value.concat({\n id: generateId(),\n createdAt: new Date(),\n content: inputValue,\n role: 'user',\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: inputValue }],\n }),\n options,\n );\n\n input.value = '';\n };\n\n const addToolResult = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: unknown;\n }) => {\n const currentMessages = messages.value;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n mutate(currentMessages);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest(currentMessages);\n }\n };\n\n return {\n id: chatId,\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading: computed(\n () => status.value === 'submitted' || status.value === 'streaming',\n ),\n status: status as Ref<'submitted' | 'streaming' | 'ready' | 'error'>,\n data: streamData as Ref<undefined | JSONValue[]>,\n setData,\n addToolResult,\n };\n}\n\n// required for use of structured clone\nfunction recursiveToRaw<T>(inputValue: T): T {\n if (Array.isArray(inputValue)) {\n return [...inputValue.map(recursiveToRaw)] as T;\n } else if (typeof inputValue === 'object' && inputValue !== null) {\n const clone: any = {};\n for (const [key, value] of Object.entries(inputValue)) {\n clone[key] = recursiveToRaw(value);\n }\n return clone;\n } else {\n return inputValue;\n }\n}\n","import type {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n} from '@ai-sdk/ui-utils';\nimport { callCompletionApi } from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data: Ref<JSONValue[] | 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 onResponse,\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 const { data: streamData, mutate: mutateStreamData } = useSWRV<\n JSONValue[] | undefined\n >(`${completionId}-data`, null);\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(prompt: string, options?: RequestOptions) {\n const existingData = (streamData.value ?? []) as JSONValue[];\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 onResponse,\n onFinish,\n onError,\n onData: data => {\n mutateStreamData(() => [...existingData, ...(data ?? [])]);\n },\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 data: streamData,\n };\n}\n","/**\n * A vue.js composable function to interact with the assistant API.\n */\n\nimport { isAbortError } from '@ai-sdk/provider-utils';\nimport type {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n} from '@ai-sdk/ui-utils';\nimport { generateId, processAssistantStream } from '@ai-sdk/ui-utils';\nimport type { ComputedRef, Ref } from 'vue';\nimport { computed, readonly, ref } from 'vue';\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Ref<Message[]>;\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;\n\n /**\n * The current thread ID.\n */\n threadId: Ref<string | undefined>;\n\n /**\n * Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.\n */\n setThreadId: (threadId: string | undefined) => void;\n /**\n * The current value of the input field.\n */\n input: Ref<string>;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param requestOptions Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => Promise<void>;\n\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: ComputedRef<() => void>;\n\n /**\n * Handler for the `onChange` event of the input field to control the input's value.\n */\n handleInputChange: (e: Event & { target: HTMLInputElement }) => void;\n\n /**\n * Handler for the `onSubmit` event of the form to append a user message and reset the input.\n */\n handleSubmit: (e: Event & { target: HTMLFormElement }) => void;\n\n /**\n * Whether the assistant is currently sending a message.\n */\n isSending: ComputedRef<boolean>;\n\n /**\n * The current status of the assistant.\n */\n status: Ref<AssistantStatus>;\n\n /**\n * The current error, if any.\n */\n error: Ref<Error | undefined>;\n};\n\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n}: UseAssistantOptions): UseAssistantHelpers {\n const messages: Ref<Message[]> = ref([]);\n const input: Ref<string> = ref('');\n const currentThreadId: Ref<string | undefined> = ref(undefined);\n const status: Ref<AssistantStatus> = ref('awaiting_message');\n const error: Ref<undefined | Error> = ref(undefined);\n\n const setMessages = (messageFactory: (messages: Message[]) => Message[]) => {\n messages.value = messageFactory(messages.value);\n };\n\n const setCurrentThreadId = (newThreadId: string | undefined) => {\n currentThreadId.value = newThreadId;\n messages.value = [];\n };\n\n const handleInputChange = (event: Event & { target: HTMLInputElement }) => {\n input.value = event?.target?.value;\n };\n\n const isSending = computed(() => status.value === 'in_progress');\n\n // Abort controller to cancel the current API call when required\n const abortController = ref<AbortController | null>(null);\n\n // memoized function to stop the current request when required\n const stop = computed(() => {\n return () => {\n if (abortController.value) {\n abortController.value.abort();\n abortController.value = null;\n }\n };\n });\n\n const append = async (\n message: Message | CreateMessage,\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n status.value = 'in_progress';\n\n // Append the new message to the current list of messages\n const newMessage: Message = {\n ...message,\n id: message.id ?? generateId(),\n };\n\n // Update the messages list with the new message\n setMessages(messages => [...messages, newMessage]);\n\n input.value = '';\n\n const controller = new AbortController();\n\n try {\n // Assign the new controller to the abortController ref\n abortController.value = controller;\n\n const response = await fetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({\n ...body,\n // Message Content\n message: message.content,\n\n // Always Use User Provided Thread ID When Available\n threadId: threadIdParam ?? currentThreadId.value ?? null,\n\n // Optional Request Data\n ...(requestOptions?.data && { data: requestOptions?.data }),\n }),\n signal: controller.signal,\n credentials,\n });\n\n if (!response.ok) {\n throw new Error(\n response.statusText ?? 'An error occurred while sending the message',\n );\n }\n\n if (!response.body) {\n throw new Error('The response body is empty');\n }\n\n await processAssistantStream({\n stream: response.body,\n onAssistantMessagePart(value) {\n messages.value = [\n ...messages.value,\n {\n id: value.id,\n content: value.content[0].text.value,\n role: value.role,\n parts: [],\n },\n ];\n },\n onTextPart(value) {\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.content += value;\n\n return [...messages.slice(0, -1), lastMessage];\n });\n },\n onAssistantControlDataPart(value) {\n if (value.threadId) {\n currentThreadId.value = value.threadId;\n }\n\n setMessages(messages => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n\n return [...messages.slice(0, -1), lastMessage];\n });\n },\n onDataMessagePart(value) {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n parts: [],\n },\n ]);\n },\n onErrorPart(value) {\n error.value = new Error(value);\n },\n });\n } catch (err) {\n // If the error is an AbortError and the signal is aborted, reset the abortController and do nothing.\n if (isAbortError(err) && abortController.value?.signal.aborted) {\n abortController.value = null;\n return;\n }\n\n // If an error handler is provided, call it with the error\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n } finally {\n // Reset the status to 'awaiting_message' after the request is complete\n abortController.value = null;\n status.value = 'awaiting_message';\n }\n };\n\n const submitMessage = async (\n event: Event & { target: HTMLFormElement },\n requestOptions?: {\n data?: Record<string, string>;\n },\n ) => {\n event?.preventDefault?.();\n\n if (!input.value) return;\n\n append(\n {\n role: 'user',\n content: input.value,\n parts: [],\n },\n requestOptions,\n );\n };\n\n return {\n append,\n messages,\n setMessages,\n threadId: readonly(currentThreadId),\n setThreadId: setCurrentThreadId,\n input,\n handleIn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A,MAAY,WAAW;AAAA,gBAC3B,MAAM;AAAA,gBACN,SAAS;AAAA,gBACT,MAAM,MAAM;AAAA,gBACZ,OAAO,CAAC;AAAA,cACV;AAAA,YACF;AAAA,WAAC;AAAA,QACH;AAAA,QACA,YAAY,OAAO;AACjB,gBAAM,QAAQ,IAAI,MAAM,KAAK;AAAA,QAC/B;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AAEZ,UAAI,aAAa,GAAG,OAAK,qBAAgB,UAAhB,mBAAuB,OAAO,UAAS;AAC9D,wBAAgB,QAAQ;AACxB;AAAA,MACF;AAGA,UAAI,WAAW,eAAe,OAAO;AACnC,gBAAQ,GAAG;AAAA,MACb;AAEA,YAAM,QAAQ;AAAA,IAChB,UAAE;AAEA,sBAAgB,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,gBAAgB,OACpB,OACA,mBAGG;AAhQP;AAiQI,yCAAO,mBAAP;AAEA,QAAI,CAAC,MAAM;AAAO;AAElB;AAAA,MACE;AAAA,QACE,MAAM;AAAA,QACN,SAAS,MAAM;AAAA,QACf,OAAO,CAAC;AAAA,MACV;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,SAAS,eAAe;AAAA,IAClC,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["generateId","fetch","_a","_b","data","swrv","ref","unref","useSWRV","store","fetch","data","_a","completion","computed","ref","messages","_a"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/use-completion.ts"],"sourcesContent":["import type {\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { computed, ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<UIMessage[]>;\n /** The error object of the API request */\n error: Ref<undefined | Error>;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: Message[] | ((messages: Message[]) => Message[]),\n ) => void;\n /** The current value of the input */\n input: Ref<string>;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: Ref<boolean>;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: Ref<'submitted' | 'streaming' | 'ready' | 'error'>;\n\n /** Additional data added on the server via StreamData. */\n data: Ref<JSONValue[] | undefined>;\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n\n /** The id of the chat */\n id: string;\n};\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, UIMessage[] | undefined> = {};\n\nexport function useChat(\n {\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers: metadataHeaders,\n body: metadataBody,\n generateId = generateIdFunc,\n onToolCall,\n fetch,\n keepLastMessageOnError = true,\n maxSteps = 1,\n experimental_prepareRequestBody,\n }: UseChatOptions & {\n /**\n * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.\n * A maximum number is required to prevent infinite loops in the case of misconfigured tools.\n * By default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n\n /**\n * Experimental (Vue only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param id The chat ID\n * @param messages The current messages in the chat\n * @param requestData The data object passed in the chat request\n * @param requestBody The request body object passed in the chat request\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\n } = {\n maxSteps: 1,\n },\n): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id ?? generateId();\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<UIMessage[]>(\n key,\n () => store[key] ?? fillMessageParts(initialMessages),\n );\n\n const { data: status, mutate: mutateStatus } = useSWRV<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >(`${chatId}-status`, null);\n\n status.value ??= 'ready';\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= fillMessageParts(initialMessages);\n\n const mutate = (data?: UIMessage[]) => {\n store[key] = data;\n return originalMutate();\n };\n\n // Because of the `initialData` option, the `data` will never be `undefined`.\n const messages = messagesData as Ref<UIMessage[]>;\n\n const error = ref<undefined | Error>(undefined);\n // cannot use JSONValue[] in ref because of infinite Typescript recursion:\n const streamData = ref<undefined | unknown[]>(undefined);\n\n let abortController: AbortController | null = null;\n\n async function triggerRequest(\n messagesSnapshot: Message[],\n { data, headers, body }: ChatRequestOptions = {},\n ) {\n error.value = undefined;\n mutateStatus(() => 'submitted');\n\n const messageCount = messages.value.length;\n const maxStep = extractMaxToolInvocationStep(\n messages.value[messages.value.length - 1]?.toolInvocations,\n );\n\n try {\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = fillMessageParts(messagesSnapshot);\n const chatMessages = previousMessages;\n mutate(chatMessages);\n\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: data,\n requestBody: body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data,\n ...unref(metadataBody), // Use unref to unwrap the ref value\n ...body,\n },\n streamProtocol,\n headers: {\n ...metadataHeaders,\n ...headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus(() => 'streaming');\n\n mutate([\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ]);\n if (data?.length) {\n streamData.value = [...existingData, ...data];\n }\n },\n onFinish,\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n generateId,\n onToolCall,\n fetch,\n // enabled use of structured clone in processChatResponse:\n lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1]),\n });\n\n mutateStatus(() => 'ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n mutateStatus(() => 'ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n mutateStatus(() => 'error');\n } finally {\n abortController = null;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages: messages.value,\n })\n ) {\n await triggerRequest(messages.value);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options?.experimental_attachments,\n );\n\n return triggerRequest(\n messages.value.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n }),\n options,\n );\n };\n\n const reload: UseChatHelpers['reload'] = async options => {\n const messagesSnapshot = messages.value;\n if (messagesSnapshot.length === 0) return null;\n\n const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];\n if (lastMessage.role === 'assistant') {\n return triggerRequest(messagesSnapshot.slice(0, -1), options);\n }\n\n return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (\n messagesArg: Message[] | ((messages: Message[]) => Message[]),\n ) => {\n if (typeof messagesArg === 'function') {\n messagesArg = messagesArg(messages.value);\n }\n\n mutate(fillMessageParts(messagesArg));\n };\n\n const setData = (\n dataArg:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof dataArg === 'function') {\n dataArg = dataArg(streamData.value as JSONValue[] | undefined);\n }\n\n streamData.value = dataArg;\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n if (!inputValue && !options.allowEmptySubmit) return;\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n triggerRequest(\n messages.value.concat({\n id: generateId(),\n createdAt: new Date(),\n content: inputValue,\n role: 'user',\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: inputValue }],\n }),\n options,\n );\n\n input.value = '';\n };\n\n const addToolResult = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: unknown;\n }) => {\n const currentMessages = messages.value;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n mutate(currentMessages);\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status.value === 'submitted' || status.value === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest(currentMessages);\n }\n };\n\n return {\n id: chatId,\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading: computed(\n () => status.value === 'submitted' || status.value === 'streaming',\n ),\n status: status as Ref<'submitted' | 'streaming' | 'ready' | 'error'>,\n data: streamData as Ref<undefined | JSONValue[]>,\n setData,\n addToolResult,\n };\n}\n\n// required for use of structured clone\nfunction recursiveToRaw<T>(inputValue: T): T {\n if (Array.isArray(inputValue)) {\n return [...inputValue.map(recursiveToRaw)] as T;\n } else if (typeof inputValue === 'object' && inputValue !== null) {\n const clone: any = {};\n for (const [key, value] of Object.entries(inputValue)) {\n clone[key] = recursiveToRaw(value);\n }\n return clone;\n } else {\n return inputValue;\n }\n}\n","import type {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n} from '@ai-sdk/ui-utils';\nimport { callCompletionApi } from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data: Ref<JSONValue[] | 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 onResponse,\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 const { data: streamData, mutate: mutateStreamData } = useSWRV<\n JSONValue[] | undefined\n >(`${completionId}-data`, null);\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(prompt: string, options?: RequestOptions) {\n const existingData = (streamData.value ?? []) as JSONValue[];\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 onResponse,\n onFinish,\n onError,\n onData: data => {\n mutateStreamData(() => [...existingData, ...(data ?? [])]);\n },\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 data: streamData,\n };\n}\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,UAAU;AAEjB,SAAS,UAAU,KAAK,aAAa;AAqFrC,IAAM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ACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,CAAAG,UAAQ;AACd,yBAAiB,MAAM,CAAC,GAAG,cAAc,GAAIA,SAAA,OAAAA,QAAQ,CAAC,CAAE,CAAC;AAAA,MAC3D;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA6C,OACjD,QACA,YACG;AACH,WAAO,eAAe,QAAQ,OAAO;AAAA,EACvC;AAEA,QAAM,OAAO,MAAM;AACjB,QAAI,iBAAiB;AACnB,sBAAgB,MAAM;AACtB,wBAAkB;AAAA,IACpB;AAAA,EACF;AAEA,QAAM,gBAAgB,CAACE,gBAAuB;AAC5C,WAAOA,WAAU;AAAA,EACnB;AAEA,QAAM,QAAQN,KAAI,YAAY;AAE9B,QAAM,eAAe,CAAC,UAA4C;AA/JpE,QAAAK;AAgKI,KAAAA,MAAA,+BAAO,mBAAP,gBAAAA,IAAA;AACA,UAAM,aAAa,MAAM;AACzB,WAAO,aAAa,SAAS,UAAU,IAAI;AAAA,EAC7C;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR;AACF;","names":["_a","_b","data","swrv","ref","unref","useSWRV","store","data","_a","completion"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/vue",
3
- "version": "1.2.3",
3
+ "version": "2.0.0-canary.0",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -19,8 +19,8 @@
19
19
  "CHANGELOG.md"
20
20
  ],
21
21
  "dependencies": {
22
- "@ai-sdk/provider-utils": "2.2.2",
23
- "@ai-sdk/ui-utils": "1.2.3",
22
+ "@ai-sdk/provider-utils": "3.0.0-canary.0",
23
+ "@ai-sdk/ui-utils": "2.0.0-canary.0",
24
24
  "swrv": "^1.0.4"
25
25
  },
26
26
  "devDependencies": {