|
| 1 | +/** |
| 2 | + * A vue.js composable function to interact with the assistant API. |
| 3 | + */ |
| 4 | + |
| 5 | +import { isAbortError } from '@ai-sdk/provider-utils'; |
| 6 | +import { readDataStream, generateId } from '@ai-sdk/ui-utils'; |
| 7 | +import type { |
| 8 | + AssistantStatus, |
| 9 | + CreateMessage, |
| 10 | + Message, |
| 11 | + UseAssistantOptions, |
| 12 | +} from '@ai-sdk/ui-utils'; |
| 13 | +import { computed, readonly, ref } from 'vue'; |
| 14 | +import type { ComputedRef, Ref } from 'vue'; |
| 15 | + |
| 16 | +export type UseAssistantHelpers = { |
| 17 | + /** |
| 18 | + * The current array of chat messages. |
| 19 | + */ |
| 20 | + messages: Ref<Message[]>; |
| 21 | + |
| 22 | + /** |
| 23 | + * Update the message store with a new array of messages. |
| 24 | + */ |
| 25 | + setMessages: (messagesProcessor: (messages: Message[]) => Message[]) => void; |
| 26 | + |
| 27 | + /** |
| 28 | + * The current thread ID. |
| 29 | + */ |
| 30 | + threadId: Ref<string | undefined>; |
| 31 | + |
| 32 | + /** |
| 33 | + * 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. |
| 34 | + */ |
| 35 | + setThreadId: (threadId: string | undefined) => void; |
| 36 | + /** |
| 37 | + * The current value of the input field. |
| 38 | + */ |
| 39 | + input: Ref<string>; |
| 40 | + |
| 41 | + /** |
| 42 | + * Append a user message to the chat list. This triggers the API call to fetch |
| 43 | + * the assistant's response. |
| 44 | + * @param message The message to append |
| 45 | + * @param requestOptions Additional options to pass to the API call |
| 46 | + */ |
| 47 | + append: ( |
| 48 | + message: Message | CreateMessage, |
| 49 | + requestOptions?: { |
| 50 | + data?: Record<string, string>; |
| 51 | + }, |
| 52 | + ) => Promise<void>; |
| 53 | + |
| 54 | + /** |
| 55 | + * Abort the current request immediately, keep the generated tokens if any. |
| 56 | + */ |
| 57 | + stop: ComputedRef<() => void>; |
| 58 | + |
| 59 | + /** |
| 60 | + * Handler for the `onChange` event of the input field to control the input's value. |
| 61 | + */ |
| 62 | + handleInputChange: (e: Event & { target: HTMLInputElement }) => void; |
| 63 | + |
| 64 | + /** |
| 65 | + * Handler for the `onSubmit` event of the form to append a user message and reset the input. |
| 66 | + */ |
| 67 | + handleSubmit: (e: Event & { target: HTMLFormElement }) => void; |
| 68 | + |
| 69 | + /** |
| 70 | + * Whether the assistant is currently sending a message. |
| 71 | + */ |
| 72 | + isSending: ComputedRef<boolean>; |
| 73 | + |
| 74 | + /** |
| 75 | + * The current status of the assistant. |
| 76 | + */ |
| 77 | + status: Ref<AssistantStatus>; |
| 78 | + |
| 79 | + /** |
| 80 | + * The current error, if any. |
| 81 | + */ |
| 82 | + error: Ref<Error | undefined>; |
| 83 | +}; |
| 84 | + |
| 85 | +export function useAssistant({ |
| 86 | + api, |
| 87 | + threadId: threadIdParam, |
| 88 | + credentials, |
| 89 | + headers, |
| 90 | + body, |
| 91 | + onError, |
| 92 | +}: UseAssistantOptions): UseAssistantHelpers { |
| 93 | + const messages: Ref<Message[]> = ref([]); |
| 94 | + const input: Ref<string> = ref(''); |
| 95 | + const currentThreadId: Ref<string | undefined> = ref(undefined); |
| 96 | + const status: Ref<AssistantStatus> = ref('awaiting_message'); |
| 97 | + const error: Ref<undefined | Error> = ref(undefined); |
| 98 | + |
| 99 | + const setMessages = (messageFactory: (messages: Message[]) => Message[]) => { |
| 100 | + messages.value = messageFactory(messages.value); |
| 101 | + }; |
| 102 | + |
| 103 | + const setCurrentThreadId = (newThreadId: string | undefined) => { |
| 104 | + currentThreadId.value = newThreadId; |
| 105 | + messages.value = []; |
| 106 | + }; |
| 107 | + |
| 108 | + const handleInputChange = (event: Event & { target: HTMLInputElement }) => { |
| 109 | + input.value = event?.target?.value; |
| 110 | + }; |
| 111 | + |
| 112 | + const isSending = computed(() => status.value === 'in_progress'); |
| 113 | + |
| 114 | + // Abort controller to cancel the current API call when required |
| 115 | + const abortController = ref<AbortController | null>(null); |
| 116 | + |
| 117 | + // memoized function to stop the current request when required |
| 118 | + const stop = computed(() => { |
| 119 | + return () => { |
| 120 | + if (abortController.value) { |
| 121 | + abortController.value.abort(); |
| 122 | + abortController.value = null; |
| 123 | + } |
| 124 | + }; |
| 125 | + }); |
| 126 | + |
| 127 | + const append = async ( |
| 128 | + message: Message | CreateMessage, |
| 129 | + requestOptions?: { |
| 130 | + data?: Record<string, string>; |
| 131 | + }, |
| 132 | + ) => { |
| 133 | + status.value = 'in_progress'; |
| 134 | + |
| 135 | + // Append the new message to the current list of messages |
| 136 | + const newMessage: Message = { |
| 137 | + ...message, |
| 138 | + id: message.id ?? generateId(), |
| 139 | + }; |
| 140 | + |
| 141 | + // Update the messages list with the new message |
| 142 | + setMessages(messages => [...messages, newMessage]); |
| 143 | + |
| 144 | + input.value = ''; |
| 145 | + |
| 146 | + const controller = new AbortController(); |
| 147 | + |
| 148 | + try { |
| 149 | + // Assign the new controller to the abortController ref |
| 150 | + abortController.value = controller; |
| 151 | + |
| 152 | + const response = await fetch(api, { |
| 153 | + method: 'POST', |
| 154 | + headers: { |
| 155 | + 'Content-Type': 'application/json', |
| 156 | + ...headers, |
| 157 | + }, |
| 158 | + body: JSON.stringify({ |
| 159 | + ...body, |
| 160 | + // Message Content |
| 161 | + message: message.content, |
| 162 | + |
| 163 | + // Always Use User Provided Thread ID When Available |
| 164 | + threadId: threadIdParam ?? currentThreadId.value ?? null, |
| 165 | + |
| 166 | + // Optional Request Data |
| 167 | + ...(requestOptions?.data && { data: requestOptions?.data }), |
| 168 | + }), |
| 169 | + signal: controller.signal, |
| 170 | + credentials, |
| 171 | + }); |
| 172 | + |
| 173 | + if (!response.ok) { |
| 174 | + throw new Error( |
| 175 | + response.statusText ?? 'An error occurred while sending the message', |
| 176 | + ); |
| 177 | + } |
| 178 | + |
| 179 | + if (!response.body) { |
| 180 | + throw new Error('The response body is empty'); |
| 181 | + } |
| 182 | + |
| 183 | + for await (const { type, value } of readDataStream( |
| 184 | + response.body.getReader(), |
| 185 | + )) { |
| 186 | + switch (type) { |
| 187 | + case 'assistant_message': { |
| 188 | + messages.value = [ |
| 189 | + ...messages.value, |
| 190 | + { |
| 191 | + id: value.id, |
| 192 | + content: value.content[0].text.value, |
| 193 | + role: value.role, |
| 194 | + }, |
| 195 | + ]; |
| 196 | + break; |
| 197 | + } |
| 198 | + case 'assistant_control_data': { |
| 199 | + if (value.threadId) { |
| 200 | + currentThreadId.value = value.threadId; |
| 201 | + } |
| 202 | + |
| 203 | + setMessages(messages => { |
| 204 | + const lastMessage = messages[messages.length - 1]; |
| 205 | + lastMessage.id = value.messageId; |
| 206 | + |
| 207 | + return [...messages.slice(0, -1), lastMessage]; |
| 208 | + }); |
| 209 | + |
| 210 | + break; |
| 211 | + } |
| 212 | + |
| 213 | + case 'text': { |
| 214 | + setMessages(messages => { |
| 215 | + const lastMessage = messages[messages.length - 1]; |
| 216 | + lastMessage.content += value; |
| 217 | + |
| 218 | + return [...messages.slice(0, -1), lastMessage]; |
| 219 | + }); |
| 220 | + |
| 221 | + break; |
| 222 | + } |
| 223 | + |
| 224 | + case 'data_message': { |
| 225 | + setMessages(messages => [ |
| 226 | + ...messages, |
| 227 | + { |
| 228 | + id: value.id ?? generateId(), |
| 229 | + role: 'data', |
| 230 | + content: '', |
| 231 | + data: value.data, |
| 232 | + }, |
| 233 | + ]); |
| 234 | + break; |
| 235 | + } |
| 236 | + |
| 237 | + case 'error': { |
| 238 | + error.value = new Error(value); |
| 239 | + } |
| 240 | + |
| 241 | + default: { |
| 242 | + console.error('Unknown message type:', type); |
| 243 | + break; |
| 244 | + } |
| 245 | + } |
| 246 | + } |
| 247 | + } catch (err) { |
| 248 | + // If the error is an AbortError and the signal is aborted, reset the abortController and do nothing. |
| 249 | + if (isAbortError(err) && abortController.value?.signal.aborted) { |
| 250 | + abortController.value = null; |
| 251 | + return; |
| 252 | + } |
| 253 | + |
| 254 | + // If an error handler is provided, call it with the error |
| 255 | + if (onError && err instanceof Error) { |
| 256 | + onError(err); |
| 257 | + } |
| 258 | + |
| 259 | + error.value = err as Error; |
| 260 | + } finally { |
| 261 | + // Reset the status to 'awaiting_message' after the request is complete |
| 262 | + abortController.value = null; |
| 263 | + status.value = 'awaiting_message'; |
| 264 | + } |
| 265 | + }; |
| 266 | + |
| 267 | + const submitMessage = async ( |
| 268 | + event: Event & { target: HTMLFormElement }, |
| 269 | + requestOptions?: { |
| 270 | + data?: Record<string, string>; |
| 271 | + }, |
| 272 | + ) => { |
| 273 | + event?.preventDefault?.(); |
| 274 | + |
| 275 | + if (!input.value) return; |
| 276 | + |
| 277 | + append( |
| 278 | + { |
| 279 | + role: 'user', |
| 280 | + content: input.value, |
| 281 | + }, |
| 282 | + requestOptions, |
| 283 | + ); |
| 284 | + }; |
| 285 | + |
| 286 | + return { |
| 287 | + append, |
| 288 | + messages, |
| 289 | + setMessages, |
| 290 | + threadId: readonly(currentThreadId), |
| 291 | + setThreadId: setCurrentThreadId, |
| 292 | + input, |
| 293 | + handleInputChange, |
| 294 | + handleSubmit: submitMessage, |
| 295 | + isSending, |
| 296 | + status, |
| 297 | + error, |
| 298 | + stop, |
| 299 | + }; |
| 300 | +} |
| 301 | + |
| 302 | +/** |
| 303 | + * @deprecated Use `useAssistant` instead. |
| 304 | + */ |
| 305 | +export const experimental_useAssistant = useAssistant; |
0 commit comments