@ai-sdk/vue 1.2.11 → 2.0.0-alpha.1

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/dist/index.js CHANGED
@@ -30,107 +30,73 @@ 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
  });
37
36
  module.exports = __toCommonJS(src_exports);
38
37
 
39
38
  // src/use-chat.ts
40
- var import_ui_utils = require("@ai-sdk/ui-utils");
39
+ var import_ai = require("ai");
41
40
  var import_swrv = __toESM(require("swrv"));
42
41
  var import_vue = require("vue");
43
42
  var useSWRV = import_swrv.default.default || import_swrv.default;
44
43
  var store = {};
44
+ var statusStore = {};
45
45
  function useChat({
46
46
  api = "/api/chat",
47
- id,
47
+ chatId,
48
48
  initialMessages = [],
49
49
  initialInput = "",
50
- sendExtraMessageFields,
51
- streamProtocol = "data",
52
- onResponse,
50
+ streamProtocol = "ui-message",
53
51
  onFinish,
54
52
  onError,
55
53
  credentials,
56
54
  headers: metadataHeaders,
57
55
  body: metadataBody,
58
- generateId: generateId2 = import_ui_utils.generateId,
56
+ generateId = import_ai.generateId,
59
57
  onToolCall,
60
- fetch: fetch2,
61
- keepLastMessageOnError = true,
58
+ fetch,
62
59
  maxSteps = 1,
63
- experimental_prepareRequestBody
60
+ experimental_prepareRequestBody,
61
+ messageMetadataSchema
64
62
  } = {
65
63
  maxSteps: 1
66
64
  }) {
67
65
  var _a, _b;
68
- const chatId = id != null ? id : generateId2();
69
- const key = `${api}|${chatId}`;
70
- const { data: messagesData, mutate: originalMutate } = useSWRV(
71
- key,
72
- () => {
73
- var _a2;
74
- return (_a2 = store[key]) != null ? _a2 : (0, import_ui_utils.fillMessageParts)(initialMessages);
75
- }
76
- );
77
- const { data: status, mutate: mutateStatus } = useSWRV(`${chatId}-status`, null);
78
- (_a = status.value) != null ? _a : status.value = "ready";
79
- (_b = messagesData.value) != null ? _b : messagesData.value = (0, import_ui_utils.fillMessageParts)(initialMessages);
66
+ const stableChatId = chatId != null ? chatId : generateId();
67
+ const key = `${api}|${stableChatId}`;
68
+ const { data: messagesData, mutate: originalMutate } = useSWRV(key, () => {
69
+ var _a2;
70
+ return (_a2 = store[key]) != null ? _a2 : initialMessages;
71
+ });
72
+ const status = (_a = statusStore[stableChatId]) != null ? _a : statusStore[stableChatId] = (0, import_vue.ref)("ready");
73
+ (_b = messagesData.value) != null ? _b : messagesData.value = initialMessages;
80
74
  const mutate = (data) => {
81
75
  store[key] = data;
82
76
  return originalMutate();
83
77
  };
84
78
  const messages = messagesData;
85
79
  const error = (0, import_vue.ref)(void 0);
86
- const streamData = (0, import_vue.ref)(void 0);
87
80
  let abortController = null;
88
- async function triggerRequest(messagesSnapshot, { data, headers, body } = {}) {
89
- var _a2, _b2, _c;
81
+ async function triggerRequest(messagesSnapshot, { headers, body } = {}) {
82
+ var _a2;
90
83
  error.value = void 0;
91
- mutateStatus(() => "submitted");
84
+ status.value = "submitted";
92
85
  const messageCount = messages.value.length;
93
- const maxStep = (0, import_ui_utils.extractMaxToolInvocationStep)(
94
- (_a2 = messages.value[messages.value.length - 1]) == null ? void 0 : _a2.toolInvocations
95
- );
86
+ const lastMessage = messages.value.at(-1);
87
+ const maxStep = lastMessage != null ? (0, import_ai.extractMaxToolInvocationStep)((0, import_ai.getToolInvocations)(lastMessage)) : 0;
96
88
  try {
97
89
  abortController = new AbortController();
98
- const previousMessages = (0, import_ui_utils.fillMessageParts)(messagesSnapshot);
99
- const chatMessages = previousMessages;
100
- mutate(chatMessages);
101
- const existingData = (_b2 = streamData.value) != null ? _b2 : [];
102
- const constructedMessagesPayload = sendExtraMessageFields ? chatMessages : chatMessages.map(
103
- ({
104
- role,
105
- content,
106
- experimental_attachments,
107
- data: data2,
108
- annotations,
109
- toolInvocations,
110
- parts
111
- }) => ({
112
- role,
113
- content,
114
- ...experimental_attachments !== void 0 && {
115
- experimental_attachments
116
- },
117
- ...data2 !== void 0 && { data: data2 },
118
- ...annotations !== void 0 && { annotations },
119
- ...toolInvocations !== void 0 && { toolInvocations },
120
- ...parts !== void 0 && { parts }
121
- })
122
- );
123
- await (0, import_ui_utils.callChatApi)({
90
+ mutate(messagesSnapshot);
91
+ await (0, import_ai.callChatApi)({
124
92
  api,
125
- body: (_c = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
126
- id: chatId,
127
- messages: chatMessages,
128
- requestData: data,
93
+ body: (_a2 = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
94
+ chatId: stableChatId,
95
+ messages: messagesSnapshot,
129
96
  requestBody: body
130
- })) != null ? _c : {
131
- id: chatId,
132
- messages: constructedMessagesPayload,
133
- data,
97
+ })) != null ? _a2 : {
98
+ chatId: stableChatId,
99
+ messages: messagesSnapshot,
134
100
  ...(0, import_vue.unref)(metadataBody),
135
101
  // Use unref to unwrap the ref value
136
102
  ...body
@@ -142,45 +108,40 @@ function useChat({
142
108
  },
143
109
  abortController: () => abortController,
144
110
  credentials,
145
- onResponse,
146
- onUpdate({ message, data: data2, replaceLastMessage }) {
147
- mutateStatus(() => "streaming");
111
+ onUpdate({ message }) {
112
+ status.value = "streaming";
113
+ const replaceLastMessage = message.id === messagesSnapshot[messagesSnapshot.length - 1].id;
148
114
  mutate([
149
- ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
115
+ ...replaceLastMessage ? messagesSnapshot.slice(0, messagesSnapshot.length - 1) : messagesSnapshot,
150
116
  message
151
117
  ]);
152
- if (data2 == null ? void 0 : data2.length) {
153
- streamData.value = [...existingData, ...data2];
154
- }
155
118
  },
156
119
  onFinish,
157
- restoreMessagesOnFailure() {
158
- if (!keepLastMessageOnError) {
159
- mutate(previousMessages);
160
- }
161
- },
162
- generateId: generateId2,
120
+ generateId,
163
121
  onToolCall,
164
- fetch: fetch2,
122
+ fetch,
165
123
  // enabled use of structured clone in processChatResponse:
166
- lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1])
124
+ lastMessage: recursiveToRaw(
125
+ messagesSnapshot[messagesSnapshot.length - 1]
126
+ ),
127
+ messageMetadataSchema
167
128
  });
168
- mutateStatus(() => "ready");
129
+ status.value = "ready";
169
130
  } catch (err) {
170
131
  if (err.name === "AbortError") {
171
132
  abortController = null;
172
- mutateStatus(() => "ready");
133
+ status.value = "ready";
173
134
  return null;
174
135
  }
175
136
  if (onError && err instanceof Error) {
176
137
  onError(err);
177
138
  }
178
139
  error.value = err;
179
- mutateStatus(() => "error");
140
+ status.value = "error";
180
141
  } finally {
181
142
  abortController = null;
182
143
  }
183
- if ((0, import_ui_utils.shouldResubmitMessages)({
144
+ if ((0, import_ai.shouldResubmitMessages)({
184
145
  originalMaxToolInvocationStep: maxStep,
185
146
  originalMessageCount: messageCount,
186
147
  maxSteps,
@@ -190,17 +151,12 @@ function useChat({
190
151
  }
191
152
  }
192
153
  const append = async (message, options) => {
193
- var _a2, _b2, _c;
194
- const attachmentsForRequest = await (0, import_ui_utils.prepareAttachmentsForRequest)(
195
- (_a2 = options == null ? void 0 : options.experimental_attachments) != null ? _a2 : message.experimental_attachments
196
- );
154
+ var _a2;
197
155
  return triggerRequest(
198
156
  messages.value.concat({
199
157
  ...message,
200
- id: (_b2 = message.id) != null ? _b2 : generateId2(),
201
- createdAt: (_c = message.createdAt) != null ? _c : /* @__PURE__ */ new Date(),
202
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
203
- parts: (0, import_ui_utils.getMessageParts)(message)
158
+ id: (_a2 = message.id) != null ? _a2 : generateId(),
159
+ parts: message.parts
204
160
  }),
205
161
  options
206
162
  );
@@ -225,32 +181,21 @@ function useChat({
225
181
  if (typeof messagesArg === "function") {
226
182
  messagesArg = messagesArg(messages.value);
227
183
  }
228
- mutate((0, import_ui_utils.fillMessageParts)(messagesArg));
229
- };
230
- const setData = (dataArg) => {
231
- if (typeof dataArg === "function") {
232
- dataArg = dataArg(streamData.value);
233
- }
234
- streamData.value = dataArg;
184
+ mutate(messagesArg);
235
185
  };
236
186
  const input = (0, import_vue.ref)(initialInput);
237
187
  const handleSubmit = async (event, options = {}) => {
238
188
  var _a2;
239
189
  (_a2 = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a2.call(event);
240
190
  const inputValue = input.value;
241
- if (!inputValue && !options.allowEmptySubmit)
191
+ const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await (0, import_ai.convertFileListToFileUIParts)(options == null ? void 0 : options.files);
192
+ if (!inputValue && fileParts.length === 0)
242
193
  return;
243
- const attachmentsForRequest = await (0, import_ui_utils.prepareAttachmentsForRequest)(
244
- options.experimental_attachments
245
- );
246
194
  triggerRequest(
247
195
  messages.value.concat({
248
- id: generateId2(),
249
- createdAt: /* @__PURE__ */ new Date(),
250
- content: inputValue,
196
+ id: generateId(),
251
197
  role: "user",
252
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
253
- parts: [{ type: "text", text: inputValue }]
198
+ parts: [...fileParts, { type: "text", text: inputValue }]
254
199
  }),
255
200
  options
256
201
  );
@@ -261,7 +206,7 @@ function useChat({
261
206
  result
262
207
  }) => {
263
208
  const currentMessages = messages.value;
264
- (0, import_ui_utils.updateToolCallResult)({
209
+ (0, import_ai.updateToolCallResult)({
265
210
  messages: currentMessages,
266
211
  toolCallId,
267
212
  toolResult: result
@@ -271,12 +216,12 @@ function useChat({
271
216
  return;
272
217
  }
273
218
  const lastMessage = currentMessages[currentMessages.length - 1];
274
- if ((0, import_ui_utils.isAssistantMessageWithCompletedToolCalls)(lastMessage)) {
219
+ if ((0, import_ai.isAssistantMessageWithCompletedToolCalls)(lastMessage)) {
275
220
  triggerRequest(currentMessages);
276
221
  }
277
222
  };
278
223
  return {
279
- id: chatId,
224
+ chatId: stableChatId,
280
225
  messages,
281
226
  append,
282
227
  error,
@@ -285,12 +230,7 @@ function useChat({
285
230
  setMessages,
286
231
  input,
287
232
  handleSubmit,
288
- isLoading: (0, import_vue.computed)(
289
- () => status.value === "submitted" || status.value === "streaming"
290
- ),
291
233
  status,
292
- data: streamData,
293
- setData,
294
234
  addToolResult
295
235
  };
296
236
  }
@@ -309,7 +249,7 @@ function recursiveToRaw(inputValue) {
309
249
  }
310
250
 
311
251
  // src/use-completion.ts
312
- var import_ui_utils2 = require("@ai-sdk/ui-utils");
252
+ var import_ai2 = require("ai");
313
253
  var import_swrv2 = __toESM(require("swrv"));
314
254
  var import_vue2 = require("vue");
315
255
  var uniqueId = 0;
@@ -324,10 +264,9 @@ function useCompletion({
324
264
  headers,
325
265
  body,
326
266
  streamProtocol,
327
- onResponse,
328
267
  onFinish,
329
268
  onError,
330
- fetch: fetch2
269
+ fetch
331
270
  } = {}) {
332
271
  var _a;
333
272
  const completionId = id || `completion-${uniqueId++}`;
@@ -341,7 +280,6 @@ function useCompletion({
341
280
  null
342
281
  );
343
282
  (_a = isLoading.value) != null ? _a : isLoading.value = false;
344
- const { data: streamData, mutate: mutateStreamData } = useSWRV2(`${completionId}-data`, null);
345
283
  data.value || (data.value = initialCompletion);
346
284
  const mutate = (data2) => {
347
285
  store2[key] = data2;
@@ -351,9 +289,7 @@ function useCompletion({
351
289
  const error = (0, import_vue2.ref)(void 0);
352
290
  let abortController = null;
353
291
  async function triggerRequest(prompt, options) {
354
- var _a2;
355
- const existingData = (_a2 = streamData.value) != null ? _a2 : [];
356
- return (0, import_ui_utils2.callCompletionApi)({
292
+ return (0, import_ai2.callCompletionApi)({
357
293
  api,
358
294
  prompt,
359
295
  credentials,
@@ -374,13 +310,9 @@ function useCompletion({
374
310
  setAbortController: (controller) => {
375
311
  abortController = controller;
376
312
  },
377
- onResponse,
378
313
  onFinish,
379
314
  onError,
380
- onData: (data2) => {
381
- mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
382
- },
383
- fetch: fetch2
315
+ fetch
384
316
  });
385
317
  }
386
318
  const complete = async (prompt, options) => {
@@ -410,182 +342,11 @@ function useCompletion({
410
342
  setCompletion,
411
343
  input,
412
344
  handleSubmit,
413
- isLoading,
414
- data: streamData
415
- };
416
- }
417
-
418
- // src/use-assistant.ts
419
- var import_provider_utils = require("@ai-sdk/provider-utils");
420
- var import_ui_utils3 = require("@ai-sdk/ui-utils");
421
- var import_vue3 = require("vue");
422
- function useAssistant({
423
- api,
424
- threadId: threadIdParam,
425
- credentials,
426
- headers,
427
- body,
428
- onError
429
- }) {
430
- const messages = (0, import_vue3.ref)([]);
431
- const input = (0, import_vue3.ref)("");
432
- const currentThreadId = (0, import_vue3.ref)(void 0);
433
- const status = (0, import_vue3.ref)("awaiting_message");
434
- const error = (0, import_vue3.ref)(void 0);
435
- const setMessages = (messageFactory) => {
436
- messages.value = messageFactory(messages.value);
437
- };
438
- const setCurrentThreadId = (newThreadId) => {
439
- currentThreadId.value = newThreadId;
440
- messages.value = [];
441
- };
442
- const handleInputChange = (event) => {
443
- var _a;
444
- input.value = (_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value;
445
- };
446
- const isSending = (0, import_vue3.computed)(() => status.value === "in_progress");
447
- const abortController = (0, import_vue3.ref)(null);
448
- const stop = (0, import_vue3.computed)(() => {
449
- return () => {
450
- if (abortController.value) {
451
- abortController.value.abort();
452
- abortController.value = null;
453
- }
454
- };
455
- });
456
- const append = async (message, requestOptions) => {
457
- var _a, _b, _c, _d;
458
- status.value = "in_progress";
459
- const newMessage = {
460
- ...message,
461
- id: (_a = message.id) != null ? _a : (0, import_ui_utils3.generateId)()
462
- };
463
- setMessages((messages2) => [...messages2, newMessage]);
464
- input.value = "";
465
- const controller = new AbortController();
466
- try {
467
- abortController.value = controller;
468
- const response = await fetch(api, {
469
- method: "POST",
470
- headers: {
471
- "Content-Type": "application/json",
472
- ...headers
473
- },
474
- body: JSON.stringify({
475
- ...body,
476
- // Message Content
477
- message: message.content,
478
- // Always Use User Provided Thread ID When Available
479
- threadId: (_b = threadIdParam != null ? threadIdParam : currentThreadId.value) != null ? _b : null,
480
- // Optional Request Data
481
- ...(requestOptions == null ? void 0 : requestOptions.data) && { data: requestOptions == null ? void 0 : requestOptions.data }
482
- }),
483
- signal: controller.signal,
484
- credentials
485
- });
486
- if (!response.ok) {
487
- throw new Error(
488
- (_c = response.statusText) != null ? _c : "An error occurred while sending the message"
489
- );
490
- }
491
- if (!response.body) {
492
- throw new Error("The response body is empty");
493
- }
494
- await (0, import_ui_utils3.processAssistantStream)({
495
- stream: response.body,
496
- onAssistantMessagePart(value) {
497
- messages.value = [
498
- ...messages.value,
499
- {
500
- id: value.id,
501
- content: value.content[0].text.value,
502
- role: value.role,
503
- parts: []
504
- }
505
- ];
506
- },
507
- onTextPart(value) {
508
- setMessages((messages2) => {
509
- const lastMessage = messages2[messages2.length - 1];
510
- lastMessage.content += value;
511
- return [...messages2.slice(0, -1), lastMessage];
512
- });
513
- },
514
- onAssistantControlDataPart(value) {
515
- if (value.threadId) {
516
- currentThreadId.value = value.threadId;
517
- }
518
- setMessages((messages2) => {
519
- const lastMessage = messages2[messages2.length - 1];
520
- lastMessage.id = value.messageId;
521
- return [...messages2.slice(0, -1), lastMessage];
522
- });
523
- },
524
- onDataMessagePart(value) {
525
- setMessages((messages2) => {
526
- var _a2;
527
- return [
528
- ...messages2,
529
- {
530
- id: (_a2 = value.id) != null ? _a2 : (0, import_ui_utils3.generateId)(),
531
- role: "data",
532
- content: "",
533
- data: value.data,
534
- parts: []
535
- }
536
- ];
537
- });
538
- },
539
- onErrorPart(value) {
540
- error.value = new Error(value);
541
- }
542
- });
543
- } catch (err) {
544
- if ((0, import_provider_utils.isAbortError)(err) && ((_d = abortController.value) == null ? void 0 : _d.signal.aborted)) {
545
- abortController.value = null;
546
- return;
547
- }
548
- if (onError && err instanceof Error) {
549
- onError(err);
550
- }
551
- error.value = err;
552
- } finally {
553
- abortController.value = null;
554
- status.value = "awaiting_message";
555
- }
556
- };
557
- const submitMessage = async (event, requestOptions) => {
558
- var _a;
559
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
560
- if (!input.value)
561
- return;
562
- append(
563
- {
564
- role: "user",
565
- content: input.value,
566
- parts: []
567
- },
568
- requestOptions
569
- );
570
- };
571
- return {
572
- append,
573
- messages,
574
- setMessages,
575
- threadId: (0, import_vue3.readonly)(currentThreadId),
576
- setThreadId: setCurrentThreadId,
577
- input,
578
- handleInputChange,
579
- handleSubmit: submitMessage,
580
- isSending,
581
- status,
582
- error,
583
- stop
345
+ isLoading
584
346
  };
585
347
  }
586
348
  // Annotate the CommonJS export names for ESM import in node:
587
349
  0 && (module.exports = {
588
- useAssistant,
589
350
  useChat,
590
351
  useCompletion
591
352
  });