@ai-sdk/vue 0.0.14 → 0.0.16
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/.turbo/turbo-build.log +10 -10
- package/.turbo/turbo-clean.log +1 -1
- package/CHANGELOG.md +14 -0
- package/README.md +3 -2
- package/dist/index.d.mts +73 -4
- package/dist/index.d.ts +73 -4
- package/dist/index.js +195 -10
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +193 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
- package/src/TestChatAssistantStreamComponent.vue +18 -0
- package/src/TestChatAssistantThreadChangeComponent.vue +22 -0
- package/src/index.ts +1 -0
- package/src/use-assistant.ts +305 -0
- package/src/use-assistant.ui.test.tsx +272 -0
- package/src/use-chat.ts +5 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
> @ai-sdk/vue@0.0.
|
|
2
|
+
> @ai-sdk/vue@0.0.16 build /home/runner/work/ai/ai/packages/vue
|
|
3
3
|
> tsup
|
|
4
4
|
|
|
5
5
|
[34mCLI[39m Building entry: src/index.ts
|
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
[34mCLI[39m Target: es2018
|
|
10
10
|
[34mCJS[39m Build start
|
|
11
11
|
[34mESM[39m Build start
|
|
12
|
-
[
|
|
13
|
-
[
|
|
14
|
-
[
|
|
15
|
-
[
|
|
16
|
-
[
|
|
17
|
-
[
|
|
12
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m14.02 KB[39m
|
|
13
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m30.47 KB[39m
|
|
14
|
+
[32mESM[39m ⚡️ Build success in 48ms
|
|
15
|
+
[32mCJS[39m [1mdist/index.js [22m[32m16.15 KB[39m
|
|
16
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m30.69 KB[39m
|
|
17
|
+
[32mCJS[39m ⚡️ Build success in 54ms
|
|
18
18
|
[34mDTS[39m Build start
|
|
19
|
-
[32mDTS[39m ⚡️ Build success in
|
|
20
|
-
[32mDTS[39m [1mdist/index.d.ts [22m[
|
|
21
|
-
[32mDTS[39m [1mdist/index.d.mts [22m[
|
|
19
|
+
[32mDTS[39m ⚡️ Build success in 5122ms
|
|
20
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m5.86 KB[39m
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.mts [22m[32m5.86 KB[39m
|
package/.turbo/turbo-clean.log
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @ai-sdk/vue
|
|
2
2
|
|
|
3
|
+
## 0.0.16
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a6cb2c8b: feat (ai/ui): add keepLastMessageOnError option to useChat
|
|
8
|
+
- Updated dependencies [a6cb2c8b]
|
|
9
|
+
- @ai-sdk/ui-utils@0.0.13
|
|
10
|
+
|
|
11
|
+
## 0.0.15
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- dd0d854e: feat (ai/vue): add useAssistant
|
|
16
|
+
|
|
3
17
|
## 0.0.14
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -2,5 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
[Vue.js](https://vuejs.org/) UI components for the [Vercel AI SDK](https://sdk.vercel.ai/docs):
|
|
4
4
|
|
|
5
|
-
- [`useChat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat)
|
|
6
|
-
- [`useCompletion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion)
|
|
5
|
+
- [`useChat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat) composable
|
|
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 { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
|
|
1
|
+
import { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
|
|
2
2
|
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
|
|
3
|
-
import { Ref } from 'vue';
|
|
3
|
+
import { Ref, ComputedRef } from 'vue';
|
|
4
4
|
|
|
5
5
|
type UseChatHelpers = {
|
|
6
6
|
/** Current messages in the chat */
|
|
@@ -39,7 +39,7 @@ type UseChatHelpers = {
|
|
|
39
39
|
/** Additional data added on the server via StreamData */
|
|
40
40
|
data: Ref<JSONValue[] | undefined>;
|
|
41
41
|
};
|
|
42
|
-
declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, streamMode, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, }?: UseChatOptions): UseChatHelpers;
|
|
42
|
+
declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, streamMode, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, }?: UseChatOptions): UseChatHelpers;
|
|
43
43
|
|
|
44
44
|
type UseCompletionHelpers = {
|
|
45
45
|
/** The current completion result */
|
|
@@ -79,4 +79,73 @@ type UseCompletionHelpers = {
|
|
|
79
79
|
};
|
|
80
80
|
declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamMode, onResponse, onFinish, onError, fetch, }?: UseCompletionOptions): UseCompletionHelpers;
|
|
81
81
|
|
|
82
|
-
|
|
82
|
+
/**
|
|
83
|
+
* A vue.js composable function to interact with the assistant API.
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
type UseAssistantHelpers = {
|
|
87
|
+
/**
|
|
88
|
+
* The current array of chat messages.
|
|
89
|
+
*/
|
|
90
|
+
messages: Ref<Message[]>;
|
|
91
|
+
/**
|
|
92
|
+
* Update the message store with a new array of messages.
|
|
93
|
+
*/
|
|
94
|
+
setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;
|
|
95
|
+
/**
|
|
96
|
+
* The current thread ID.
|
|
97
|
+
*/
|
|
98
|
+
threadId: Ref<string | undefined>;
|
|
99
|
+
/**
|
|
100
|
+
* 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.
|
|
101
|
+
*/
|
|
102
|
+
setThreadId: (threadId: string | undefined) => void;
|
|
103
|
+
/**
|
|
104
|
+
* The current value of the input field.
|
|
105
|
+
*/
|
|
106
|
+
input: Ref<string>;
|
|
107
|
+
/**
|
|
108
|
+
* Append a user message to the chat list. This triggers the API call to fetch
|
|
109
|
+
* the assistant's response.
|
|
110
|
+
* @param message The message to append
|
|
111
|
+
* @param requestOptions Additional options to pass to the API call
|
|
112
|
+
*/
|
|
113
|
+
append: (message: Message | CreateMessage, requestOptions?: {
|
|
114
|
+
data?: Record<string, string>;
|
|
115
|
+
}) => Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Abort the current request immediately, keep the generated tokens if any.
|
|
118
|
+
*/
|
|
119
|
+
stop: ComputedRef<() => void>;
|
|
120
|
+
/**
|
|
121
|
+
* Handler for the `onChange` event of the input field to control the input's value.
|
|
122
|
+
*/
|
|
123
|
+
handleInputChange: (e: Event & {
|
|
124
|
+
target: HTMLInputElement;
|
|
125
|
+
}) => void;
|
|
126
|
+
/**
|
|
127
|
+
* Handler for the `onSubmit` event of the form to append a user message and reset the input.
|
|
128
|
+
*/
|
|
129
|
+
handleSubmit: (e: Event & {
|
|
130
|
+
target: HTMLFormElement;
|
|
131
|
+
}) => void;
|
|
132
|
+
/**
|
|
133
|
+
* Whether the assistant is currently sending a message.
|
|
134
|
+
*/
|
|
135
|
+
isSending: ComputedRef<boolean>;
|
|
136
|
+
/**
|
|
137
|
+
* The current status of the assistant.
|
|
138
|
+
*/
|
|
139
|
+
status: Ref<AssistantStatus>;
|
|
140
|
+
/**
|
|
141
|
+
* The current error, if any.
|
|
142
|
+
*/
|
|
143
|
+
error: Ref<Error | undefined>;
|
|
144
|
+
};
|
|
145
|
+
declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, }: UseAssistantOptions): UseAssistantHelpers;
|
|
146
|
+
/**
|
|
147
|
+
* @deprecated Use `useAssistant` instead.
|
|
148
|
+
*/
|
|
149
|
+
declare const experimental_useAssistant: typeof useAssistant;
|
|
150
|
+
|
|
151
|
+
export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, experimental_useAssistant, useAssistant, useChat, useCompletion };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
|
|
1
|
+
import { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
|
|
2
2
|
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
|
|
3
|
-
import { Ref } from 'vue';
|
|
3
|
+
import { Ref, ComputedRef } from 'vue';
|
|
4
4
|
|
|
5
5
|
type UseChatHelpers = {
|
|
6
6
|
/** Current messages in the chat */
|
|
@@ -39,7 +39,7 @@ type UseChatHelpers = {
|
|
|
39
39
|
/** Additional data added on the server via StreamData */
|
|
40
40
|
data: Ref<JSONValue[] | undefined>;
|
|
41
41
|
};
|
|
42
|
-
declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, streamMode, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, }?: UseChatOptions): UseChatHelpers;
|
|
42
|
+
declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, streamMode, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, }?: UseChatOptions): UseChatHelpers;
|
|
43
43
|
|
|
44
44
|
type UseCompletionHelpers = {
|
|
45
45
|
/** The current completion result */
|
|
@@ -79,4 +79,73 @@ type UseCompletionHelpers = {
|
|
|
79
79
|
};
|
|
80
80
|
declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamMode, onResponse, onFinish, onError, fetch, }?: UseCompletionOptions): UseCompletionHelpers;
|
|
81
81
|
|
|
82
|
-
|
|
82
|
+
/**
|
|
83
|
+
* A vue.js composable function to interact with the assistant API.
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
type UseAssistantHelpers = {
|
|
87
|
+
/**
|
|
88
|
+
* The current array of chat messages.
|
|
89
|
+
*/
|
|
90
|
+
messages: Ref<Message[]>;
|
|
91
|
+
/**
|
|
92
|
+
* Update the message store with a new array of messages.
|
|
93
|
+
*/
|
|
94
|
+
setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void;
|
|
95
|
+
/**
|
|
96
|
+
* The current thread ID.
|
|
97
|
+
*/
|
|
98
|
+
threadId: Ref<string | undefined>;
|
|
99
|
+
/**
|
|
100
|
+
* 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.
|
|
101
|
+
*/
|
|
102
|
+
setThreadId: (threadId: string | undefined) => void;
|
|
103
|
+
/**
|
|
104
|
+
* The current value of the input field.
|
|
105
|
+
*/
|
|
106
|
+
input: Ref<string>;
|
|
107
|
+
/**
|
|
108
|
+
* Append a user message to the chat list. This triggers the API call to fetch
|
|
109
|
+
* the assistant's response.
|
|
110
|
+
* @param message The message to append
|
|
111
|
+
* @param requestOptions Additional options to pass to the API call
|
|
112
|
+
*/
|
|
113
|
+
append: (message: Message | CreateMessage, requestOptions?: {
|
|
114
|
+
data?: Record<string, string>;
|
|
115
|
+
}) => Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Abort the current request immediately, keep the generated tokens if any.
|
|
118
|
+
*/
|
|
119
|
+
stop: ComputedRef<() => void>;
|
|
120
|
+
/**
|
|
121
|
+
* Handler for the `onChange` event of the input field to control the input's value.
|
|
122
|
+
*/
|
|
123
|
+
handleInputChange: (e: Event & {
|
|
124
|
+
target: HTMLInputElement;
|
|
125
|
+
}) => void;
|
|
126
|
+
/**
|
|
127
|
+
* Handler for the `onSubmit` event of the form to append a user message and reset the input.
|
|
128
|
+
*/
|
|
129
|
+
handleSubmit: (e: Event & {
|
|
130
|
+
target: HTMLFormElement;
|
|
131
|
+
}) => void;
|
|
132
|
+
/**
|
|
133
|
+
* Whether the assistant is currently sending a message.
|
|
134
|
+
*/
|
|
135
|
+
isSending: ComputedRef<boolean>;
|
|
136
|
+
/**
|
|
137
|
+
* The current status of the assistant.
|
|
138
|
+
*/
|
|
139
|
+
status: Ref<AssistantStatus>;
|
|
140
|
+
/**
|
|
141
|
+
* The current error, if any.
|
|
142
|
+
*/
|
|
143
|
+
error: Ref<Error | undefined>;
|
|
144
|
+
};
|
|
145
|
+
declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, }: UseAssistantOptions): UseAssistantHelpers;
|
|
146
|
+
/**
|
|
147
|
+
* @deprecated Use `useAssistant` instead.
|
|
148
|
+
*/
|
|
149
|
+
declare const experimental_useAssistant: typeof useAssistant;
|
|
150
|
+
|
|
151
|
+
export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, experimental_useAssistant, useAssistant, useChat, useCompletion };
|
package/dist/index.js
CHANGED
|
@@ -30,6 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var src_exports = {};
|
|
32
32
|
__export(src_exports, {
|
|
33
|
+
experimental_useAssistant: () => experimental_useAssistant,
|
|
34
|
+
useAssistant: () => useAssistant,
|
|
33
35
|
useChat: () => useChat,
|
|
34
36
|
useCompletion: () => useCompletion
|
|
35
37
|
});
|
|
@@ -56,8 +58,9 @@ function useChat({
|
|
|
56
58
|
credentials,
|
|
57
59
|
headers,
|
|
58
60
|
body,
|
|
59
|
-
generateId = import_ui_utils.generateId,
|
|
60
|
-
fetch
|
|
61
|
+
generateId: generateId2 = import_ui_utils.generateId,
|
|
62
|
+
fetch: fetch2,
|
|
63
|
+
keepLastMessageOnError = false
|
|
61
64
|
} = {}) {
|
|
62
65
|
var _a, _b;
|
|
63
66
|
const chatId = id || `chat-${uniqueId++}`;
|
|
@@ -85,7 +88,7 @@ function useChat({
|
|
|
85
88
|
error.value = void 0;
|
|
86
89
|
mutateLoading(() => true);
|
|
87
90
|
abortController = new AbortController();
|
|
88
|
-
const previousMessages =
|
|
91
|
+
const previousMessages = messagesSnapshot;
|
|
89
92
|
mutate(messagesSnapshot);
|
|
90
93
|
const requestOptions = {
|
|
91
94
|
headers: headers2 != null ? headers2 : options == null ? void 0 : options.headers,
|
|
@@ -146,12 +149,14 @@ function useChat({
|
|
|
146
149
|
onFinish == null ? void 0 : onFinish(message);
|
|
147
150
|
},
|
|
148
151
|
restoreMessagesOnFailure() {
|
|
149
|
-
|
|
152
|
+
if (!keepLastMessageOnError) {
|
|
153
|
+
mutate(previousMessages);
|
|
154
|
+
}
|
|
150
155
|
},
|
|
151
|
-
generateId,
|
|
156
|
+
generateId: generateId2,
|
|
152
157
|
onToolCall: void 0,
|
|
153
158
|
// not implemented yet
|
|
154
|
-
fetch
|
|
159
|
+
fetch: fetch2
|
|
155
160
|
});
|
|
156
161
|
},
|
|
157
162
|
experimental_onFunctionCall,
|
|
@@ -177,7 +182,7 @@ function useChat({
|
|
|
177
182
|
const append = async (message, options) => {
|
|
178
183
|
var _a2, _b2, _c, _d;
|
|
179
184
|
if (!message.id) {
|
|
180
|
-
message.id =
|
|
185
|
+
message.id = generateId2();
|
|
181
186
|
}
|
|
182
187
|
const requestOptions = {
|
|
183
188
|
headers: (_b2 = options == null ? void 0 : options.headers) != null ? _b2 : (_a2 = options == null ? void 0 : options.options) == null ? void 0 : _a2.headers,
|
|
@@ -211,7 +216,7 @@ function useChat({
|
|
|
211
216
|
const inputValue = input.value;
|
|
212
217
|
triggerRequest(
|
|
213
218
|
inputValue ? messages.value.concat({
|
|
214
|
-
id:
|
|
219
|
+
id: generateId2(),
|
|
215
220
|
content: inputValue,
|
|
216
221
|
role: "user"
|
|
217
222
|
}) : messages.value,
|
|
@@ -252,7 +257,7 @@ function useCompletion({
|
|
|
252
257
|
onResponse,
|
|
253
258
|
onFinish,
|
|
254
259
|
onError,
|
|
255
|
-
fetch
|
|
260
|
+
fetch: fetch2
|
|
256
261
|
} = {}) {
|
|
257
262
|
var _a;
|
|
258
263
|
const completionId = id || `completion-${uniqueId2++}`;
|
|
@@ -305,7 +310,7 @@ function useCompletion({
|
|
|
305
310
|
onData: (data2) => {
|
|
306
311
|
mutateStreamData(() => [...existingData, ...data2 != null ? data2 : []]);
|
|
307
312
|
},
|
|
308
|
-
fetch
|
|
313
|
+
fetch: fetch2
|
|
309
314
|
});
|
|
310
315
|
}
|
|
311
316
|
const complete = async (prompt, options) => {
|
|
@@ -339,8 +344,188 @@ function useCompletion({
|
|
|
339
344
|
data: streamData
|
|
340
345
|
};
|
|
341
346
|
}
|
|
347
|
+
|
|
348
|
+
// src/use-assistant.ts
|
|
349
|
+
var import_provider_utils = require("@ai-sdk/provider-utils");
|
|
350
|
+
var import_ui_utils3 = require("@ai-sdk/ui-utils");
|
|
351
|
+
var import_vue3 = require("vue");
|
|
352
|
+
function useAssistant({
|
|
353
|
+
api,
|
|
354
|
+
threadId: threadIdParam,
|
|
355
|
+
credentials,
|
|
356
|
+
headers,
|
|
357
|
+
body,
|
|
358
|
+
onError
|
|
359
|
+
}) {
|
|
360
|
+
const messages = (0, import_vue3.ref)([]);
|
|
361
|
+
const input = (0, import_vue3.ref)("");
|
|
362
|
+
const currentThreadId = (0, import_vue3.ref)(void 0);
|
|
363
|
+
const status = (0, import_vue3.ref)("awaiting_message");
|
|
364
|
+
const error = (0, import_vue3.ref)(void 0);
|
|
365
|
+
const setMessages = (messageFactory) => {
|
|
366
|
+
messages.value = messageFactory(messages.value);
|
|
367
|
+
};
|
|
368
|
+
const setCurrentThreadId = (newThreadId) => {
|
|
369
|
+
currentThreadId.value = newThreadId;
|
|
370
|
+
messages.value = [];
|
|
371
|
+
};
|
|
372
|
+
const handleInputChange = (event) => {
|
|
373
|
+
var _a;
|
|
374
|
+
input.value = (_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value;
|
|
375
|
+
};
|
|
376
|
+
const isSending = (0, import_vue3.computed)(() => status.value === "in_progress");
|
|
377
|
+
const abortController = (0, import_vue3.ref)(null);
|
|
378
|
+
const stop = (0, import_vue3.computed)(() => {
|
|
379
|
+
return () => {
|
|
380
|
+
if (abortController.value) {
|
|
381
|
+
abortController.value.abort();
|
|
382
|
+
abortController.value = null;
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
const append = async (message, requestOptions) => {
|
|
387
|
+
var _a, _b, _c, _d;
|
|
388
|
+
status.value = "in_progress";
|
|
389
|
+
const newMessage = {
|
|
390
|
+
...message,
|
|
391
|
+
id: (_a = message.id) != null ? _a : (0, import_ui_utils3.generateId)()
|
|
392
|
+
};
|
|
393
|
+
setMessages((messages2) => [...messages2, newMessage]);
|
|
394
|
+
input.value = "";
|
|
395
|
+
const controller = new AbortController();
|
|
396
|
+
try {
|
|
397
|
+
abortController.value = controller;
|
|
398
|
+
const response = await fetch(api, {
|
|
399
|
+
method: "POST",
|
|
400
|
+
headers: {
|
|
401
|
+
"Content-Type": "application/json",
|
|
402
|
+
...headers
|
|
403
|
+
},
|
|
404
|
+
body: JSON.stringify({
|
|
405
|
+
...body,
|
|
406
|
+
// Message Content
|
|
407
|
+
message: message.content,
|
|
408
|
+
// Always Use User Provided Thread ID When Available
|
|
409
|
+
threadId: (_b = threadIdParam != null ? threadIdParam : currentThreadId.value) != null ? _b : null,
|
|
410
|
+
// Optional Request Data
|
|
411
|
+
...(requestOptions == null ? void 0 : requestOptions.data) && { data: requestOptions == null ? void 0 : requestOptions.data }
|
|
412
|
+
}),
|
|
413
|
+
signal: controller.signal,
|
|
414
|
+
credentials
|
|
415
|
+
});
|
|
416
|
+
if (!response.ok) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
(_c = response.statusText) != null ? _c : "An error occurred while sending the message"
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (!response.body) {
|
|
422
|
+
throw new Error("The response body is empty");
|
|
423
|
+
}
|
|
424
|
+
for await (const { type, value } of (0, import_ui_utils3.readDataStream)(
|
|
425
|
+
response.body.getReader()
|
|
426
|
+
)) {
|
|
427
|
+
switch (type) {
|
|
428
|
+
case "assistant_message": {
|
|
429
|
+
messages.value = [
|
|
430
|
+
...messages.value,
|
|
431
|
+
{
|
|
432
|
+
id: value.id,
|
|
433
|
+
content: value.content[0].text.value,
|
|
434
|
+
role: value.role
|
|
435
|
+
}
|
|
436
|
+
];
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
case "assistant_control_data": {
|
|
440
|
+
if (value.threadId) {
|
|
441
|
+
currentThreadId.value = value.threadId;
|
|
442
|
+
}
|
|
443
|
+
setMessages((messages2) => {
|
|
444
|
+
const lastMessage = messages2[messages2.length - 1];
|
|
445
|
+
lastMessage.id = value.messageId;
|
|
446
|
+
return [...messages2.slice(0, -1), lastMessage];
|
|
447
|
+
});
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
case "text": {
|
|
451
|
+
setMessages((messages2) => {
|
|
452
|
+
const lastMessage = messages2[messages2.length - 1];
|
|
453
|
+
lastMessage.content += value;
|
|
454
|
+
return [...messages2.slice(0, -1), lastMessage];
|
|
455
|
+
});
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
case "data_message": {
|
|
459
|
+
setMessages((messages2) => {
|
|
460
|
+
var _a2;
|
|
461
|
+
return [
|
|
462
|
+
...messages2,
|
|
463
|
+
{
|
|
464
|
+
id: (_a2 = value.id) != null ? _a2 : (0, import_ui_utils3.generateId)(),
|
|
465
|
+
role: "data",
|
|
466
|
+
content: "",
|
|
467
|
+
data: value.data
|
|
468
|
+
}
|
|
469
|
+
];
|
|
470
|
+
});
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
case "error": {
|
|
474
|
+
error.value = new Error(value);
|
|
475
|
+
}
|
|
476
|
+
default: {
|
|
477
|
+
console.error("Unknown message type:", type);
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
} catch (err) {
|
|
483
|
+
if ((0, import_provider_utils.isAbortError)(err) && ((_d = abortController.value) == null ? void 0 : _d.signal.aborted)) {
|
|
484
|
+
abortController.value = null;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (onError && err instanceof Error) {
|
|
488
|
+
onError(err);
|
|
489
|
+
}
|
|
490
|
+
error.value = err;
|
|
491
|
+
} finally {
|
|
492
|
+
abortController.value = null;
|
|
493
|
+
status.value = "awaiting_message";
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
const submitMessage = async (event, requestOptions) => {
|
|
497
|
+
var _a;
|
|
498
|
+
(_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
|
|
499
|
+
if (!input.value)
|
|
500
|
+
return;
|
|
501
|
+
append(
|
|
502
|
+
{
|
|
503
|
+
role: "user",
|
|
504
|
+
content: input.value
|
|
505
|
+
},
|
|
506
|
+
requestOptions
|
|
507
|
+
);
|
|
508
|
+
};
|
|
509
|
+
return {
|
|
510
|
+
append,
|
|
511
|
+
messages,
|
|
512
|
+
setMessages,
|
|
513
|
+
threadId: (0, import_vue3.readonly)(currentThreadId),
|
|
514
|
+
setThreadId: setCurrentThreadId,
|
|
515
|
+
input,
|
|
516
|
+
handleInputChange,
|
|
517
|
+
handleSubmit: submitMessage,
|
|
518
|
+
isSending,
|
|
519
|
+
status,
|
|
520
|
+
error,
|
|
521
|
+
stop
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
var experimental_useAssistant = useAssistant;
|
|
342
525
|
// Annotate the CommonJS export names for ESM import in node:
|
|
343
526
|
0 && (module.exports = {
|
|
527
|
+
experimental_useAssistant,
|
|
528
|
+
useAssistant,
|
|
344
529
|
useChat,
|
|
345
530
|
useCompletion
|
|
346
531
|
});
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n processChatStream,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<Message[]>;\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: (messages: Message[]) => 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 /** 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, Message[] | undefined> = {};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n experimental_onFunctionCall,\n streamMode,\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n}: UseChatOptions = {}): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id || `chat-${uniqueId++}`;\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<Message[]>(\n key,\n () => store[key] || initialMessages,\n );\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${chatId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= initialMessages;\n\n const mutate = (data?: Message[]) => {\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<Message[]>;\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 async function triggerRequest(\n messagesSnapshot: Message[],\n { options, data, headers, body }: ChatRequestOptions = {},\n ) {\n try {\n error.value = undefined;\n mutateLoading(() => true);\n\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = messagesData.value;\n mutate(messagesSnapshot);\n\n const requestOptions = {\n headers: headers ?? options?.headers,\n body: body ?? options?.body,\n };\n\n let chatRequest: ChatRequest = {\n messages: messagesSnapshot,\n options: requestOptions,\n body: requestOptions.body,\n headers: requestOptions.headers,\n data,\n };\n\n await processChatStream({\n getStreamedResponse: async () => {\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n name,\n data,\n annotations,\n function_call,\n }) => ({\n role,\n content,\n ...(name !== undefined && { name }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n // outdated function/tool call handling (TODO deprecate):\n ...(function_call !== undefined && { function_call }),\n }),\n );\n\n return await callChatApi({\n api,\n body: {\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...unref(body), // Use unref to unwrap the ref value\n ...requestOptions.body,\n },\n streamMode,\n headers: {\n ...headers,\n ...requestOptions.headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged]);\n streamData.value = [...existingData, ...(data ?? [])];\n },\n onFinish(message) {\n // workaround: sometimes the last chunk is not shown in the UI.\n // push it twice to make sure it's displayed.\n mutate([...chatRequest.messages, message]);\n onFinish?.(message);\n },\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n mutate(previousMessages);\n },\n generateId,\n onToolCall: undefined, // not implemented yet\n fetch,\n });\n },\n experimental_onFunctionCall,\n updateChatRequest(newChatRequest) {\n chatRequest = newChatRequest;\n },\n getCurrentMessages: () => messages.value,\n });\n\n abortController = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n } finally {\n mutateLoading(() => false);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n if (!message.id) {\n message.id = generateId();\n }\n\n const requestOptions = {\n headers: options?.headers ?? options?.options?.headers,\n body: options?.body ?? options?.options?.body,\n };\n\n return triggerRequest(messages.value.concat(message as Message), options);\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 return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (messages: Message[]) => {\n mutate(messages);\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n triggerRequest(\n inputValue\n ? messages.value.concat({\n id: generateId(),\n content: inputValue,\n role: 'user',\n })\n : messages.value,\n options,\n );\n\n input.value = '';\n };\n\n return {\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading,\n data: streamData as Ref<undefined | JSONValue[]>,\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 streamMode,\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 streamMode,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,sBAIO;AACP,kBAAiB;AAEjB,iBAA2B;AAiD3B,IAAI,WAAW;AAGf,IAAM,UAAW,YAAAA,QAAK,WAAgD,YAAAA;AACtE,IAAM,QAA+C,CAAC;AAE/C,SAAS,QAAQ;AAAA,EACtB,MAAM;AAAA,EACN;AAAA,EACA,kBAAkB,CAAC;AAAA,EACnB,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,gBAAAC;AAAA,EACb;AACF,IAAoB,CAAC,GAAmB;AAtFxC;AAwFE,QAAM,SAAS,MAAM,QAAQ,UAAU;AAEvC,QAAM,MAAM,GAAG,GAAG,IAAI,MAAM;AAC5B,QAAM,EAAE,MAAM,cAAc,QAAQ,eAAe,IAAI;AAAA,IACrD;AAAA,IACA,MAAM,MAAM,GAAG,KAAK;AAAA,EACtB;AAEA,QAAM,EAAE,MAAM,WAAW,QAAQ,cAAc,IAAI;AAAA,IACjD,GAAG,MAAM;AAAA,IACT;AAAA,EACF;AAEA,kBAAU,UAAV,sBAAU,QAAU;AAGpB,qBA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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","headers","body","_a","data","_b","messages","import_ui_utils","import_swrv","import_vue","uniqueId","useSWRV","swrv","store","data","_a","completion"]}
|
|
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 ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n processChatStream,\n} from '@ai-sdk/ui-utils';\nimport swrv from 'swrv';\nimport type { Ref } from 'vue';\nimport { ref, unref } from 'vue';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Ref<Message[]>;\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: (messages: Message[]) => 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 /** 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, Message[] | undefined> = {};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n experimental_onFunctionCall,\n streamMode,\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = false,\n}: UseChatOptions = {}): UseChatHelpers {\n // Generate a unique ID for the chat if not provided.\n const chatId = id || `chat-${uniqueId++}`;\n\n const key = `${api}|${chatId}`;\n const { data: messagesData, mutate: originalMutate } = useSWRV<Message[]>(\n key,\n () => store[key] || initialMessages,\n );\n\n const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n `${chatId}-loading`,\n null,\n );\n\n isLoading.value ??= false;\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n messagesData.value ??= initialMessages;\n\n const mutate = (data?: Message[]) => {\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<Message[]>;\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 async function triggerRequest(\n messagesSnapshot: Message[],\n { options, data, headers, body }: ChatRequestOptions = {},\n ) {\n try {\n error.value = undefined;\n mutateLoading(() => true);\n\n abortController = new AbortController();\n\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n const previousMessages = messagesSnapshot;\n mutate(messagesSnapshot);\n\n const requestOptions = {\n headers: headers ?? options?.headers,\n body: body ?? options?.body,\n };\n\n let chatRequest: ChatRequest = {\n messages: messagesSnapshot,\n options: requestOptions,\n body: requestOptions.body,\n headers: requestOptions.headers,\n data,\n };\n\n await processChatStream({\n getStreamedResponse: async () => {\n const existingData = (streamData.value ?? []) as JSONValue[];\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatRequest.messages\n : chatRequest.messages.map(\n ({\n role,\n content,\n name,\n data,\n annotations,\n function_call,\n }) => ({\n role,\n content,\n ...(name !== undefined && { name }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n // outdated function/tool call handling (TODO deprecate):\n ...(function_call !== undefined && { function_call }),\n }),\n );\n\n return await callChatApi({\n api,\n body: {\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...unref(body), // Use unref to unwrap the ref value\n ...requestOptions.body,\n },\n streamMode,\n headers: {\n ...headers,\n ...requestOptions.headers,\n },\n abortController: () => abortController,\n credentials,\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged]);\n streamData.value = [...existingData, ...(data ?? [])];\n },\n onFinish(message) {\n // workaround: sometimes the last chunk is not shown in the UI.\n // push it twice to make sure it's displayed.\n mutate([...chatRequest.messages, message]);\n onFinish?.(message);\n },\n restoreMessagesOnFailure() {\n // Restore the previous messages if the request fails.\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n generateId,\n onToolCall: undefined, // not implemented yet\n fetch,\n });\n },\n experimental_onFunctionCall,\n updateChatRequest(newChatRequest) {\n chatRequest = newChatRequest;\n },\n getCurrentMessages: () => messages.value,\n });\n\n abortController = null;\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortController = null;\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.value = err as Error;\n } finally {\n mutateLoading(() => false);\n }\n }\n\n const append: UseChatHelpers['append'] = async (message, options) => {\n if (!message.id) {\n message.id = generateId();\n }\n\n const requestOptions = {\n headers: options?.headers ?? options?.options?.headers,\n body: options?.body ?? options?.options?.body,\n };\n\n return triggerRequest(messages.value.concat(message as Message), options);\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 return triggerRequest(messagesSnapshot, options);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (messages: Message[]) => {\n mutate(messages);\n };\n\n const input = ref(initialInput);\n\n const handleSubmit = (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n\n const inputValue = input.value;\n\n triggerRequest(\n inputValue\n ? messages.value.concat({\n id: generateId(),\n content: inputValue,\n role: 'user',\n })\n : messages.value,\n options,\n );\n\n input.value = '';\n };\n\n return {\n messages,\n append,\n error,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading,\n data: streamData as Ref<undefined | JSONValue[]>,\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 streamMode,\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 streamMode,\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 { readDataStream, generateId } from '@ai-sdk/ui-utils';\nimport type {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n} from '@ai-sdk/ui-utils';\nimport { computed, readonly, ref } from 'vue';\nimport type { ComputedRef, 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 for await (const { type, value } of readDataStream(\n response.body.getReader(),\n )) {\n switch (type) {\n case 'assistant_message': {\n messages.value = [\n ...messages.value,\n {\n id: value.id,\n content: value.content[0].text.value,\n role: value.role,\n },\n ];\n break;\n }\n case 'assistant_control_data': {\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 break;\n }\n\n case 'text': {\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 break;\n }\n\n case 'data_message': {\n setMessages(messages => [\n ...messages,\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n break;\n }\n\n case 'error': {\n error.value = new Error(value);\n }\n\n default: {\n console.error('Unknown message type:', type);\n break;\n }\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 },\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\n/**\n * @deprecated Use `useAssistant` instead.\n */\nexport const experimental_useAssistant = useAssistant;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,sBAIO;AACP,kBAAiB;AAEjB,iBAA2B;AAiD3B,IAAI,WAAW;AAGf,IAAM,UAAW,YAAAA,QAAK,WAAgD,YAAAA;AACtE,IAAM,QAA+C,CAAC;AAE/C,SAAS,QAAQ;AAAA,EACtB,MAAM;AAAA,EACN;AAAA,EACA,kBAAkB,CAAC;AAAA,EACnB,eAAe;AAAA,EACf;AAAA,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ACE;AAAA,QACE,MAAM;AAAA,QACN,SAAS,MAAM;AAAA,MACjB;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;AAKO,IAAM,4BAA4B;","names":["swrv","generateId","generateIdFunc","fetch","headers","body","_a","data","_b","messages","import_ui_utils","import_swrv","import_vue","uniqueId","useSWRV","swrv","store","fetch","data","_a","completion","import_ui_utils","import_vue","messages","_a"]}
|