ai 3.2.45 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +221 -21
- package/dist/index.d.ts +221 -21
- package/dist/index.js +640 -278
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +618 -266
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -8
- package/rsc/dist/index.d.ts +3 -3
- package/rsc/dist/rsc-server.d.mts +3 -3
- package/rsc/dist/rsc-server.mjs +1299 -1033
- package/rsc/dist/rsc-server.mjs.map +1 -1
- package/rsc/dist/rsc-shared.mjs +23 -45
- package/rsc/dist/rsc-shared.mjs.map +1 -1
- package/svelte/dist/index.js +1 -1
- package/svelte/dist/index.js.map +1 -1
- package/svelte/dist/index.mjs +1 -1
- package/svelte/dist/index.mjs.map +1 -1
package/rsc/dist/rsc-shared.mjs
CHANGED
@@ -148,40 +148,18 @@ function useStreamableValue(streamableValue) {
|
|
148
148
|
}
|
149
149
|
|
150
150
|
// rsc/shared-client/context.tsx
|
151
|
-
import * as
|
151
|
+
import * as React from "react";
|
152
152
|
import * as jsondiffpatch from "jsondiffpatch";
|
153
153
|
|
154
|
-
//
|
155
|
-
|
156
|
-
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
157
|
-
var R = [
|
158
|
-
async ({
|
159
|
-
c,
|
160
|
-
// current
|
161
|
-
n
|
162
|
-
// next
|
163
|
-
}) => {
|
164
|
-
const chunk = await n;
|
165
|
-
if (chunk.done) {
|
166
|
-
return chunk.value;
|
167
|
-
}
|
168
|
-
if (chunk.append) {
|
169
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
170
|
-
c,
|
171
|
-
/* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) })
|
172
|
-
] });
|
173
|
-
}
|
174
|
-
return /* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) });
|
175
|
-
}
|
176
|
-
][0];
|
177
|
-
var isFunction = (x) => typeof x === "function";
|
154
|
+
// util/is-function.ts
|
155
|
+
var isFunction = (value) => typeof value === "function";
|
178
156
|
|
179
157
|
// rsc/shared-client/context.tsx
|
180
|
-
import { jsx
|
181
|
-
var InternalUIStateProvider =
|
182
|
-
var InternalAIStateProvider =
|
183
|
-
var InternalActionProvider =
|
184
|
-
var InternalSyncUIStateProvider =
|
158
|
+
import { jsx } from "react/jsx-runtime";
|
159
|
+
var InternalUIStateProvider = React.createContext(null);
|
160
|
+
var InternalAIStateProvider = React.createContext(void 0);
|
161
|
+
var InternalActionProvider = React.createContext(null);
|
162
|
+
var InternalSyncUIStateProvider = React.createContext(null);
|
185
163
|
function InternalAIProvider({
|
186
164
|
children,
|
187
165
|
initialUIState,
|
@@ -190,13 +168,13 @@ function InternalAIProvider({
|
|
190
168
|
wrappedActions,
|
191
169
|
wrappedSyncUIState
|
192
170
|
}) {
|
193
|
-
if (!("use" in
|
171
|
+
if (!("use" in React)) {
|
194
172
|
throw new Error("Unsupported React version.");
|
195
173
|
}
|
196
|
-
const uiState =
|
174
|
+
const uiState = React.useState(initialUIState);
|
197
175
|
const setUIState = uiState[1];
|
198
|
-
const resolvedInitialAIStatePatch = initialAIStatePatch ?
|
199
|
-
initialAIState =
|
176
|
+
const resolvedInitialAIStatePatch = initialAIStatePatch ? React.use(initialAIStatePatch) : void 0;
|
177
|
+
initialAIState = React.useMemo(() => {
|
200
178
|
if (resolvedInitialAIStatePatch) {
|
201
179
|
return jsondiffpatch.patch(
|
202
180
|
jsondiffpatch.clone(initialAIState),
|
@@ -205,13 +183,13 @@ function InternalAIProvider({
|
|
205
183
|
}
|
206
184
|
return initialAIState;
|
207
185
|
}, [initialAIState, resolvedInitialAIStatePatch]);
|
208
|
-
const aiState =
|
186
|
+
const aiState = React.useState(initialAIState);
|
209
187
|
const setAIState = aiState[1];
|
210
|
-
const aiStateRef =
|
211
|
-
|
188
|
+
const aiStateRef = React.useRef(aiState[0]);
|
189
|
+
React.useEffect(() => {
|
212
190
|
aiStateRef.current = aiState[0];
|
213
191
|
}, [aiState[0]]);
|
214
|
-
const clientWrappedActions =
|
192
|
+
const clientWrappedActions = React.useMemo(
|
215
193
|
() => Object.fromEntries(
|
216
194
|
Object.entries(wrappedActions).map(([key, action]) => [
|
217
195
|
key,
|
@@ -238,7 +216,7 @@ function InternalAIProvider({
|
|
238
216
|
),
|
239
217
|
[wrappedActions]
|
240
218
|
);
|
241
|
-
const clientWrappedSyncUIStateAction =
|
219
|
+
const clientWrappedSyncUIStateAction = React.useMemo(() => {
|
242
220
|
if (!wrappedSyncUIState) {
|
243
221
|
return () => {
|
244
222
|
};
|
@@ -261,7 +239,7 @@ function InternalAIProvider({
|
|
261
239
|
}
|
262
240
|
};
|
263
241
|
}, [wrappedSyncUIState]);
|
264
|
-
return /* @__PURE__ */
|
242
|
+
return /* @__PURE__ */ jsx(InternalAIStateProvider.Provider, { value: aiState, children: /* @__PURE__ */ jsx(InternalUIStateProvider.Provider, { value: uiState, children: /* @__PURE__ */ jsx(InternalActionProvider.Provider, { value: clientWrappedActions, children: /* @__PURE__ */ jsx(
|
265
243
|
InternalSyncUIStateProvider.Provider,
|
266
244
|
{
|
267
245
|
value: clientWrappedSyncUIStateAction,
|
@@ -270,7 +248,7 @@ function InternalAIProvider({
|
|
270
248
|
) }) }) });
|
271
249
|
}
|
272
250
|
function useUIState() {
|
273
|
-
const state =
|
251
|
+
const state = React.useContext(InternalUIStateProvider);
|
274
252
|
if (state === null) {
|
275
253
|
throw new Error("`useUIState` must be used inside an <AI> provider.");
|
276
254
|
}
|
@@ -285,7 +263,7 @@ function useUIState() {
|
|
285
263
|
return state;
|
286
264
|
}
|
287
265
|
function useAIState(...args) {
|
288
|
-
const state =
|
266
|
+
const state = React.useContext(InternalAIStateProvider);
|
289
267
|
if (state === null) {
|
290
268
|
throw new Error("`useAIState` must be used inside an <AI> provider.");
|
291
269
|
}
|
@@ -303,7 +281,7 @@ function useAIState(...args) {
|
|
303
281
|
);
|
304
282
|
}
|
305
283
|
const key = args[0];
|
306
|
-
const setter =
|
284
|
+
const setter = React.useCallback(
|
307
285
|
typeof key === "undefined" ? state[1] : (newState) => {
|
308
286
|
if (isFunction(newState)) {
|
309
287
|
return state[1]((s) => {
|
@@ -322,11 +300,11 @@ function useAIState(...args) {
|
|
322
300
|
}
|
323
301
|
}
|
324
302
|
function useActions() {
|
325
|
-
const actions =
|
303
|
+
const actions = React.useContext(InternalActionProvider);
|
326
304
|
return actions;
|
327
305
|
}
|
328
306
|
function useSyncUIState() {
|
329
|
-
const syncUIState =
|
307
|
+
const syncUIState = React.useContext(
|
330
308
|
InternalSyncUIStateProvider
|
331
309
|
);
|
332
310
|
if (syncUIState === null) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../shared-client/streamable.tsx","../constants.ts","../shared-client/context.tsx","../utils.tsx"],"sourcesContent":["import { startTransition, useLayoutEffect, useState } from 'react';\nimport { STREAMABLE_VALUE_TYPE } from '../constants';\nimport type { StreamableValue } from '../types';\n\nfunction hasReadableValueSignature(value: unknown): value is StreamableValue {\n return !!(\n value &&\n typeof value === 'object' &&\n 'type' in value &&\n value.type === STREAMABLE_VALUE_TYPE\n );\n}\n\nfunction assertStreamableValue(\n value: unknown,\n): asserts value is StreamableValue {\n if (!hasReadableValueSignature(value)) {\n throw new Error(\n 'Invalid value: this hook only accepts values created via `createStreamableValue`.',\n );\n }\n}\n\nfunction isStreamableValue(value: unknown): value is StreamableValue {\n const hasSignature = hasReadableValueSignature(value);\n\n if (!hasSignature && typeof value !== 'undefined') {\n throw new Error(\n 'Invalid value: this hook only accepts values created via `createStreamableValue`.',\n );\n }\n\n return hasSignature;\n}\n\n/**\n * `readStreamableValue` takes a streamable value created via the `createStreamableValue().value` API,\n * and returns an async iterator.\n *\n * ```js\n * // Inside your AI action:\n *\n * async function action() {\n * 'use server'\n * const streamable = createStreamableValue();\n *\n * streamable.update(1);\n * streamable.update(2);\n * streamable.done(3);\n * // ...\n * return streamable.value;\n * }\n * ```\n *\n * And to read the value:\n *\n * ```js\n * const streamableValue = await action()\n * for await (const v of readStreamableValue(streamableValue)) {\n * console.log(v)\n * }\n * ```\n *\n * This logs out 1, 2, 3 on console.\n */\nexport function readStreamableValue<T = unknown>(\n streamableValue: StreamableValue<T>,\n): AsyncIterable<T | undefined> {\n assertStreamableValue(streamableValue);\n\n return {\n [Symbol.asyncIterator]() {\n let row: StreamableValue<T> | Promise<StreamableValue<T>> =\n streamableValue;\n let curr = row.curr;\n let done = false;\n let initial = true;\n\n return {\n async next() {\n if (done) return { value: curr, done: true };\n\n row = await row;\n\n if (typeof row.error !== 'undefined') {\n throw row.error;\n }\n if ('curr' in row || row.diff) {\n if (row.diff) {\n switch (row.diff[0]) {\n case 0:\n if (typeof curr !== 'string') {\n throw new Error(\n 'Invalid patch: can only append to string types. This is a bug in the AI SDK.',\n );\n } else {\n (curr as string) = curr + row.diff[1];\n }\n break;\n }\n } else {\n curr = row.curr;\n }\n\n // The last emitted { done: true } won't be used as the value\n // by the for await...of syntax.\n if (!row.next) {\n done = true;\n return {\n value: curr,\n done: false,\n };\n }\n }\n\n if (!row.next) {\n return {\n value: curr,\n done: true,\n };\n }\n\n row = row.next;\n if (initial) {\n initial = false;\n if (typeof curr === 'undefined') {\n // This is the initial chunk and there isn't an initial value yet.\n // Let's skip this one.\n return this.next();\n }\n }\n\n return {\n value: curr,\n done: false,\n };\n },\n };\n },\n };\n}\n\n/**\n * `useStreamableValue` is a React hook that takes a streamable value created via the `createStreamableValue().value` API,\n * and returns the current value, error, and pending state.\n *\n * This is useful for consuming streamable values received from a component's props. For example:\n *\n * ```js\n * function MyComponent({ streamableValue }) {\n * const [data, error, pending] = useStreamableValue(streamableValue);\n *\n * if (pending) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Data: {data}</div>;\n * }\n * ```\n */\nexport function useStreamableValue<T = unknown, Error = unknown>(\n streamableValue?: StreamableValue<T>,\n): [data: T | undefined, error: Error | undefined, pending: boolean] {\n const [curr, setCurr] = useState<T | undefined>(\n isStreamableValue(streamableValue) ? streamableValue.curr : undefined,\n );\n const [error, setError] = useState<Error | undefined>(\n isStreamableValue(streamableValue) ? streamableValue.error : undefined,\n );\n const [pending, setPending] = useState<boolean>(\n isStreamableValue(streamableValue) ? !!streamableValue.next : false,\n );\n\n useLayoutEffect(() => {\n if (!isStreamableValue(streamableValue)) return;\n\n let cancelled = false;\n\n const iterator = readStreamableValue(streamableValue);\n if (streamableValue.next) {\n startTransition(() => {\n if (cancelled) return;\n setPending(true);\n });\n }\n\n (async () => {\n try {\n for await (const value of iterator) {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setCurr(value);\n });\n }\n } catch (e) {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setError(e as Error);\n });\n } finally {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setPending(false);\n });\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [streamableValue]);\n\n return [curr, error, pending];\n}\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\nexport const DEV_DEFAULT_STREAMABLE_WARNING_TIME = 15 * 1000;\n","/* eslint-disable react-hooks/exhaustive-deps */\n'use client';\n\nimport * as React from 'react';\n\nimport * as jsondiffpatch from 'jsondiffpatch';\nimport type {\n InternalAIProviderProps,\n AIProvider,\n InferAIState,\n ValueOrUpdater,\n InferActions,\n InferUIState,\n} from '../types';\nimport { isFunction } from '../utils';\n\nconst InternalUIStateProvider = React.createContext<null | any>(null);\nconst InternalAIStateProvider = React.createContext<undefined | any>(undefined);\nconst InternalActionProvider = React.createContext<null | any>(null);\nconst InternalSyncUIStateProvider = React.createContext<null | any>(null);\n\nexport function InternalAIProvider({\n children,\n initialUIState,\n initialAIState,\n initialAIStatePatch,\n wrappedActions,\n wrappedSyncUIState,\n}: InternalAIProviderProps) {\n if (!('use' in React)) {\n throw new Error('Unsupported React version.');\n }\n\n const uiState = React.useState(initialUIState);\n const setUIState = uiState[1];\n\n const resolvedInitialAIStatePatch = initialAIStatePatch\n ? (React as any).use(initialAIStatePatch)\n : undefined;\n initialAIState = React.useMemo(() => {\n if (resolvedInitialAIStatePatch) {\n return jsondiffpatch.patch(\n jsondiffpatch.clone(initialAIState),\n resolvedInitialAIStatePatch,\n );\n }\n return initialAIState;\n }, [initialAIState, resolvedInitialAIStatePatch]);\n\n const aiState = React.useState(initialAIState);\n const setAIState = aiState[1];\n const aiStateRef = React.useRef(aiState[0]);\n\n React.useEffect(() => {\n aiStateRef.current = aiState[0];\n }, [aiState[0]]);\n\n const clientWrappedActions = React.useMemo(\n () =>\n Object.fromEntries(\n Object.entries(wrappedActions).map(([key, action]) => [\n key,\n async (...args: any) => {\n const aiStateSnapshot = aiStateRef.current;\n const [aiStateDelta, result] = await action(\n aiStateSnapshot,\n ...args,\n );\n (async () => {\n const delta = await aiStateDelta;\n if (delta !== undefined) {\n aiState[1](\n jsondiffpatch.patch(\n jsondiffpatch.clone(aiStateSnapshot),\n delta,\n ),\n );\n }\n })();\n return result;\n },\n ]),\n ),\n [wrappedActions],\n );\n\n const clientWrappedSyncUIStateAction = React.useMemo(() => {\n if (!wrappedSyncUIState) {\n return () => {};\n }\n\n return async () => {\n const aiStateSnapshot = aiStateRef.current;\n const [aiStateDelta, uiState] = await wrappedSyncUIState!(\n aiStateSnapshot,\n );\n\n if (uiState !== undefined) {\n setUIState(uiState);\n }\n\n const delta = await aiStateDelta;\n if (delta !== undefined) {\n const patchedAiState = jsondiffpatch.patch(\n jsondiffpatch.clone(aiStateSnapshot),\n delta,\n );\n setAIState(patchedAiState);\n }\n };\n }, [wrappedSyncUIState]);\n\n return (\n <InternalAIStateProvider.Provider value={aiState}>\n <InternalUIStateProvider.Provider value={uiState}>\n <InternalActionProvider.Provider value={clientWrappedActions}>\n <InternalSyncUIStateProvider.Provider\n value={clientWrappedSyncUIStateAction}\n >\n {children}\n </InternalSyncUIStateProvider.Provider>\n </InternalActionProvider.Provider>\n </InternalUIStateProvider.Provider>\n </InternalAIStateProvider.Provider>\n );\n}\n\nexport function useUIState<AI extends AIProvider = any>() {\n type T = InferUIState<AI, any>;\n\n const state = React.useContext<\n [T, (v: T | ((v_: T) => T)) => void] | null | undefined\n >(InternalUIStateProvider);\n if (state === null) {\n throw new Error('`useUIState` must be used inside an <AI> provider.');\n }\n if (!Array.isArray(state)) {\n throw new Error('Invalid state');\n }\n if (state[0] === undefined) {\n throw new Error(\n '`initialUIState` must be provided to `createAI` or `<AI>`',\n );\n }\n return state;\n}\n\n// TODO: How do we avoid causing a re-render when the AI state changes but you\n// are only listening to a specific key? We need useSES perhaps?\nfunction useAIState<AI extends AIProvider = any>(): [\n InferAIState<AI, any>,\n (newState: ValueOrUpdater<InferAIState<AI, any>>) => void,\n];\nfunction useAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): [\n InferAIState<AI, any>[typeof key],\n (newState: ValueOrUpdater<InferAIState<AI, any>[typeof key]>) => void,\n];\nfunction useAIState<AI extends AIProvider = any>(\n ...args: [] | [keyof InferAIState<AI, any>]\n) {\n type T = InferAIState<AI, any>;\n\n const state = React.useContext<\n [T, (newState: ValueOrUpdater<T>) => void] | null | undefined\n >(InternalAIStateProvider);\n if (state === null) {\n throw new Error('`useAIState` must be used inside an <AI> provider.');\n }\n if (!Array.isArray(state)) {\n throw new Error('Invalid state');\n }\n if (state[0] === undefined) {\n throw new Error(\n '`initialAIState` must be provided to `createAI` or `<AI>`',\n );\n }\n if (args.length >= 1 && typeof state[0] !== 'object') {\n throw new Error(\n 'When using `useAIState` with a key, the AI state must be an object.',\n );\n }\n\n const key = args[0];\n const setter = React.useCallback(\n typeof key === 'undefined'\n ? state[1]\n : (newState: ValueOrUpdater<T>) => {\n if (isFunction(newState)) {\n return state[1](s => {\n return { ...s, [key]: newState(s[key]) };\n });\n } else {\n return state[1]({ ...state[0], [key]: newState });\n }\n },\n [key],\n );\n\n if (args.length === 0) {\n return state;\n } else {\n return [state[0][args[0]], setter];\n }\n}\n\nexport function useActions<AI extends AIProvider = any>() {\n type T = InferActions<AI, any>;\n\n const actions = React.useContext<T>(InternalActionProvider);\n return actions;\n}\n\nexport function useSyncUIState() {\n const syncUIState = React.useContext<() => Promise<void>>(\n InternalSyncUIStateProvider,\n );\n\n if (syncUIState === null) {\n throw new Error('`useSyncUIState` must be used inside an <AI> provider.');\n }\n\n return syncUIState;\n}\n\nexport { useAIState };\n","import React, { Suspense } from 'react';\n\nexport function createResolvablePromise<T = any>() {\n let resolve: (value: T) => void, reject: (error: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n\n// Use the name `R` for `Row` as it will be shorter in the RSC payload.\nconst R = [\n (async ({\n c, // current\n n, // next\n }: {\n c: React.ReactNode;\n n: Promise<any>;\n }) => {\n const chunk = await n;\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {c}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<any>;\n }>,\n][0];\n\nexport function createSuspensedChunk(initialValue: React.ReactNode) {\n const { promise, resolve, reject } = createResolvablePromise();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ) as React.ReactNode,\n resolve,\n reject,\n };\n}\n\nexport const isFunction = (x: unknown): x is Function =>\n typeof x === 'function';\n\nexport const consumeStream = async (stream: ReadableStream) => {\n const reader = stream.getReader();\n while (true) {\n const { done } = await reader.read();\n if (done) break;\n }\n};\n"],"mappings":";;;AAAA,SAAS,iBAAiB,iBAAiB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AClB,QAAM,SAAe;AAAA,IACnB,OAAO,QAAQ,cACX,MAAM,CAAC,IACP,CAAC,aAAgC;AAC/B,UAAI,WAAW,QAAQ,GAAG;AACxB,eAAO,MAAM,CAAC,EAAE,OAAK;AACnB,iBAAO,EAAE,GAAG,GAAG,CAAC,GAAG,GAAG,SAAS,EAAE,GAAG,CAAC,EAAE;AAAA,QACzC,CAAC;AAAA,MACH,OAAO;AACL,eAAO,MAAM,CAAC,EAAE,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,SAAS,CAAC;AAAA,MAClD;AAAA,IACF;AAAA,IACJ,CAAC,GAAG;AAAA,EACN;AAEA,MAAI,KAAK,WAAW,GAAG;AACrB,WAAO;AAAA,EACT,OAAO;AACL,WAAO,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,MAAM;AAAA,EACnC;AACF;AAEO,SAAS,aAA0C;AAGxD,QAAM,UAAgB,kBAAc,sBAAsB;AAC1D,SAAO;AACT;AAEO,SAAS,iBAAiB;AAC/B,QAAM,cAAoB;AAAA,IACxB;AAAA,EACF;AAEA,MAAI,gBAAgB,MAAM;AACxB,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AAEA,SAAO;AACT;","names":["React","jsx","React","uiState"]}
|
1
|
+
{"version":3,"sources":["../shared-client/streamable.tsx","../constants.ts","../shared-client/context.tsx","../../util/is-function.ts"],"sourcesContent":["import { startTransition, useLayoutEffect, useState } from 'react';\nimport { STREAMABLE_VALUE_TYPE } from '../constants';\nimport type { StreamableValue } from '../types';\n\nfunction hasReadableValueSignature(value: unknown): value is StreamableValue {\n return !!(\n value &&\n typeof value === 'object' &&\n 'type' in value &&\n value.type === STREAMABLE_VALUE_TYPE\n );\n}\n\nfunction assertStreamableValue(\n value: unknown,\n): asserts value is StreamableValue {\n if (!hasReadableValueSignature(value)) {\n throw new Error(\n 'Invalid value: this hook only accepts values created via `createStreamableValue`.',\n );\n }\n}\n\nfunction isStreamableValue(value: unknown): value is StreamableValue {\n const hasSignature = hasReadableValueSignature(value);\n\n if (!hasSignature && typeof value !== 'undefined') {\n throw new Error(\n 'Invalid value: this hook only accepts values created via `createStreamableValue`.',\n );\n }\n\n return hasSignature;\n}\n\n/**\n * `readStreamableValue` takes a streamable value created via the `createStreamableValue().value` API,\n * and returns an async iterator.\n *\n * ```js\n * // Inside your AI action:\n *\n * async function action() {\n * 'use server'\n * const streamable = createStreamableValue();\n *\n * streamable.update(1);\n * streamable.update(2);\n * streamable.done(3);\n * // ...\n * return streamable.value;\n * }\n * ```\n *\n * And to read the value:\n *\n * ```js\n * const streamableValue = await action()\n * for await (const v of readStreamableValue(streamableValue)) {\n * console.log(v)\n * }\n * ```\n *\n * This logs out 1, 2, 3 on console.\n */\nexport function readStreamableValue<T = unknown>(\n streamableValue: StreamableValue<T>,\n): AsyncIterable<T | undefined> {\n assertStreamableValue(streamableValue);\n\n return {\n [Symbol.asyncIterator]() {\n let row: StreamableValue<T> | Promise<StreamableValue<T>> =\n streamableValue;\n let curr = row.curr;\n let done = false;\n let initial = true;\n\n return {\n async next() {\n if (done) return { value: curr, done: true };\n\n row = await row;\n\n if (typeof row.error !== 'undefined') {\n throw row.error;\n }\n if ('curr' in row || row.diff) {\n if (row.diff) {\n switch (row.diff[0]) {\n case 0:\n if (typeof curr !== 'string') {\n throw new Error(\n 'Invalid patch: can only append to string types. This is a bug in the AI SDK.',\n );\n } else {\n (curr as string) = curr + row.diff[1];\n }\n break;\n }\n } else {\n curr = row.curr;\n }\n\n // The last emitted { done: true } won't be used as the value\n // by the for await...of syntax.\n if (!row.next) {\n done = true;\n return {\n value: curr,\n done: false,\n };\n }\n }\n\n if (!row.next) {\n return {\n value: curr,\n done: true,\n };\n }\n\n row = row.next;\n if (initial) {\n initial = false;\n if (typeof curr === 'undefined') {\n // This is the initial chunk and there isn't an initial value yet.\n // Let's skip this one.\n return this.next();\n }\n }\n\n return {\n value: curr,\n done: false,\n };\n },\n };\n },\n };\n}\n\n/**\n * `useStreamableValue` is a React hook that takes a streamable value created via the `createStreamableValue().value` API,\n * and returns the current value, error, and pending state.\n *\n * This is useful for consuming streamable values received from a component's props. For example:\n *\n * ```js\n * function MyComponent({ streamableValue }) {\n * const [data, error, pending] = useStreamableValue(streamableValue);\n *\n * if (pending) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Data: {data}</div>;\n * }\n * ```\n */\nexport function useStreamableValue<T = unknown, Error = unknown>(\n streamableValue?: StreamableValue<T>,\n): [data: T | undefined, error: Error | undefined, pending: boolean] {\n const [curr, setCurr] = useState<T | undefined>(\n isStreamableValue(streamableValue) ? streamableValue.curr : undefined,\n );\n const [error, setError] = useState<Error | undefined>(\n isStreamableValue(streamableValue) ? streamableValue.error : undefined,\n );\n const [pending, setPending] = useState<boolean>(\n isStreamableValue(streamableValue) ? !!streamableValue.next : false,\n );\n\n useLayoutEffect(() => {\n if (!isStreamableValue(streamableValue)) return;\n\n let cancelled = false;\n\n const iterator = readStreamableValue(streamableValue);\n if (streamableValue.next) {\n startTransition(() => {\n if (cancelled) return;\n setPending(true);\n });\n }\n\n (async () => {\n try {\n for await (const value of iterator) {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setCurr(value);\n });\n }\n } catch (e) {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setError(e as Error);\n });\n } finally {\n if (cancelled) return;\n startTransition(() => {\n if (cancelled) return;\n setPending(false);\n });\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [streamableValue]);\n\n return [curr, error, pending];\n}\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\nexport const DEV_DEFAULT_STREAMABLE_WARNING_TIME = 15 * 1000;\n","/* eslint-disable react-hooks/exhaustive-deps */\n'use client';\n\nimport * as React from 'react';\n\nimport * as jsondiffpatch from 'jsondiffpatch';\nimport { isFunction } from '../../util/is-function';\nimport type {\n AIProvider,\n InferActions,\n InferAIState,\n InferUIState,\n InternalAIProviderProps,\n ValueOrUpdater,\n} from '../types';\n\nconst InternalUIStateProvider = React.createContext<null | any>(null);\nconst InternalAIStateProvider = React.createContext<undefined | any>(undefined);\nconst InternalActionProvider = React.createContext<null | any>(null);\nconst InternalSyncUIStateProvider = React.createContext<null | any>(null);\n\nexport function InternalAIProvider({\n children,\n initialUIState,\n initialAIState,\n initialAIStatePatch,\n wrappedActions,\n wrappedSyncUIState,\n}: InternalAIProviderProps) {\n if (!('use' in React)) {\n throw new Error('Unsupported React version.');\n }\n\n const uiState = React.useState(initialUIState);\n const setUIState = uiState[1];\n\n const resolvedInitialAIStatePatch = initialAIStatePatch\n ? (React as any).use(initialAIStatePatch)\n : undefined;\n initialAIState = React.useMemo(() => {\n if (resolvedInitialAIStatePatch) {\n return jsondiffpatch.patch(\n jsondiffpatch.clone(initialAIState),\n resolvedInitialAIStatePatch,\n );\n }\n return initialAIState;\n }, [initialAIState, resolvedInitialAIStatePatch]);\n\n const aiState = React.useState(initialAIState);\n const setAIState = aiState[1];\n const aiStateRef = React.useRef(aiState[0]);\n\n React.useEffect(() => {\n aiStateRef.current = aiState[0];\n }, [aiState[0]]);\n\n const clientWrappedActions = React.useMemo(\n () =>\n Object.fromEntries(\n Object.entries(wrappedActions).map(([key, action]) => [\n key,\n async (...args: any) => {\n const aiStateSnapshot = aiStateRef.current;\n const [aiStateDelta, result] = await action(\n aiStateSnapshot,\n ...args,\n );\n (async () => {\n const delta = await aiStateDelta;\n if (delta !== undefined) {\n aiState[1](\n jsondiffpatch.patch(\n jsondiffpatch.clone(aiStateSnapshot),\n delta,\n ),\n );\n }\n })();\n return result;\n },\n ]),\n ),\n [wrappedActions],\n );\n\n const clientWrappedSyncUIStateAction = React.useMemo(() => {\n if (!wrappedSyncUIState) {\n return () => {};\n }\n\n return async () => {\n const aiStateSnapshot = aiStateRef.current;\n const [aiStateDelta, uiState] = await wrappedSyncUIState!(\n aiStateSnapshot,\n );\n\n if (uiState !== undefined) {\n setUIState(uiState);\n }\n\n const delta = await aiStateDelta;\n if (delta !== undefined) {\n const patchedAiState = jsondiffpatch.patch(\n jsondiffpatch.clone(aiStateSnapshot),\n delta,\n );\n setAIState(patchedAiState);\n }\n };\n }, [wrappedSyncUIState]);\n\n return (\n <InternalAIStateProvider.Provider value={aiState}>\n <InternalUIStateProvider.Provider value={uiState}>\n <InternalActionProvider.Provider value={clientWrappedActions}>\n <InternalSyncUIStateProvider.Provider\n value={clientWrappedSyncUIStateAction}\n >\n {children}\n </InternalSyncUIStateProvider.Provider>\n </InternalActionProvider.Provider>\n </InternalUIStateProvider.Provider>\n </InternalAIStateProvider.Provider>\n );\n}\n\nexport function useUIState<AI extends AIProvider = any>() {\n type T = InferUIState<AI, any>;\n\n const state = React.useContext<\n [T, (v: T | ((v_: T) => T)) => void] | null | undefined\n >(InternalUIStateProvider);\n if (state === null) {\n throw new Error('`useUIState` must be used inside an <AI> provider.');\n }\n if (!Array.isArray(state)) {\n throw new Error('Invalid state');\n }\n if (state[0] === undefined) {\n throw new Error(\n '`initialUIState` must be provided to `createAI` or `<AI>`',\n );\n }\n return state;\n}\n\n// TODO: How do we avoid causing a re-render when the AI state changes but you\n// are only listening to a specific key? We need useSES perhaps?\nfunction useAIState<AI extends AIProvider = any>(): [\n InferAIState<AI, any>,\n (newState: ValueOrUpdater<InferAIState<AI, any>>) => void,\n];\nfunction useAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): [\n InferAIState<AI, any>[typeof key],\n (newState: ValueOrUpdater<InferAIState<AI, any>[typeof key]>) => void,\n];\nfunction useAIState<AI extends AIProvider = any>(\n ...args: [] | [keyof InferAIState<AI, any>]\n) {\n type T = InferAIState<AI, any>;\n\n const state = React.useContext<\n [T, (newState: ValueOrUpdater<T>) => void] | null | undefined\n >(InternalAIStateProvider);\n if (state === null) {\n throw new Error('`useAIState` must be used inside an <AI> provider.');\n }\n if (!Array.isArray(state)) {\n throw new Error('Invalid state');\n }\n if (state[0] === undefined) {\n throw new Error(\n '`initialAIState` must be provided to `createAI` or `<AI>`',\n );\n }\n if (args.length >= 1 && typeof state[0] !== 'object') {\n throw new Error(\n 'When using `useAIState` with a key, the AI state must be an object.',\n );\n }\n\n const key = args[0];\n const setter = React.useCallback(\n typeof key === 'undefined'\n ? state[1]\n : (newState: ValueOrUpdater<T>) => {\n if (isFunction(newState)) {\n return state[1](s => {\n return { ...s, [key]: newState(s[key]) };\n });\n } else {\n return state[1]({ ...state[0], [key]: newState });\n }\n },\n [key],\n );\n\n if (args.length === 0) {\n return state;\n } else {\n return [state[0][args[0]], setter];\n }\n}\n\nexport function useActions<AI extends AIProvider = any>() {\n type T = InferActions<AI, any>;\n\n const actions = React.useContext<T>(InternalActionProvider);\n return actions;\n}\n\nexport function useSyncUIState() {\n const syncUIState = React.useContext<() => Promise<void>>(\n InternalSyncUIStateProvider,\n );\n\n if (syncUIState === null) {\n throw new Error('`useSyncUIState` must be used inside an <AI> provider.');\n }\n\n return syncUIState;\n}\n\nexport { useAIState };\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n"],"mappings":";;;AAAA,SAAS,iBAAiB,iBAAiB,gBAAgB;;;ACApD,IAAM,wBAAwB,OAAO,IAAI,qBAAqB;AAC9D,IAAM,sCAAsC,KAAK;;;ADGxD,SAAS,0BAA0B,OAA0C;AAC3E,SAAO,CAAC,EACN,SACA,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS;AAEnB;AAEA,SAAS,sBACP,OACkC;AAClC,MAAI,CAAC,0BAA0B,KAAK,GAAG;AACrC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,kBAAkB,OAA0C;AACnE,QAAM,eAAe,0BAA0B,KAAK;AAEpD,MAAI,CAAC,gBAAgB,OAAO,UAAU,aAAa;AACjD,UAAM,IAAI;AAAA,MACR;AAAA,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C;AACA,MAAI,MAAM,CAAC,MAAM,QAAW;AAC1B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,MAAI,KAAK,UAAU,KAAK,OAAO,MAAM,CAAC,MAAM,UAAU;AACpD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,KAAK,CAAC;AAClB,QAAM,SAAe;AAAA,IACnB,OAAO,QAAQ,cACX,MAAM,CAAC,IACP,CAAC,aAAgC;AAC/B,UAAI,WAAW,QAAQ,GAAG;AACxB,eAAO,MAAM,CAAC,EAAE,OAAK;AACnB,iBAAO,EAAE,GAAG,GAAG,CAAC,GAAG,GAAG,SAAS,EAAE,GAAG,CAAC,EAAE;AAAA,QACzC,CAAC;AAAA,MACH,OAAO;AACL,eAAO,MAAM,CAAC,EAAE,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,GAAG,SAAS,CAAC;AAAA,MAClD;AAAA,IACF;AAAA,IACJ,CAAC,GAAG;AAAA,EACN;AAEA,MAAI,KAAK,WAAW,GAAG;AACrB,WAAO;AAAA,EACT,OAAO;AACL,WAAO,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,MAAM;AAAA,EACnC;AACF;AAEO,SAAS,aAA0C;AAGxD,QAAM,UAAgB,iBAAc,sBAAsB;AAC1D,SAAO;AACT;AAEO,SAAS,iBAAiB;AAC/B,QAAM,cAAoB;AAAA,IACxB;AAAA,EACF;AAEA,MAAI,gBAAgB,MAAM;AACxB,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AAEA,SAAO;AACT;","names":["uiState"]}
|
package/svelte/dist/index.js
CHANGED
@@ -411,7 +411,7 @@ var H = class {
|
|
411
411
|
}
|
412
412
|
};
|
413
413
|
|
414
|
-
// ../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.
|
414
|
+
// ../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.18/node_modules/sswr/dist/sswr.js
|
415
415
|
var import_svelte = require("svelte");
|
416
416
|
function p() {
|
417
417
|
}
|
package/svelte/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../index.ts","../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.3/node_modules/sswr/dist/sswr.js","../use-completion.ts","../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 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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,sBAIO;;;ACdP,IAAI,IAAI,OAAO;AACf,IAAI,IAAI,CAAC,GAAG,GAAG,MAAM,KAAK,IAAI,EAAE,GAAG,GAAG,EAAE,YAAY,MAAI,cAAc,MAAI,UAAU,MAAI,OA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AA,EACpE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["e","c","A","W","D","K","v","p","w","q","x","S","h","O","w","E","F","generateId","fetch","generateIdFunc","F","data","headers","body","chatRequest","import_ui_utils","import_store","uniqueId","store","fetch","F","data","completion","import_ui_utils","import_store","uniqueId","store","fetch","messages"]}
|
1
|
+
{"version":3,"sources":["../index.ts","../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":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-assistant';\n","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":";;;;;;;;;;;;;;;;;;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AAAA,IACpB;AAAA,EACF;AAGA,iBAAe,cACb,OACA,gBACA;AArPJ;AAsPI,yCAAO,mBAAP;AACA,UAAM,iBAAa,mBAAI,KAAK;AAC5B,QAAI,CAAC;AAAY;AAEjB,UAAM,OAAO,EAAE,MAAM,QAAQ,SAAS,WAAW,GAAG,cAAc;AAAA,EACpE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["e","c","A","W","D","K","v","p","w","q","x","S","h","O","w","E","F","generateId","fetch","generateIdFunc","F","data","headers","body","chatRequest","import_ui_utils","import_store","uniqueId","store","fetch","F","data","completion","import_ui_utils","import_store","uniqueId","store","fetch","messages"]}
|
package/svelte/dist/index.mjs
CHANGED
@@ -387,7 +387,7 @@ var H = class {
|
|
387
387
|
}
|
388
388
|
};
|
389
389
|
|
390
|
-
// ../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.
|
390
|
+
// ../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.18/node_modules/sswr/dist/sswr.js
|
391
391
|
import { beforeUpdate as w, onDestroy as E2 } from "svelte";
|
392
392
|
function p() {
|
393
393
|
}
|