ai
Version:
Vercel AI SDK - The AI Toolkit for TypeScript and JavaScript
1 lines • 65.9 kB
Source Map (JSON)
{"version":3,"sources":["../use-chat.ts","../../../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs","../../../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.18/node_modules/sswr/dist/sswr.js","../use-completion.ts","../use-assistant.ts"],"sourcesContent":["import type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n FetchFunction,\n IdGenerator,\n JSONValue,\n Message,\n UseChatOptions as SharedUseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n generateId as generateIdFunc,\n processChatStream,\n} from '@ai-sdk/ui-utils';\nimport { useSWR } from 'sswr';\nimport { Readable, Writable, derived, get, writable } from 'svelte/store';\nexport type { CreateMessage, Message };\n\nexport type UseChatOptions = SharedUseChatOptions & {\n /**\n Maximal number of automatic roundtrips for tool calls.\n\n An automatic tool call roundtrip is a call to the server with the\n tool call results when all tool calls in the last assistant\n message have results.\n\n A maximum number is required to prevent infinite loops in the\n case of misconfigured tools.\n\n By default, it's set to 0, which will disable the feature.\n */\n maxToolRoundtrips?: number;\n};\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Readable<Message[]>;\n /** The error object of the API request */\n error: Readable<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 * @param message The message to append\n * @param chatRequestOptions Additional options to pass to the API call\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: (\n messages: Message[] | ((messages: Message[]) => Message[]),\n ) => void;\n\n /** The current value of the input */\n input: Writable<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 metadata?: Object;\n /** Whether the API request is in progress */\n isLoading: Readable<boolean | undefined>;\n\n /** Additional data added on the server via StreamData */\n data: Readable<JSONValue[] | undefined>;\n /**\n Maximal number of automatic roundtrips for tool calls.\n\n An automatic tool call roundtrip is a call to the server with the\n tool call results when all tool calls in the last assistant\n message have results.\n\n A maximum number is required to prevent infinite loops in the\n case of misconfigured tools.\n\n By default, it's set to 0, which will disable the feature.\n */\n maxToolRoundtrips?: number;\n};\n\nconst getStreamedResponse = async (\n api: string,\n chatRequest: ChatRequest,\n mutate: (messages: Message[]) => void,\n mutateStreamData: (data: JSONValue[] | undefined) => void,\n existingData: JSONValue[] | undefined,\n extraMetadata: {\n credentials?: RequestCredentials;\n headers?: Record<string, string> | Headers;\n body?: any;\n },\n previousMessages: Message[],\n abortControllerRef: AbortController | null,\n generateId: IdGenerator,\n streamProtocol: UseChatOptions['streamProtocol'],\n onFinish: UseChatOptions['onFinish'],\n onResponse: ((response: Response) => void | Promise<void>) | undefined,\n onToolCall: UseChatOptions['onToolCall'] | undefined,\n sendExtraMessageFields: boolean | undefined,\n fetch: FetchFunction | undefined,\n keepLastMessageOnError: boolean | undefined,\n) => {\n // Do an optimistic update to the chat state to show the updated messages\n // immediately.\n mutate(chatRequest.messages);\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 tool_calls,\n tool_call_id,\n toolInvocations,\n }) => ({\n role,\n content,\n ...(name !== undefined && { name }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n // outdated function/tool call handling (TODO deprecate):\n tool_call_id,\n ...(function_call !== undefined && { function_call }),\n ...(tool_calls !== undefined && { tool_calls }),\n }),\n );\n\n return await callChatApi({\n api,\n body: {\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...extraMetadata.body,\n ...chatRequest.body,\n ...(chatRequest.functions !== undefined && {\n functions: chatRequest.functions,\n }),\n ...(chatRequest.function_call !== undefined && {\n function_call: chatRequest.function_call,\n }),\n ...(chatRequest.tools !== undefined && {\n tools: chatRequest.tools,\n }),\n ...(chatRequest.tool_choice !== undefined && {\n tool_choice: chatRequest.tool_choice,\n }),\n },\n streamProtocol,\n credentials: extraMetadata.credentials,\n headers: {\n ...extraMetadata.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef,\n restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n mutate(previousMessages);\n }\n },\n onResponse,\n onUpdate(merged, data) {\n mutate([...chatRequest.messages, ...merged]);\n mutateStreamData([...(existingData || []), ...(data || [])]);\n },\n onFinish,\n generateId,\n onToolCall,\n fetch,\n });\n};\n\nlet uniqueId = 0;\n\nconst store: Record<string, Message[] | undefined> = {};\n\n/**\nCheck if the message is an assistant message with completed tool calls.\nThe message must have at least one tool invocation and all tool invocations\nmust have a result.\n */\nfunction isAssistantMessageWithCompletedToolCalls(message: Message) {\n return (\n message.role === 'assistant' &&\n message.toolInvocations &&\n message.toolInvocations.length > 0 &&\n message.toolInvocations.every(toolInvocation => 'result' in toolInvocation)\n );\n}\n\n/**\nReturns the number of trailing assistant messages in the array.\n */\nfunction countTrailingAssistantMessages(messages: Message[]) {\n let count = 0;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n count++;\n } else {\n break;\n }\n }\n\n return count;\n}\n\n/**\n * @deprecated Use `useChat` from `@ai-sdk/svelte` instead.\n */\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages = [],\n initialInput = '',\n sendExtraMessageFields,\n experimental_onFunctionCall,\n experimental_onToolCall,\n streamMode,\n streamProtocol,\n onResponse,\n onFinish,\n onError,\n onToolCall,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = false,\n maxToolRoundtrips = 0,\n}: UseChatOptions = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // streamMode is deprecated, use streamProtocol instead.\n if (streamMode) {\n streamProtocol ??= streamMode === 'text' ? 'text' : undefined;\n }\n\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 {\n data,\n mutate: originalMutate,\n isLoading: isSWRLoading,\n } = useSWR<Message[]>(key, {\n fetcher: () => store[key] || initialMessages,\n fallbackData: initialMessages,\n });\n\n const streamData = writable<JSONValue[] | undefined>(undefined);\n\n const loading = writable<boolean>(false);\n\n // Force the `data` to be `initialMessages` if it's `undefined`.\n data.set(initialMessages);\n\n const mutate = (data: Message[]) => {\n store[key] = data;\n return originalMutate(data);\n };\n\n // Because of the `fallbackData` option, the `data` will never be `undefined`.\n const messages = data as Writable<Message[]>;\n\n // Abort controller to cancel the current API call.\n let abortController: AbortController | null = null;\n\n const extraMetadata = {\n credentials,\n headers,\n body,\n };\n\n const error = writable<undefined | Error>(undefined);\n\n // Actual mutation hook to send messages to the API endpoint and update the\n // chat state.\n async function triggerRequest(chatRequest: ChatRequest) {\n const messagesSnapshot = get(messages);\n const messageCount = messagesSnapshot.length;\n\n try {\n error.set(undefined);\n loading.set(true);\n abortController = new AbortController();\n\n await processChatStream({\n getStreamedResponse: () =>\n getStreamedResponse(\n api,\n chatRequest,\n mutate,\n data => {\n streamData.set(data);\n },\n get(streamData),\n extraMetadata,\n get(messages),\n abortController,\n generateId,\n streamProtocol,\n onFinish,\n onResponse,\n onToolCall,\n sendExtraMessageFields,\n fetch,\n keepLastMessageOnError,\n ),\n experimental_onFunctionCall,\n experimental_onToolCall,\n updateChatRequest: chatRequestParam => {\n chatRequest = chatRequestParam;\n },\n getCurrentMessages: () => get(messages),\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.set(err as Error);\n } finally {\n loading.set(false);\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const newMessagesSnapshot = get(messages);\n\n const lastMessage = newMessagesSnapshot[newMessagesSnapshot.length - 1];\n if (\n // ensure we actually have new messages (to prevent infinite loops in case of errors):\n newMessagesSnapshot.length > messageCount &&\n // ensure there is a last message:\n lastMessage != null &&\n // check if the feature is enabled:\n maxToolRoundtrips > 0 &&\n // check that roundtrip is possible:\n isAssistantMessageWithCompletedToolCalls(lastMessage) &&\n // limit the number of automatic roundtrips:\n countTrailingAssistantMessages(newMessagesSnapshot) <= maxToolRoundtrips\n ) {\n await triggerRequest({ messages: newMessagesSnapshot });\n }\n }\n\n const append: UseChatHelpers['append'] = async (\n message: Message | CreateMessage,\n {\n options,\n functions,\n function_call,\n tools,\n tool_choice,\n data,\n headers,\n body,\n }: ChatRequestOptions = {},\n ) => {\n if (!message.id) {\n message.id = generateId();\n }\n\n const requestOptions = {\n headers: headers ?? options?.headers,\n body: body ?? options?.body,\n };\n\n const chatRequest: ChatRequest = {\n messages: get(messages).concat(message as Message),\n options: requestOptions,\n headers: requestOptions.headers,\n body: requestOptions.body,\n data,\n ...(functions !== undefined && { functions }),\n ...(function_call !== undefined && { function_call }),\n ...(tools !== undefined && { tools }),\n ...(tool_choice !== undefined && { tool_choice }),\n };\n return triggerRequest(chatRequest);\n };\n\n const reload: UseChatHelpers['reload'] = async ({\n options,\n functions,\n function_call,\n tools,\n tool_choice,\n data,\n headers,\n body,\n }: ChatRequestOptions = {}) => {\n const messagesSnapshot = get(messages);\n if (messagesSnapshot.length === 0) return null;\n\n const requestOptions = {\n headers: headers ?? options?.headers,\n body: body ?? options?.body,\n };\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messagesSnapshot.at(-1);\n if (lastMessage?.role === 'assistant') {\n const chatRequest: ChatRequest = {\n messages: messagesSnapshot.slice(0, -1),\n options: requestOptions,\n headers: requestOptions.headers,\n body: requestOptions.body,\n data,\n ...(functions !== undefined && { functions }),\n ...(function_call !== undefined && { function_call }),\n ...(tools !== undefined && { tools }),\n ...(tool_choice !== undefined && { tool_choice }),\n };\n\n return triggerRequest(chatRequest);\n }\n\n const chatRequest: ChatRequest = {\n messages: messagesSnapshot,\n options: requestOptions,\n headers: requestOptions.headers,\n body: requestOptions.body,\n data,\n };\n\n return triggerRequest(chatRequest);\n };\n\n const stop = () => {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n };\n\n const setMessages = (\n messagesArg: Message[] | ((messages: Message[]) => Message[]),\n ) => {\n if (typeof messagesArg === 'function') {\n messagesArg = messagesArg(get(messages));\n }\n\n mutate(messagesArg);\n };\n\n const input = writable(initialInput);\n\n const handleSubmit = (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n ) => {\n event?.preventDefault?.();\n const inputValue = get(input);\n\n if (!inputValue && !options.allowEmptySubmit) return;\n\n const requestOptions = {\n headers: options.headers ?? options.options?.headers,\n body: options.body ?? options.options?.body,\n };\n\n const chatRequest: ChatRequest = {\n messages:\n !inputValue && options.allowEmptySubmit\n ? get(messages)\n : get(messages).concat({\n id: generateId(),\n content: inputValue,\n role: 'user',\n createdAt: new Date(),\n } as Message),\n options: requestOptions,\n body: requestOptions.body,\n headers: requestOptions.headers,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\n\n input.set('');\n };\n\n const isLoading = derived(\n [isSWRLoading, loading],\n ([$isSWRLoading, $loading]) => {\n return $isSWRLoading || $loading;\n },\n );\n\n const addToolResult = ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => {\n const messagesSnapshot = get(messages) ?? [];\n const updatedMessages = messagesSnapshot.map((message, index, arr) =>\n // update the tool calls in the last assistant message:\n index === arr.length - 1 &&\n message.role === 'assistant' &&\n message.toolInvocations\n ? {\n ...message,\n toolInvocations: message.toolInvocations.map(toolInvocation =>\n toolInvocation.toolCallId === toolCallId\n ? { ...toolInvocation, result }\n : toolInvocation,\n ),\n }\n : message,\n );\n\n messages.set(updatedMessages);\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = updatedMessages[updatedMessages.length - 1];\n\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: updatedMessages });\n }\n };\n\n return {\n messages,\n error,\n append,\n reload,\n stop,\n setMessages,\n input,\n handleSubmit,\n isLoading,\n data: streamData,\n addToolResult,\n };\n}\n","var P = Object.defineProperty;\nvar F = (r, e, t) => e in r ? P(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;\nvar h = (r, e, t) => (F(r, typeof e != \"symbol\" ? e + \"\" : e, t), t);\nclass I {\n constructor() {\n /**\n * Stores the list of active listener.s\n */\n h(this, \"listeners\", /* @__PURE__ */ new Map());\n }\n /**\n * Subscribes a given listener.\n */\n subscribe(e, t) {\n this.listeners.has(e) || this.listeners.set(e, []), !this.listeners.get(e).includes(t) && this.listeners.get(e).push(t);\n }\n /**\n * Unsubscribes the given listener.\n */\n unsubscribe(e, t) {\n this.listeners.has(e) && this.listeners.get(e).includes(t) && (this.listeners.get(e).splice(this.listeners.get(e).indexOf(t), 1), this.listeners.get(e).length === 0 && this.listeners.delete(e));\n }\n /**\n * Emits an event to all active listeners.\n */\n emit(e, t) {\n this.listeners.has(e) && this.listeners.get(e).forEach((s) => s(t));\n }\n}\nconst L = {\n broadcast: !1\n}, S = {\n broadcast: !1\n};\nclass O {\n /**\n * Creates the cache item given the data and expiration at.\n */\n constructor({ data: e, expiresAt: t = null }) {\n /**\n * Determines the data that's stored in the cache.\n */\n h(this, \"data\");\n /**\n * Determines the expiration date for the given set of data.\n */\n h(this, \"expiresAt\");\n this.data = e, this.expiresAt = t;\n }\n /**\n * Determines if the current cache item is still being resolved.\n * This returns true if data is a promise, or false if type `D`.\n */\n isResolving() {\n return this.data instanceof Promise;\n }\n /**\n * Determines if the given cache item has expired.\n */\n hasExpired() {\n return this.expiresAt === null || this.expiresAt < /* @__PURE__ */ new Date();\n }\n /**\n * Set the expiration time of the given cache item relative to now.\n */\n expiresIn(e) {\n return this.expiresAt = /* @__PURE__ */ new Date(), this.expiresAt.setMilliseconds(this.expiresAt.getMilliseconds() + e), this;\n }\n}\nclass q {\n constructor() {\n /**\n * Stores the elements of the cache in a key-value pair.\n */\n h(this, \"elements\", /* @__PURE__ */ new Map());\n /**\n * Stores the event target instance to dispatch and receive events.\n */\n h(this, \"event\", new I());\n }\n /**\n * Resolves the promise and replaces the Promise to the resolved data.\n * It also broadcasts the value change if needed or deletes the key if\n * the value resolves to undefined or null.\n */\n resolve(e, t) {\n Promise.resolve(t.data).then((s) => {\n if (s == null)\n return this.remove(e);\n t.data = s, this.broadcast(e, s);\n });\n }\n /**\n * Gets an element from the cache.\n *\n * It is assumed the item always exist when\n * you get it. Use the has method to check\n * for the existence of it.\n */\n get(e) {\n return this.elements.get(e);\n }\n /**\n * Sets an element to the cache.\n */\n set(e, t) {\n this.elements.set(e, t), this.resolve(e, t);\n }\n /**\n * Removes an key-value pair from the cache.\n */\n remove(e, t) {\n const { broadcast: s } = { ...L, ...t };\n s && this.broadcast(e, void 0), this.elements.delete(e);\n }\n /**\n * Removes all the key-value pairs from the cache.\n */\n clear(e) {\n const { broadcast: t } = { ...S, ...e };\n if (t)\n for (const s of this.elements.keys())\n this.broadcast(s, void 0);\n this.elements.clear();\n }\n /**\n * Determines if the given key exists\n * in the cache.\n */\n has(e) {\n return this.elements.has(e);\n }\n /**\n * Subscribes the callback to the given key.\n */\n subscribe(e, t) {\n this.event.subscribe(e, t);\n }\n /**\n * Unsubscribes to the given key events.\n */\n unsubscribe(e, t) {\n this.event.unsubscribe(e, t);\n }\n /**\n * Broadcasts a value change on all subscribed instances.\n */\n broadcast(e, t) {\n this.event.emit(e, t);\n }\n}\nconst x = {\n cache: new q(),\n errors: new I(),\n fetcher: async (r) => {\n const e = await fetch(r);\n if (!e.ok)\n throw Error(\"Not a 2XX response.\");\n return e.json();\n },\n fallbackData: void 0,\n loadInitialCache: !0,\n revalidateOnStart: !0,\n dedupingInterval: 2e3,\n revalidateOnFocus: !0,\n focusThrottleInterval: 5e3,\n revalidateOnReconnect: !0,\n reconnectWhen: (r, { enabled: e }) => e && typeof window < \"u\" ? (window.addEventListener(\"online\", r), () => window.removeEventListener(\"online\", r)) : () => {\n },\n focusWhen: (r, { enabled: e, throttleInterval: t }) => {\n if (e && typeof window < \"u\") {\n let s = null;\n const i = () => {\n const a = Date.now();\n (s === null || a - s > t) && (s = a, r());\n };\n return window.addEventListener(\"focus\", i), () => window.removeEventListener(\"focus\", i);\n }\n return () => {\n };\n },\n revalidateFunction: void 0\n}, E = {\n ...x,\n force: !1\n}, T = {\n revalidate: !0,\n revalidateOptions: { ...E },\n revalidateFunction: void 0\n}, X = {\n broadcast: !1\n};\nclass H {\n /**\n * Creates a new instance of SWR.\n */\n constructor(e) {\n /**\n * Stores the options of the SWR.\n */\n h(this, \"options\");\n this.options = { ...x, ...e };\n }\n /**\n * Gets the cache of the SWR.\n */\n get cache() {\n return this.options.cache;\n }\n /**\n * Gets the cache of the SWR.\n */\n get errors() {\n return this.options.errors;\n }\n /**\n * Requests the data using the provided fetcher.\n */\n async requestData(e, t) {\n return await Promise.resolve(t(e)).catch((s) => {\n throw this.errors.emit(e, s), s;\n });\n }\n /**\n * Resolves the given to a SWRKey or undefined.\n */\n resolveKey(e) {\n if (typeof e == \"function\")\n try {\n return e();\n } catch {\n return;\n }\n return e;\n }\n /**\n * Clear the specified keys from the cache. If no keys\n * are specified, it clears all the cache keys.\n */\n clear(e, t) {\n const s = { ...X, ...t };\n if (e == null)\n return this.cache.clear(s);\n if (!Array.isArray(e))\n return this.cache.remove(e, s);\n for (const i of e)\n this.cache.remove(i, s);\n }\n /**\n * Revalidates the key and mutates the cache if needed.\n */\n async revalidate(e, t) {\n if (!e)\n throw new Error(\"[Revalidate] Key issue: ${key}\");\n const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {\n ...E,\n fetcher: s,\n dedupingInterval: i,\n ...t\n };\n if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {\n const c = this.requestData(e, o), l = c.catch(() => {\n });\n return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c;\n }\n return this.getWait(e);\n }\n /**\n * Mutates the data of a given key with a new value.\n * This is used to replace the cache contents of the\n * given key manually.\n */\n async mutate(e, t, s) {\n if (!e)\n throw new Error(\"[Mutate] Key issue: ${key}\");\n const {\n revalidate: i,\n revalidateOptions: a,\n revalidateFunction: o\n } = {\n ...T,\n ...s\n };\n let n;\n if (typeof t == \"function\") {\n let c;\n if (this.cache.has(e)) {\n const l = this.cache.get(e);\n l.isResolving() || (c = l.data);\n }\n n = t(c);\n } else\n n = t;\n return this.cache.set(e, new O({ data: n })), i ? await ((o == null ? void 0 : o(e, a)) ?? this.revalidate(e, a)) : n;\n }\n /**\n * Gets the data of the given key. Keep in mind\n * this data will be stale and revalidate in the background\n * unless specified otherwise.\n */\n subscribeData(e, t) {\n if (e) {\n const s = (i) => t(i);\n return this.cache.subscribe(e, s), () => this.cache.unsubscribe(e, s);\n }\n return () => {\n };\n }\n /**\n * Subscribes to errors on the given key.\n */\n subscribeErrors(e, t) {\n if (e) {\n const s = (i) => t(i);\n return this.errors.subscribe(e, s), () => this.errors.unsubscribe(e, s);\n }\n return () => {\n };\n }\n /**\n * Gets the current cached data of the given key.\n * This does not trigger any revalidation nor mutation\n * of the data.\n * - If the data has never been validated\n * (there is no cache) it will return undefined.\n * - If the item is pending to resolve (there is a request\n * pending to resolve) it will return undefined.\n */\n get(e) {\n if (e && this.cache.has(e)) {\n const t = this.cache.get(e);\n if (!t.isResolving())\n return t.data;\n }\n }\n /**\n * Gets an element from the cache. The difference\n * with the get is that this method returns a promise\n * that will resolve the the value. If there's no item\n * in the cache, it will wait for it before resolving.\n */\n getWait(e) {\n return new Promise((t, s) => {\n const i = this.subscribeData(e, (n) => {\n if (i(), n !== void 0)\n return t(n);\n }), a = this.subscribeErrors(e, (n) => {\n if (a(), n !== void 0)\n return s(n);\n }), o = this.get(e);\n if (o !== void 0)\n return t(o);\n });\n }\n /**\n * Use a SWR value given the key and\n * subscribe to future changes.\n */\n subscribe(e, t, s, i) {\n const {\n fetcher: a,\n fallbackData: o,\n loadInitialCache: n,\n revalidateOnStart: c,\n dedupingInterval: l,\n revalidateOnFocus: A,\n focusThrottleInterval: C,\n revalidateOnReconnect: R,\n reconnectWhen: W,\n focusWhen: D,\n revalidateFunction: d\n } = {\n // Current instance options\n // (includes default options)\n ...this.options,\n // Current call options.\n ...i\n }, K = (m) => (d == null ? void 0 : d(this.resolveKey(e), m)) ?? this.revalidate(this.resolveKey(e), m), f = () => K({ fetcher: a, dedupingInterval: l }), u = n ? this.get(this.resolveKey(e)) : o ?? void 0, g = c ? f() : Promise.resolve(void 0), M = u ? Promise.resolve(u) : g;\n u && (t == null || t(u));\n const v = t ? this.subscribeData(this.resolveKey(e), t) : void 0, b = s ? this.subscribeErrors(this.resolveKey(e), s) : void 0, p = D(f, {\n throttleInterval: C,\n enabled: A\n }), w = W(f, {\n enabled: R\n });\n return { unsubscribe: () => {\n v == null || v(), b == null || b(), p == null || p(), w == null || w();\n }, dataPromise: M, revalidatePromise: g };\n }\n}\nexport {\n O as CacheItem,\n q as DefaultCache,\n I as DefaultSWREventManager,\n H as SWR,\n S as defaultCacheClearOptions,\n L as defaultCacheRemoveOptions,\n X as defaultClearOptions,\n T as defaultMutateOptions,\n x as defaultOptions,\n E as defaultRevalidateOptions\n};\n","import { SWR as _ } from \"swrev\";\nimport { beforeUpdate as w, onDestroy as E } from \"svelte\";\nfunction p() {\n}\nfunction D(t) {\n return t();\n}\nfunction q(t) {\n t.forEach(D);\n}\nfunction x(t) {\n return typeof t == \"function\";\n}\nfunction K(t, e) {\n return t != t ? e == e : t !== e || t && typeof t == \"object\" || typeof t == \"function\";\n}\nfunction z(t, ...e) {\n if (t == null) {\n for (const r of e)\n r(void 0);\n return p;\n }\n const n = t.subscribe(...e);\n return n.unsubscribe ? () => n.unsubscribe() : n;\n}\nconst v = [];\nfunction A(t, e) {\n return {\n subscribe: y(t, e).subscribe\n };\n}\nfunction y(t, e = p) {\n let n;\n const r = /* @__PURE__ */ new Set();\n function i(u) {\n if (K(t, u) && (t = u, n)) {\n const f = !v.length;\n for (const s of r)\n s[1](), v.push(s, t);\n if (f) {\n for (let s = 0; s < v.length; s += 2)\n v[s][0](v[s + 1]);\n v.length = 0;\n }\n }\n }\n function a(u) {\n i(u(t));\n }\n function d(u, f = p) {\n const s = [u, f];\n return r.add(s), r.size === 1 && (n = e(i, a) || p), u(t), () => {\n r.delete(s), r.size === 0 && n && (n(), n = null);\n };\n }\n return { set: i, update: a, subscribe: d };\n}\nfunction S(t, e, n) {\n const r = !Array.isArray(t), i = r ? [t] : t;\n if (!i.every(Boolean))\n throw new Error(\"derived() expects stores as input, got a falsy value\");\n const a = e.length < 2;\n return A(n, (d, u) => {\n let f = !1;\n const s = [];\n let h = 0, o = p;\n const l = () => {\n if (h)\n return;\n o();\n const b = e(r ? s[0] : s, d, u);\n a ? d(b) : o = x(b) ? b : p;\n }, g = i.map(\n (b, m) => z(\n b,\n (R) => {\n s[m] = R, h &= ~(1 << m), f && l();\n },\n () => {\n h |= 1 << m;\n }\n )\n );\n return f = !0, l(), function() {\n q(g), o(), f = !1;\n };\n });\n}\nclass O extends _ {\n /**\n * Svelte specific use of SWR.\n */\n useSWR(e, n) {\n let r;\n const i = y(void 0, () => () => r == null ? void 0 : r()), a = y(void 0, () => () => r == null ? void 0 : r());\n w(() => {\n const o = (g) => {\n a.set(void 0), i.set(g);\n }, l = (g) => a.set(g);\n r || (r = this.subscribe(e, o, l, {\n loadInitialCache: !0,\n ...n\n }).unsubscribe);\n }), E(() => r == null ? void 0 : r());\n const d = (o, l) => this.mutate(this.resolveKey(e), o, {\n revalidateOptions: n,\n ...l\n }), u = (o) => this.revalidate(this.resolveKey(e), { ...n, ...o }), f = (o) => this.clear(this.resolveKey(e), o), s = S([i, a], ([o, l]) => o === void 0 && l === void 0), h = S([i, a], ([o, l]) => o !== void 0 && l === void 0);\n return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h };\n }\n}\nconst W = (t) => new O(t);\nlet c = W();\nconst C = (t) => (c = W(t), c), I = (t, e) => c.subscribeData(t, e), L = (t, e) => c.subscribeErrors(t, e), U = (t) => c.get(t), V = (t) => c.getWait(t), $ = (t, e, n, r) => c.subscribe(t, e, n, r), F = (t, e) => c.useSWR(t, e), G = (t, e, n) => c.mutate(t, e, n), H = (t, e) => c.revalidate(t, e), J = (t, e) => c.clear(t, e);\nexport {\n O as SSWR,\n J as clear,\n C as createDefaultSWR,\n W as createSWR,\n U as get,\n V as getOrWait,\n G as mutate,\n H as revalidate,\n I as subscribe,\n L as subscribeErrors,\n c as swr,\n $ as use,\n F as useSWR\n};\n","import type {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n} from '@ai-sdk/ui-utils';\nimport { callCompletionApi } from '@ai-sdk/ui-utils';\nimport { useSWR } from 'sswr';\nimport { Readable, Writable, derived, get, writable } from 'svelte/store';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: Readable<string>;\n /** The error object of the API request */\n error: Readable<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: Writable<string>;\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n /** Whether the API request is in progress */\n isLoading: Readable<boolean | undefined>;\n\n /** Additional data added on the server via StreamData */\n data: Readable<JSONValue[] | undefined>;\n};\n\nlet uniqueId = 0;\n\nconst store: Record<string, any> = {};\n\n/**\n * @deprecated Use `useCompletion` from `@ai-sdk/svelte` instead.\n */\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamMode,\n streamProtocol,\n onResponse,\n onFinish,\n onError,\n fetch,\n}: UseCompletionOptions = {}): UseCompletionHelpers {\n // streamMode is deprecated, use streamProtocol instead.\n if (streamMode) {\n streamProtocol ??= streamMode === 'text' ? 'text' : undefined;\n }\n\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 {\n data,\n mutate: originalMutate,\n isLoading: isSWRLoading,\n } = useSWR<string>(key, {\n fetcher: () => store[key] || initialCompletion,\n fallbackData: initialCompletion,\n });\n\n const streamData = writable<JSONValue[] | undefined>(undefined);\n\n const loading = writable<boolean>(false);\n\n // Force the `data` to be `initialCompletion` if it's `undefined`.\n data.set(initialCompletion);\n\n const mutate = (data: string) => {\n store[key] = data;\n return originalMutate(data);\n };\n\n // Because of the `fallbackData` option, the `data` will never be `undefined`.\n const completion = data as Writable<string>;\n\n const error = writable<undefined | Error>(undefined);\n\n let abortController: AbortController | null = null;\n\n const complete: UseCompletionHelpers['complete'] = async (\n prompt: string,\n options?: RequestOptions,\n ) => {\n const existingData = get(streamData);\n return callCompletionApi({\n api,\n prompt,\n credentials,\n headers: {\n ...headers,\n ...options?.headers,\n },\n body: {\n ...body,\n ...options?.body,\n },\n streamProtocol,\n setCompletion: mutate,\n setLoading: loadingState => loading.set(loadingState),\n setError: err => error.set(err),\n setAbortController: controller => {\n abortController = controller;\n },\n onResponse,\n onFinish,\n onError,\n onData(data) {\n streamData.set([...(existingData || []), ...(data || [])]);\n },\n fetch,\n });\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 = writable(initialInput);\n\n const handleSubmit = (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n\n const inputValue = get(input);\n return inputValue ? complete(inputValue) : undefined;\n };\n\n const isLoading = derived(\n [isSWRLoading, loading],\n ([$isSWRLoading, $loading]) => {\n return $isSWRLoading || $loading;\n },\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","import { isAbortError } from '@ai-sdk/provider-utils';\nimport type {\n AssistantStatus,\n CreateMessage,\n Message,\n UseAssistantOptions,\n} from '@ai-sdk/ui-utils';\nimport { generateId, readDataStream } from '@ai-sdk/ui-utils';\nimport { Readable, Writable, get, writable } from 'svelte/store';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nlet uniqueId = 0;\n\nconst store: Record<string, any> = {};\n\nexport type UseAssistantHelpers = {\n /**\n * The current array of chat messages.\n */\n messages: Readable<Message[]>;\n\n /**\n * Update the message store with a new array of messages.\n */\n setMessages: (messages: Message[]) => void;\n\n /**\n * The current thread ID.\n */\n threadId: Readable<string | undefined>;\n\n /**\n * The current value of the input field.\n */\n input: Writable<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?: { data?: Record<string, string> },\n ) => Promise<void>;\n\n /**\nAbort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Form submission handler that automatically resets the input field and appends a user message.\n */\n submitMessage: (\n event?: { preventDefault?: () => void },\n requestOptions?: { data?: Record<string, string> },\n ) => Promise<void>;\n\n /**\n * The current status of the assistant. This can be used to show a loading indicator.\n */\n status: Readable<AssistantStatus>;\n\n /**\n * The error thrown during the assistant message processing, if any.\n */\n error: Readable<undefined | Error>;\n};\n\n/**\n * @deprecated Use `useAssistant` from `@ai-sdk/svelte` instead.\n */\nexport function useAssistant({\n api,\n threadId: threadIdParam,\n credentials,\n headers,\n body,\n onError,\n fetch,\n}: UseAssistantOptions): UseAssistantHelpers {\n // Generate a unique thread ID\n const threadIdStore = writable<string | undefined>(threadIdParam);\n\n // Initialize message, input, status, and error stores\n const key = `${api}|${threadIdParam ?? `completion-${uniqueId++}`}`;\n const messages = writable<Message[]>(store[key] || []);\n const input = writable('');\n const status = writable<AssistantStatus>('awaiting_message');\n const error = writable<undefined | Error>(undefined);\n\n // To manage aborting the current fetch request\n let abortController: AbortController | null = null;\n\n // Update the message store\n const mutateMessages = (newMessages: Message[]) => {\n store[key] = newMessages;\n messages.set(newMessages);\n };\n\n // Function to handle API calls and state management\n async function append(\n message: Message | CreateMessage,\n requestOptions?: { data?: Record<string, string> },\n ) {\n status.set('in_progress');\n abortController = new AbortController(); // Initialize a new AbortController\n\n // Add the new message to the existing array\n mutateMessages([\n ...get(messages),\n { ...message, id: message.id ?? generateId() },\n ]);\n\n input.set('');\n\n try {\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n credentials,\n signal: abortController.signal,\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify({\n ...body,\n // always use user-provided threadId when available:\n threadId: threadIdParam ?? get(threadIdStore) ?? null,\n message: message.content,\n\n // optional request data:\n data: requestOptions?.data,\n }),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the assistant response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n // Read the streamed response data\n for await (const { type, value } of readDataStream(\n response.body.getReader(),\n )) {\n switch (type) {\n case 'assistant_message': {\n mutateMessages([\n ...get(messages),\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case 'text': {\n // text delta - add to last message:\n mutateMessages(\n get(messages).map((msg, index, array) => {\n if (index === array.length - 1) {\n return { ...msg, content: msg.content + value };\n }\n return msg;\n }),\n );\n break;\n }\n\n case 'data_message': {\n mutateMessages([\n ...get(messages),\n {\n id: value.id ?? generateId(),\n role: 'data',\n content: '',\n data: value.data,\n },\n ]);\n break;\n }\n\n case 'assistant_control_data': {\n threadIdStore.set(value.threadId);\n\n mutateMessages(\n get(messages).map((msg, index, array) => {\n if (index === array.length - 1) {\n return { ...msg, id: value.messageId };\n }\n return msg;\n }),\n );\n\n break;\n }\n\n case 'error': {\n error.set(new Error(value));\n break;\n }\n }\n }\n } catch (err) {\n // Ignore abort errors as they are expected when the user cancels the request:\n if (isAbortError(error) && abortController?.signal?.aborted) {\n abortController = null;\n return;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n error.set(err as Error);\n } finally {\n abortController = null;\n status.set('awaiting_message');\n }\n }\n\n function setMessages(messages: Message[]) {\n mutateMessages(messages);\n }\n\n function stop() {\n if (abortController) {\n abortController.abort();\n abortController = null;\n }\n }\n\n // Function to handle form submission\n async function submitMessage(\n event?: { preventDefault?: () => void },\n requestOptions?: { data?: Record<string, string> },\n ) {\n event?.preventDefault?.();\n const inputValue = get(input);\n if (!inputValue) return;\n\n await append({ role: 'user', content: inputValue }, requestOptions);\n }\n\n return {\n messages,\n error,\n threadId: threadIdStore,\n input,\n append,\n submitMessage,\n status,\n setMessages,\n stop,\n };\n}\n"],"mappings":";AAUA;AAAA,EACE;AAAA,EACA,cAAc;AAAA,EACd;AAAA,OACK;;;ACdP,IAAI,IAAI,OAAO;AACf,IAAI,IAAI,CAAC,GAAG,GAAG,MAAM,KAAK,IAAI,EAAE,GAAG,GAAG,EAAE,YAAY,MAAI,cAAc,MAAI,UAAU,MAAI,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,IAAI;AAC7G,IAAI,IAAI,CAAC,GAAG,GAAG,OAAO,EAAE,GAAG,OAAO,KAAK,W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