|
| 1 | +import { isAbortError } from '@ai-sdk/provider-utils'; |
| 2 | +import { Readable, Writable, get, writable } from 'svelte/store'; |
| 3 | +import { generateId } from '../shared/generate-id'; |
| 4 | +import { readDataStream } from '../shared/read-data-stream'; |
| 5 | +import type { |
| 6 | + AssistantStatus, |
| 7 | + CreateMessage, |
| 8 | + Message, |
| 9 | + UseAssistantOptions, |
| 10 | +} from '../shared/types'; |
| 11 | + |
| 12 | +let uniqueId = 0; |
| 13 | + |
| 14 | +const store: Record<string, any> = {}; |
| 15 | + |
| 16 | +export type UseAssistantHelpers = { |
| 17 | + /** |
| 18 | + * The current array of chat messages. |
| 19 | + */ |
| 20 | + messages: Readable<Message[]>; |
| 21 | + |
| 22 | + /** |
| 23 | + * Update the message store with a new array of messages. |
| 24 | + */ |
| 25 | + setMessages: (messages: Message[]) => void; |
| 26 | + |
| 27 | + /** |
| 28 | + * The current thread ID. |
| 29 | + */ |
| 30 | + threadId: Readable<string | undefined>; |
| 31 | + |
| 32 | + /** |
| 33 | + * The current value of the input field. |
| 34 | + */ |
| 35 | + input: Writable<string>; |
| 36 | + |
| 37 | + /** |
| 38 | + * Append a user message to the chat list. This triggers the API call to fetch |
| 39 | + * the assistant's response. |
| 40 | + * @param message The message to append |
| 41 | + * @param requestOptions Additional options to pass to the API call |
| 42 | + */ |
| 43 | + append: ( |
| 44 | + message: Message | CreateMessage, |
| 45 | + requestOptions?: { data?: Record<string, string> }, |
| 46 | + ) => Promise<void>; |
| 47 | + |
| 48 | + /** |
| 49 | +Abort the current request immediately, keep the generated tokens if any. |
| 50 | + */ |
| 51 | + stop: () => void; |
| 52 | + |
| 53 | + /** |
| 54 | + * Form submission handler that automatically resets the input field and appends a user message. |
| 55 | + */ |
| 56 | + submitMessage: ( |
| 57 | + e: any, |
| 58 | + requestOptions?: { data?: Record<string, string> }, |
| 59 | + ) => Promise<void>; |
| 60 | + |
| 61 | + /** |
| 62 | + * The current status of the assistant. This can be used to show a loading indicator. |
| 63 | + */ |
| 64 | + status: Readable<AssistantStatus>; |
| 65 | + |
| 66 | + /** |
| 67 | + * The error thrown during the assistant message processing, if any. |
| 68 | + */ |
| 69 | + error: Readable<undefined | Error>; |
| 70 | +}; |
| 71 | + |
| 72 | +export function useAssistant({ |
| 73 | + api, |
| 74 | + threadId: threadIdParam, |
| 75 | + credentials, |
| 76 | + headers, |
| 77 | + body, |
| 78 | + onError, |
| 79 | +}: UseAssistantOptions): UseAssistantHelpers { |
| 80 | + // Generate a unique thread ID |
| 81 | + const threadIdStore = writable<string | undefined>(threadIdParam); |
| 82 | + |
| 83 | + // Initialize message, input, status, and error stores |
| 84 | + const key = `${api}|${threadIdParam ?? `completion-${uniqueId++}`}`; |
| 85 | + const messages = writable<Message[]>(store[key] || []); |
| 86 | + const input = writable(''); |
| 87 | + const status = writable<AssistantStatus>('awaiting_message'); |
| 88 | + const error = writable<undefined | Error>(undefined); |
| 89 | + |
| 90 | + // To manage aborting the current fetch request |
| 91 | + let abortController: AbortController | null = null; |
| 92 | + |
| 93 | + // Update the message store |
| 94 | + const mutateMessages = (newMessages: Message[]) => { |
| 95 | + store[key] = newMessages; |
| 96 | + messages.set(newMessages); |
| 97 | + }; |
| 98 | + |
| 99 | + // Function to handle API calls and state management |
| 100 | + async function append( |
| 101 | + message: Message | CreateMessage, |
| 102 | + requestOptions?: { data?: Record<string, string> }, |
| 103 | + ) { |
| 104 | + status.set('in_progress'); |
| 105 | + abortController = new AbortController(); // Initialize a new AbortController |
| 106 | + |
| 107 | + // Add the new message to the existing array |
| 108 | + mutateMessages([ |
| 109 | + ...get(messages), |
| 110 | + { ...message, id: message.id ?? generateId() }, |
| 111 | + ]); |
| 112 | + |
| 113 | + input.set(''); |
| 114 | + |
| 115 | + try { |
| 116 | + const result = await fetch(api, { |
| 117 | + method: 'POST', |
| 118 | + credentials, |
| 119 | + signal: abortController.signal, |
| 120 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 121 | + body: JSON.stringify({ |
| 122 | + ...body, |
| 123 | + // always use user-provided threadId when available: |
| 124 | + threadId: threadIdParam ?? get(threadIdStore) ?? null, |
| 125 | + message: message.content, |
| 126 | + |
| 127 | + // optional request data: |
| 128 | + data: requestOptions?.data, |
| 129 | + }), |
| 130 | + }); |
| 131 | + |
| 132 | + if (result.body == null) { |
| 133 | + throw new Error('The response body is empty.'); |
| 134 | + } |
| 135 | + |
| 136 | + // Read the streamed response data |
| 137 | + for await (const { type, value } of readDataStream( |
| 138 | + result.body.getReader(), |
| 139 | + )) { |
| 140 | + switch (type) { |
| 141 | + case 'assistant_message': { |
| 142 | + mutateMessages([ |
| 143 | + ...get(messages), |
| 144 | + { |
| 145 | + id: value.id, |
| 146 | + role: value.role, |
| 147 | + content: value.content[0].text.value, |
| 148 | + }, |
| 149 | + ]); |
| 150 | + break; |
| 151 | + } |
| 152 | + |
| 153 | + case 'text': { |
| 154 | + // text delta - add to last message: |
| 155 | + mutateMessages( |
| 156 | + get(messages).map((msg, index, array) => { |
| 157 | + if (index === array.length - 1) { |
| 158 | + return { ...msg, content: msg.content + value }; |
| 159 | + } |
| 160 | + return msg; |
| 161 | + }), |
| 162 | + ); |
| 163 | + break; |
| 164 | + } |
| 165 | + |
| 166 | + case 'data_message': { |
| 167 | + mutateMessages([ |
| 168 | + ...get(messages), |
| 169 | + { |
| 170 | + id: value.id ?? generateId(), |
| 171 | + role: 'data', |
| 172 | + content: '', |
| 173 | + data: value.data, |
| 174 | + }, |
| 175 | + ]); |
| 176 | + break; |
| 177 | + } |
| 178 | + |
| 179 | + case 'assistant_control_data': { |
| 180 | + threadIdStore.set(value.threadId); |
| 181 | + |
| 182 | + mutateMessages( |
| 183 | + get(messages).map((msg, index, array) => { |
| 184 | + if (index === array.length - 1) { |
| 185 | + return { ...msg, id: value.messageId }; |
| 186 | + } |
| 187 | + return msg; |
| 188 | + }), |
| 189 | + ); |
| 190 | + |
| 191 | + break; |
| 192 | + } |
| 193 | + |
| 194 | + case 'error': { |
| 195 | + error.set(new Error(value)); |
| 196 | + break; |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + } catch (err) { |
| 201 | + // Ignore abort errors as they are expected when the user cancels the request: |
| 202 | + if (isAbortError(error) && abortController?.signal?.aborted) { |
| 203 | + abortController = null; |
| 204 | + return; |
| 205 | + } |
| 206 | + |
| 207 | + if (onError && err instanceof Error) { |
| 208 | + onError(err); |
| 209 | + } |
| 210 | + |
| 211 | + error.set(err as Error); |
| 212 | + } finally { |
| 213 | + abortController = null; |
| 214 | + status.set('awaiting_message'); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + function setMessages(messages: Message[]) { |
| 219 | + mutateMessages(messages); |
| 220 | + } |
| 221 | + |
| 222 | + function stop() { |
| 223 | + if (abortController) { |
| 224 | + abortController.abort(); |
| 225 | + abortController = null; |
| 226 | + } |
| 227 | + } |
| 228 | + |
| 229 | + // Function to handle form submission |
| 230 | + async function submitMessage( |
| 231 | + e: any, |
| 232 | + requestOptions?: { data?: Record<string, string> }, |
| 233 | + ) { |
| 234 | + e.preventDefault(); |
| 235 | + const inputValue = get(input); |
| 236 | + if (!inputValue) return; |
| 237 | + |
| 238 | + await append({ role: 'user', content: inputValue }, requestOptions); |
| 239 | + } |
| 240 | + |
| 241 | + return { |
| 242 | + messages, |
| 243 | + error, |
| 244 | + threadId: threadIdStore, |
| 245 | + input, |
| 246 | + append, |
| 247 | + submitMessage, |
| 248 | + status, |
| 249 | + setMessages, |
| 250 | + stop, |
| 251 | + }; |
| 252 | +} |
0 commit comments