@ai-sdk/vue 1.2.12 → 2.0.0-alpha.10

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.mjs CHANGED
@@ -1,294 +1,10 @@
1
- // src/use-chat.ts
2
- import {
3
- callChatApi,
4
- extractMaxToolInvocationStep,
5
- fillMessageParts,
6
- generateId as generateIdFunc,
7
- getMessageParts,
8
- isAssistantMessageWithCompletedToolCalls,
9
- prepareAttachmentsForRequest,
10
- shouldResubmitMessages,
11
- updateToolCallResult
12
- } from "@ai-sdk/ui-utils";
1
+ // src/use-completion.ts
2
+ import { callCompletionApi } from "ai";
13
3
  import swrv from "swrv";
14
- import { computed, ref, unref } from "vue";
4
+ import { ref, unref } from "vue";
5
+ var uniqueId = 0;
15
6
  var useSWRV = swrv.default || swrv;
16
7
  var store = {};
17
- var statusStore = {};
18
- function useChat({
19
- api = "/api/chat",
20
- id,
21
- initialMessages = [],
22
- initialInput = "",
23
- sendExtraMessageFields,
24
- streamProtocol = "data",
25
- onResponse,
26
- onFinish,
27
- onError,
28
- credentials,
29
- headers: metadataHeaders,
30
- body: metadataBody,
31
- generateId: generateId2 = generateIdFunc,
32
- onToolCall,
33
- fetch: fetch2,
34
- keepLastMessageOnError = true,
35
- maxSteps = 1,
36
- experimental_prepareRequestBody
37
- } = {
38
- maxSteps: 1
39
- }) {
40
- var _a, _b;
41
- const chatId = id != null ? id : generateId2();
42
- const key = `${api}|${chatId}`;
43
- const { data: messagesData, mutate: originalMutate } = useSWRV(
44
- key,
45
- () => {
46
- var _a2;
47
- return (_a2 = store[key]) != null ? _a2 : fillMessageParts(initialMessages);
48
- }
49
- );
50
- const status = (_a = statusStore[chatId]) != null ? _a : statusStore[chatId] = ref(
51
- "ready"
52
- );
53
- (_b = messagesData.value) != null ? _b : messagesData.value = fillMessageParts(initialMessages);
54
- const mutate = (data) => {
55
- store[key] = data;
56
- return originalMutate();
57
- };
58
- const messages = messagesData;
59
- const error = ref(void 0);
60
- const streamData = ref(void 0);
61
- let abortController = null;
62
- async function triggerRequest(messagesSnapshot, { data, headers, body } = {}) {
63
- var _a2, _b2, _c;
64
- error.value = void 0;
65
- status.value = "submitted";
66
- const messageCount = messages.value.length;
67
- const maxStep = extractMaxToolInvocationStep(
68
- (_a2 = messages.value[messages.value.length - 1]) == null ? void 0 : _a2.toolInvocations
69
- );
70
- try {
71
- abortController = new AbortController();
72
- const previousMessages = fillMessageParts(messagesSnapshot);
73
- const chatMessages = previousMessages;
74
- mutate(chatMessages);
75
- const existingData = (_b2 = streamData.value) != null ? _b2 : [];
76
- const constructedMessagesPayload = sendExtraMessageFields ? chatMessages : chatMessages.map(
77
- ({
78
- role,
79
- content,
80
- experimental_attachments,
81
- data: data2,
82
- annotations,
83
- toolInvocations,
84
- parts
85
- }) => ({
86
- role,
87
- content,
88
- ...experimental_attachments !== void 0 && {
89
- experimental_attachments
90
- },
91
- ...data2 !== void 0 && { data: data2 },
92
- ...annotations !== void 0 && { annotations },
93
- ...toolInvocations !== void 0 && { toolInvocations },
94
- ...parts !== void 0 && { parts }
95
- })
96
- );
97
- await callChatApi({
98
- api,
99
- body: (_c = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
100
- id: chatId,
101
- messages: chatMessages,
102
- requestData: data,
103
- requestBody: body
104
- })) != null ? _c : {
105
- id: chatId,
106
- messages: constructedMessagesPayload,
107
- data,
108
- ...unref(metadataBody),
109
- // Use unref to unwrap the ref value
110
- ...body
111
- },
112
- streamProtocol,
113
- headers: {
114
- ...metadataHeaders,
115
- ...headers
116
- },
117
- abortController: () => abortController,
118
- credentials,
119
- onResponse,
120
- onUpdate({ message, data: data2, replaceLastMessage }) {
121
- status.value = "streaming";
122
- mutate([
123
- ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
124
- message
125
- ]);
126
- if (data2 == null ? void 0 : data2.length) {
127
- streamData.value = [...existingData, ...data2];
128
- }
129
- },
130
- onFinish,
131
- restoreMessagesOnFailure() {
132
- if (!keepLastMessageOnError) {
133
- mutate(previousMessages);
134
- }
135
- },
136
- generateId: generateId2,
137
- onToolCall,
138
- fetch: fetch2,
139
- // enabled use of structured clone in processChatResponse:
140
- lastMessage: recursiveToRaw(chatMessages[chatMessages.length - 1])
141
- });
142
- status.value = "ready";
143
- } catch (err) {
144
- if (err.name === "AbortError") {
145
- abortController = null;
146
- status.value = "ready";
147
- return null;
148
- }
149
- if (onError && err instanceof Error) {
150
- onError(err);
151
- }
152
- error.value = err;
153
- status.value = "error";
154
- } finally {
155
- abortController = null;
156
- }
157
- if (shouldResubmitMessages({
158
- originalMaxToolInvocationStep: maxStep,
159
- originalMessageCount: messageCount,
160
- maxSteps,
161
- messages: messages.value
162
- })) {
163
- await triggerRequest(messages.value);
164
- }
165
- }
166
- const append = async (message, options) => {
167
- var _a2, _b2, _c;
168
- const attachmentsForRequest = await prepareAttachmentsForRequest(
169
- (_a2 = options == null ? void 0 : options.experimental_attachments) != null ? _a2 : message.experimental_attachments
170
- );
171
- return triggerRequest(
172
- messages.value.concat({
173
- ...message,
174
- id: (_b2 = message.id) != null ? _b2 : generateId2(),
175
- createdAt: (_c = message.createdAt) != null ? _c : /* @__PURE__ */ new Date(),
176
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
177
- parts: getMessageParts(message)
178
- }),
179
- options
180
- );
181
- };
182
- const reload = async (options) => {
183
- const messagesSnapshot = messages.value;
184
- if (messagesSnapshot.length === 0)
185
- return null;
186
- const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
187
- if (lastMessage.role === "assistant") {
188
- return triggerRequest(messagesSnapshot.slice(0, -1), options);
189
- }
190
- return triggerRequest(messagesSnapshot, options);
191
- };
192
- const stop = () => {
193
- if (abortController) {
194
- abortController.abort();
195
- abortController = null;
196
- }
197
- };
198
- const setMessages = (messagesArg) => {
199
- if (typeof messagesArg === "function") {
200
- messagesArg = messagesArg(messages.value);
201
- }
202
- mutate(fillMessageParts(messagesArg));
203
- };
204
- const setData = (dataArg) => {
205
- if (typeof dataArg === "function") {
206
- dataArg = dataArg(streamData.value);
207
- }
208
- streamData.value = dataArg;
209
- };
210
- const input = ref(initialInput);
211
- const handleSubmit = async (event, options = {}) => {
212
- var _a2;
213
- (_a2 = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a2.call(event);
214
- const inputValue = input.value;
215
- if (!inputValue && !options.allowEmptySubmit)
216
- return;
217
- const attachmentsForRequest = await prepareAttachmentsForRequest(
218
- options.experimental_attachments
219
- );
220
- triggerRequest(
221
- messages.value.concat({
222
- id: generateId2(),
223
- createdAt: /* @__PURE__ */ new Date(),
224
- content: inputValue,
225
- role: "user",
226
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
227
- parts: [{ type: "text", text: inputValue }]
228
- }),
229
- options
230
- );
231
- input.value = "";
232
- };
233
- const addToolResult = ({
234
- toolCallId,
235
- result
236
- }) => {
237
- const currentMessages = messages.value;
238
- updateToolCallResult({
239
- messages: currentMessages,
240
- toolCallId,
241
- toolResult: result
242
- });
243
- mutate(currentMessages);
244
- if (status.value === "submitted" || status.value === "streaming") {
245
- return;
246
- }
247
- const lastMessage = currentMessages[currentMessages.length - 1];
248
- if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
249
- triggerRequest(currentMessages);
250
- }
251
- };
252
- return {
253
- id: chatId,
254
- messages,
255
- append,
256
- error,
257
- reload,
258
- stop,
259
- setMessages,
260
- input,
261
- handleSubmit,
262
- isLoading: computed(
263
- () => status.value === "submitted" || status.value === "streaming"
264
- ),
265
- status,
266
- data: streamData,
267
- setData,
268
- addToolResult
269
- };
270
- }
271
- function recursiveToRaw(inputValue) {
272
- if (Array.isArray(inputValue)) {
273
- return [...inputValue.map(recursiveToRaw)];
274
- } else if (typeof inputValue === "object" && inputValue !== null) {
275
- const clone = {};
276
- for (const [key, value] of Object.entries(inputValue)) {
277
- clone[key] = recursiveToRaw(value);
278
- }
279
- return clone;
280
- } else {
281
- return inputValue;
282
- }
283
- }
284
-
285
- // src/use-completion.ts
286
- import { callCompletionApi } from "@ai-sdk/ui-utils";
287
- import swrv2 from "swrv";
288
- import { ref as ref2, unref as unref2 } from "vue";
289
- var uniqueId = 0;
290
- var useSWRV2 = swrv2.default || swrv2;
291
- var store2 = {};
292
8
  function useCompletion({
293
9
  api = "/api/completion",
294
10
  id,
@@ -298,35 +14,31 @@ function useCompletion({
298
14
  headers,
299
15
  body,
300
16
  streamProtocol,
301
- onResponse,
302
17
  onFinish,
303
18
  onError,
304
- fetch: fetch2
19
+ fetch
305
20
  } = {}) {
306
21
  var _a;
307
22
  const completionId = id || `completion-${uniqueId++}`;
308
23
  const key = `${api}|${completionId}`;
309
- const { data, mutate: originalMutate } = useSWRV2(
24
+ const { data, mutate: originalMutate } = useSWRV(
310
25
  key,
311
- () => store2[key] || initialCompletion
26
+ () => store[key] || initialCompletion
312
27
  );
313
- const { data: isLoading, mutate: mutateLoading } = useSWRV2(
28
+ const { data: isLoading, mutate: mutateLoading } = useSWRV(
314
29
  `${completionId}-loading`,
315
30
  null
316
31
  );
317
32
  (_a = isLoading.value) != null ? _a : isLoading.value = false;
318
- const { data: streamData, mutate: mutateStreamData } = useSWRV2(`${completionId}-data`, null);
319
33
  data.value || (data.value = initialCompletion);
320
34
  const mutate = (data2) => {
321
- store2[key] = data2;
35
+ store[key] = data2;
322
36
  return originalMutate();
323
37
  };
324
38
  const completion = data;
325
- const error = ref2(void 0);
39
+ const error = ref(void 0);
326
40
  let abortController = null;
327
41
  async function triggerRequest(prompt, options) {
328
- var _a2;
329
- const existingData = (_a2 = streamData.value) != null ? _a2 : [];
330
42
  return callCompletionApi({
331
43
  api,
332
44
  prompt,
@@ -336,7 +48,7 @@ function useCompletion({
336
48
  ...options == null ? void 0 : options.headers
337
49
  },
338
50
  body: {
339
- ...unref2(body),
51
+ ...unref(body),
340
52
  ...options == null ? void 0 : options.body
341
53
  },
342
54
  streamProtocol,
@@ -348,13 +60,9 @@ function useCompletion({
348
60
  setAbortController: (controller) => {
349
61
  abortController = controller;
350
62
  },
351
- onResponse,
352
63
  onFinish,
353
64
  onError,
354
- onData: (data2) => {
355
- mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
356
- },
357
- fetch: fetch2
65
+ fetch
358
66
  });
359
67
  }
360
68
  const complete = async (prompt, options) => {
@@ -369,7 +77,7 @@ function useCompletion({
369
77
  const setCompletion = (completion2) => {
370
78
  mutate(completion2);
371
79
  };
372
- const input = ref2(initialInput);
80
+ const input = ref(initialInput);
373
81
  const handleSubmit = (event) => {
374
82
  var _a2;
375
83
  (_a2 = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a2.call(event);
@@ -384,182 +92,63 @@ function useCompletion({
384
92
  setCompletion,
385
93
  input,
386
94
  handleSubmit,
387
- isLoading,
388
- data: streamData
95
+ isLoading
389
96
  };
390
97
  }
391
98
 
392
- // src/use-assistant.ts
393
- import { isAbortError } from "@ai-sdk/provider-utils";
394
- import { generateId, processAssistantStream } from "@ai-sdk/ui-utils";
395
- import { computed as computed2, readonly, ref as ref3 } from "vue";
396
- function useAssistant({
397
- api,
398
- threadId: threadIdParam,
399
- credentials,
400
- headers,
401
- body,
402
- onError
403
- }) {
404
- const messages = ref3([]);
405
- const input = ref3("");
406
- const currentThreadId = ref3(void 0);
407
- const status = ref3("awaiting_message");
408
- const error = ref3(void 0);
409
- const setMessages = (messageFactory) => {
410
- messages.value = messageFactory(messages.value);
411
- };
412
- const setCurrentThreadId = (newThreadId) => {
413
- currentThreadId.value = newThreadId;
414
- messages.value = [];
415
- };
416
- const handleInputChange = (event) => {
417
- var _a;
418
- input.value = (_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value;
419
- };
420
- const isSending = computed2(() => status.value === "in_progress");
421
- const abortController = ref3(null);
422
- const stop = computed2(() => {
423
- return () => {
424
- if (abortController.value) {
425
- abortController.value.abort();
426
- abortController.value = null;
427
- }
99
+ // src/chat.vue.ts
100
+ import {
101
+ AbstractChat
102
+ } from "ai";
103
+ import { ref as ref2 } from "vue";
104
+ var VueChatState = class {
105
+ constructor(messages) {
106
+ this.statusRef = ref2("ready");
107
+ this.errorRef = ref2(void 0);
108
+ this.pushMessage = (message) => {
109
+ this.messagesRef.value.push(message);
428
110
  };
429
- });
430
- const append = async (message, requestOptions) => {
431
- var _a, _b, _c, _d;
432
- status.value = "in_progress";
433
- const newMessage = {
434
- ...message,
435
- id: (_a = message.id) != null ? _a : generateId()
111
+ this.popMessage = () => {
112
+ this.messagesRef.value.pop();
436
113
  };
437
- setMessages((messages2) => [...messages2, newMessage]);
438
- input.value = "";
439
- const controller = new AbortController();
440
- try {
441
- abortController.value = controller;
442
- const response = await fetch(api, {
443
- method: "POST",
444
- headers: {
445
- "Content-Type": "application/json",
446
- ...headers
447
- },
448
- body: JSON.stringify({
449
- ...body,
450
- // Message Content
451
- message: message.content,
452
- // Always Use User Provided Thread ID When Available
453
- threadId: (_b = threadIdParam != null ? threadIdParam : currentThreadId.value) != null ? _b : null,
454
- // Optional Request Data
455
- ...(requestOptions == null ? void 0 : requestOptions.data) && { data: requestOptions == null ? void 0 : requestOptions.data }
456
- }),
457
- signal: controller.signal,
458
- credentials
459
- });
460
- if (!response.ok) {
461
- throw new Error(
462
- (_c = response.statusText) != null ? _c : "An error occurred while sending the message"
463
- );
464
- }
465
- if (!response.body) {
466
- throw new Error("The response body is empty");
467
- }
468
- await processAssistantStream({
469
- stream: response.body,
470
- onAssistantMessagePart(value) {
471
- messages.value = [
472
- ...messages.value,
473
- {
474
- id: value.id,
475
- content: value.content[0].text.value,
476
- role: value.role,
477
- parts: []
478
- }
479
- ];
480
- },
481
- onTextPart(value) {
482
- setMessages((messages2) => {
483
- const lastMessage = messages2[messages2.length - 1];
484
- lastMessage.content += value;
485
- return [...messages2.slice(0, -1), lastMessage];
486
- });
487
- },
488
- onAssistantControlDataPart(value) {
489
- if (value.threadId) {
490
- currentThreadId.value = value.threadId;
491
- }
492
- setMessages((messages2) => {
493
- const lastMessage = messages2[messages2.length - 1];
494
- lastMessage.id = value.messageId;
495
- return [...messages2.slice(0, -1), lastMessage];
496
- });
497
- },
498
- onDataMessagePart(value) {
499
- setMessages((messages2) => {
500
- var _a2;
501
- return [
502
- ...messages2,
503
- {
504
- id: (_a2 = value.id) != null ? _a2 : generateId(),
505
- role: "data",
506
- content: "",
507
- data: value.data,
508
- parts: []
509
- }
510
- ];
511
- });
512
- },
513
- onErrorPart(value) {
514
- error.value = new Error(value);
515
- }
516
- });
517
- } catch (err) {
518
- if (isAbortError(err) && ((_d = abortController.value) == null ? void 0 : _d.signal.aborted)) {
519
- abortController.value = null;
520
- return;
521
- }
522
- if (onError && err instanceof Error) {
523
- onError(err);
524
- }
525
- error.value = err;
526
- } finally {
527
- abortController.value = null;
528
- status.value = "awaiting_message";
529
- }
530
- };
531
- const submitMessage = async (event, requestOptions) => {
532
- var _a;
533
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
534
- if (!input.value)
535
- return;
536
- append(
537
- {
538
- role: "user",
539
- content: input.value,
540
- parts: []
541
- },
542
- requestOptions
543
- );
544
- };
545
- return {
546
- append,
114
+ this.replaceMessage = (index, message) => {
115
+ this.messagesRef.value[index] = { ...message };
116
+ };
117
+ this.snapshot = (value) => value;
118
+ this.messagesRef = ref2(messages != null ? messages : []);
119
+ }
120
+ get messages() {
121
+ return this.messagesRef.value;
122
+ }
123
+ set messages(messages) {
124
+ this.messagesRef.value = messages;
125
+ }
126
+ get status() {
127
+ return this.statusRef.value;
128
+ }
129
+ set status(status) {
130
+ this.statusRef.value = status;
131
+ }
132
+ get error() {
133
+ return this.errorRef.value;
134
+ }
135
+ set error(error) {
136
+ this.errorRef.value = error;
137
+ }
138
+ };
139
+ var Chat = class extends AbstractChat {
140
+ constructor({
547
141
  messages,
548
- setMessages,
549
- threadId: readonly(currentThreadId),
550
- setThreadId: setCurrentThreadId,
551
- input,
552
- handleInputChange,
553
- handleSubmit: submitMessage,
554
- isSending,
555
- status,
556
- error,
557
- stop
558
- };
559
- }
142
+ ...init
143
+ }) {
144
+ super({
145
+ ...init,
146
+ state: new VueChatState(messages)
147
+ });
148
+ }
149
+ };
560
150
  export {
561
- useAssistant,
562
- useChat,
151
+ Chat,
563
152
  useCompletion
564
153
  };
565
154
  //# sourceMappingURL=index.mjs.map