@ai-sdk/svelte 1.1.24 → 2.0.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +5 -3
  3. package/dist/chat-context.svelte.d.ts +14 -0
  4. package/dist/chat-context.svelte.d.ts.map +1 -0
  5. package/dist/chat-context.svelte.js +13 -0
  6. package/dist/chat.svelte.d.ts +75 -0
  7. package/dist/chat.svelte.d.ts.map +1 -0
  8. package/dist/chat.svelte.js +244 -0
  9. package/dist/completion-context.svelte.d.ts +15 -0
  10. package/dist/completion-context.svelte.d.ts.map +1 -0
  11. package/dist/completion-context.svelte.js +14 -0
  12. package/dist/completion.svelte.d.ts +37 -0
  13. package/dist/completion.svelte.d.ts.map +1 -0
  14. package/dist/completion.svelte.js +111 -0
  15. package/dist/context-provider.d.ts +2 -0
  16. package/dist/context-provider.d.ts.map +1 -0
  17. package/dist/context-provider.js +11 -0
  18. package/dist/index.d.ts +5 -166
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +4 -551
  21. package/dist/structured-object-context.svelte.d.ts +12 -0
  22. package/dist/structured-object-context.svelte.d.ts.map +1 -0
  23. package/dist/structured-object-context.svelte.js +12 -0
  24. package/dist/structured-object.svelte.d.ts +73 -0
  25. package/dist/structured-object.svelte.d.ts.map +1 -0
  26. package/dist/structured-object.svelte.js +123 -0
  27. package/dist/tests/chat-synchronization.svelte +12 -0
  28. package/dist/tests/chat-synchronization.svelte.d.ts +11 -0
  29. package/dist/tests/chat-synchronization.svelte.d.ts.map +1 -0
  30. package/dist/tests/completion-synchronization.svelte +12 -0
  31. package/dist/tests/completion-synchronization.svelte.d.ts +11 -0
  32. package/dist/tests/completion-synchronization.svelte.d.ts.map +1 -0
  33. package/dist/tests/structured-object-synchronization.svelte +22 -0
  34. package/dist/tests/structured-object-synchronization.svelte.d.ts +28 -0
  35. package/dist/tests/structured-object-synchronization.svelte.d.ts.map +1 -0
  36. package/dist/utils.svelte.d.ts +17 -0
  37. package/dist/utils.svelte.d.ts.map +1 -0
  38. package/dist/utils.svelte.js +50 -0
  39. package/package.json +56 -35
  40. package/src/chat-context.svelte.ts +23 -0
  41. package/src/chat.svelte.ts +341 -0
  42. package/src/completion-context.svelte.ts +24 -0
  43. package/src/completion.svelte.ts +133 -0
  44. package/src/context-provider.ts +20 -0
  45. package/src/index.ts +16 -0
  46. package/src/structured-object-context.svelte.ts +27 -0
  47. package/src/structured-object.svelte.ts +222 -0
  48. package/src/tests/chat-synchronization.svelte +12 -0
  49. package/src/tests/completion-synchronization.svelte +12 -0
  50. package/src/tests/structured-object-synchronization.svelte +22 -0
  51. package/src/utils.svelte.ts +66 -0
  52. package/dist/index.d.mts +0 -166
  53. package/dist/index.js.map +0 -1
  54. package/dist/index.mjs +0 -532
  55. package/dist/index.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @ai-sdk/svelte
2
2
 
3
+ ## 2.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - @ai-sdk/provider-utils@2.1.14
8
+ - @ai-sdk/ui-utils@1.1.20
9
+
10
+ ## 2.0.0
11
+
12
+ ### Major Changes
13
+
14
+ - 9e2cb6f: feat (ui/svelte): Modern Svelte 5 (**breaking change**)
15
+
3
16
  ## 1.1.24
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  [Svelte](https://svelte.dev/) UI components for the [AI SDK](https://sdk.vercel.ai/docs):
4
4
 
5
- - [`useChat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat) hook
6
- - [`useCompletion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion) hook
7
- - [`useAssistant`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-assistant) hook
5
+ - [`Chat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat)
6
+ - [`Completion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion)
7
+ - [`StructuredObject`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-object)
8
+
9
+ For information on the few ways the Svelte APIs differ from the React ones, see [the docs](https://sdk.vercel.ai/docs/getting-started/svelte#how-does-ai-sdksvelte-differ-from-ai-sdkreact)
@@ -0,0 +1,14 @@
1
+ import type { JSONValue, UIMessage } from '@ai-sdk/ui-utils';
2
+ import { KeyedStore } from './utils.svelte.js';
3
+ declare class ChatStore {
4
+ messages: UIMessage[];
5
+ data: JSONValue[] | undefined;
6
+ status: "submitted" | "streaming" | "ready" | "error";
7
+ error: Error | undefined;
8
+ }
9
+ export declare class KeyedChatStore extends KeyedStore<ChatStore> {
10
+ constructor(value?: Iterable<readonly [string, ChatStore]> | null | undefined);
11
+ }
12
+ export declare const hasChatContext: () => boolean, getChatContext: () => KeyedChatStore, setChatContext: (value: KeyedChatStore) => KeyedChatStore;
13
+ export {};
14
+ //# sourceMappingURL=chat-context.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-context.svelte.d.ts","sourceRoot":"","sources":["../src/chat-context.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAiB,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE9D,cAAM,SAAS;IACb,QAAQ,cAA2B;IACnC,IAAI,0BAAyB;IAC7B,MAAM,gDAAkE;IACxE,KAAK,oBAAmB;CACzB;AAED,qBAAa,cAAe,SAAQ,UAAU,CAAC,SAAS,CAAC;gBAErD,KAAK,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS;CAIpE;AAED,eAAO,MACO,cAAc,iBACd,cAAc,wBACd,cAAc,2CACa,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { createContext, KeyedStore } from './utils.svelte.js';
2
+ class ChatStore {
3
+ messages = $state([]);
4
+ data = $state();
5
+ status = $state('ready');
6
+ error = $state();
7
+ }
8
+ export class KeyedChatStore extends KeyedStore {
9
+ constructor(value) {
10
+ super(ChatStore, value);
11
+ }
12
+ }
13
+ export const { hasContext: hasChatContext, getContext: getChatContext, setContext: setChatContext, } = createContext('Chat');
@@ -0,0 +1,75 @@
1
+ import { type UIMessage, type UseChatOptions, type JSONValue, type Message, type CreateMessage, type ChatRequestOptions } from '@ai-sdk/ui-utils';
2
+ export type ChatOptions = Readonly<Omit<UseChatOptions, 'keepLastMessageOnError'> & {
3
+ /**
4
+ * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
5
+ * Must be at least 1.
6
+ * A maximum number is required to prevent infinite loops in the case of misconfigured tools.
7
+ * By default, it's set to 1, which means that only a single LLM call is made.
8
+ * @default 1
9
+ */
10
+ maxSteps?: number;
11
+ }>;
12
+ export type { CreateMessage, Message, UIMessage };
13
+ export declare class Chat {
14
+ #private;
15
+ /**
16
+ * The id of the chat. If not provided through the constructor, a random ID will be generated
17
+ * using the provided `generateId` function, or a built-in function if not provided.
18
+ */
19
+ readonly id: string;
20
+ /**
21
+ * Additional data added on the server via StreamData.
22
+ *
23
+ * This is writable, so you can use it to transform or clear the chat data.
24
+ */
25
+ get data(): JSONValue[] | undefined;
26
+ set data(value: JSONValue[] | undefined);
27
+ /**
28
+ * Hook status:
29
+ *
30
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
31
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
32
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
33
+ * - `error`: An error occurred during the API request, preventing successful completion.
34
+ */
35
+ get status(): "submitted" | "streaming" | "ready" | "error";
36
+ /** The error object of the API request */
37
+ get error(): Error | undefined;
38
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
39
+ input: string;
40
+ /**
41
+ * Current messages in the chat.
42
+ *
43
+ * This is writable, which is useful when you want to edit the messages on the client, and then
44
+ * trigger {@link reload} to regenerate the AI response.
45
+ */
46
+ get messages(): UIMessage[];
47
+ set messages(value: Message[]);
48
+ constructor(options?: ChatOptions);
49
+ /**
50
+ * Append a user message to the chat list. This triggers the API call to fetch
51
+ * the assistant's response.
52
+ * @param message The message to append
53
+ * @param options Additional options to pass to the API call
54
+ */
55
+ append: (message: Message | CreateMessage, { data, headers, body, experimental_attachments }?: ChatRequestOptions) => Promise<void>;
56
+ /**
57
+ * Reload the last AI chat response for the given chat history. If the last
58
+ * message isn't from the assistant, it will request the API to generate a
59
+ * new response.
60
+ */
61
+ reload: ({ data, headers, body }?: ChatRequestOptions) => Promise<void>;
62
+ /**
63
+ * Abort the current request immediately, keep the generated tokens if any.
64
+ */
65
+ stop: () => void;
66
+ /** Form submission handler to automatically reset input and append a user message */
67
+ handleSubmit: (event?: {
68
+ preventDefault?: () => void;
69
+ }, options?: ChatRequestOptions) => Promise<void>;
70
+ addToolResult: ({ toolCallId, result, }: {
71
+ toolCallId: string;
72
+ result: unknown;
73
+ }) => Promise<void>;
74
+ }
75
+ //# sourceMappingURL=chat.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.svelte.d.ts","sourceRoot":"","sources":["../src/chat.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,SAAS,EAKd,KAAK,OAAO,EACZ,KAAK,aAAa,EAClB,KAAK,kBAAkB,EAKxB,MAAM,kBAAkB,CAAC;AAQ1B,MAAM,MAAM,WAAW,GAAG,QAAQ,CAChC,IAAI,CAAC,cAAc,EAAE,wBAAwB,CAAC,GAAG;IAC/C;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CACF,CAAC;AAEF,YAAY,EAAE,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;AAElD,qBAAa,IAAI;;IAOf;;;OAGG;IACH,QAAQ,CAAC,EAAE,SAAoD;IAI/D;;;;OAIG;IACH,IAAI,IAAI,IAGQ,SAAS,EAAE,GAAG,SAAS,CADtC;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,SAAS,EAEtC;IAED;;;;;;;OAOG;IACH,IAAI,MAAM,kDAET;IAED,0CAA0C;IAC1C,IAAI,KAAK,sBAER;IAED,mFAAmF;IACnF,KAAK,SAAqB;IAE1B;;;;;OAKG;IACH,IAAI,QAAQ,IAAI,SAAS,EAAE,CAE1B;IACD,IAAI,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,EAE5B;gBAEW,OAAO,GAAE,WAAgB;IAYrC;;;;;OAKG;IACH,MAAM,YACK,OAAO,GAAG,aAAa,sDACmB,kBAAkB,mBAgBrE;IAEF;;;;OAIG;IACH,MAAM,6BAAmC,kBAAkB,mBAezD;IAEF;;OAEG;IACH,IAAI,aASF;IAEF,qFAAqF;IACrF,YAAY,WACF;QAAE,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;KAAE,YAC9B,kBAAkB,mBA6B3B;IAEF,aAAa,4BAGV;QACD,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,OAAO,CAAC;KACjB,mBAWC;CAmHH"}
@@ -0,0 +1,244 @@
1
+ import { fillMessageParts, generateId, extractMaxToolInvocationStep, callChatApi, shouldResubmitMessages, prepareAttachmentsForRequest, getMessageParts, updateToolCallResult, isAssistantMessageWithCompletedToolCalls, } from '@ai-sdk/ui-utils';
2
+ import { isAbortError } from '@ai-sdk/provider-utils';
3
+ import { KeyedChatStore, getChatContext, hasChatContext, } from './chat-context.svelte.js';
4
+ export class Chat {
5
+ #options = {};
6
+ #api = $derived(this.#options.api ?? '/api/chat');
7
+ #generateId = $derived(this.#options.generateId ?? generateId);
8
+ #maxSteps = $derived(this.#options.maxSteps ?? 1);
9
+ #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
10
+ #keyedStore = $state();
11
+ /**
12
+ * The id of the chat. If not provided through the constructor, a random ID will be generated
13
+ * using the provided `generateId` function, or a built-in function if not provided.
14
+ */
15
+ id = $derived(this.#options.id ?? this.#generateId());
16
+ #store = $derived(this.#keyedStore.get(this.id));
17
+ #abortController;
18
+ /**
19
+ * Additional data added on the server via StreamData.
20
+ *
21
+ * This is writable, so you can use it to transform or clear the chat data.
22
+ */
23
+ get data() {
24
+ return this.#store.data;
25
+ }
26
+ set data(value) {
27
+ this.#store.data = value;
28
+ }
29
+ /**
30
+ * Hook status:
31
+ *
32
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
33
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
34
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
35
+ * - `error`: An error occurred during the API request, preventing successful completion.
36
+ */
37
+ get status() {
38
+ return this.#store.status;
39
+ }
40
+ /** The error object of the API request */
41
+ get error() {
42
+ return this.#store.error;
43
+ }
44
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
45
+ input = $state();
46
+ /**
47
+ * Current messages in the chat.
48
+ *
49
+ * This is writable, which is useful when you want to edit the messages on the client, and then
50
+ * trigger {@link reload} to regenerate the AI response.
51
+ */
52
+ get messages() {
53
+ return this.#store.messages;
54
+ }
55
+ set messages(value) {
56
+ this.#store.messages = fillMessageParts(value);
57
+ }
58
+ constructor(options = {}) {
59
+ if (hasChatContext()) {
60
+ this.#keyedStore = getChatContext();
61
+ }
62
+ else {
63
+ this.#keyedStore = new KeyedChatStore();
64
+ }
65
+ this.#options = options;
66
+ this.messages = options.initialMessages ?? [];
67
+ this.input = options.initialInput ?? '';
68
+ }
69
+ /**
70
+ * Append a user message to the chat list. This triggers the API call to fetch
71
+ * the assistant's response.
72
+ * @param message The message to append
73
+ * @param options Additional options to pass to the API call
74
+ */
75
+ append = async (message, { data, headers, body, experimental_attachments } = {}) => {
76
+ const attachmentsForRequest = await prepareAttachmentsForRequest(experimental_attachments);
77
+ const messages = this.messages.concat({
78
+ ...message,
79
+ id: message.id ?? generateId(),
80
+ createdAt: message.createdAt ?? new Date(),
81
+ experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
82
+ parts: getMessageParts(message),
83
+ });
84
+ return this.#triggerRequest({ messages, headers, body, data });
85
+ };
86
+ /**
87
+ * Reload the last AI chat response for the given chat history. If the last
88
+ * message isn't from the assistant, it will request the API to generate a
89
+ * new response.
90
+ */
91
+ reload = async ({ data, headers, body } = {}) => {
92
+ if (this.messages.length === 0) {
93
+ return;
94
+ }
95
+ const lastMessage = this.messages[this.messages.length - 1];
96
+ await this.#triggerRequest({
97
+ messages: lastMessage.role === 'assistant'
98
+ ? this.messages.slice(0, -1)
99
+ : this.messages,
100
+ headers,
101
+ body,
102
+ data,
103
+ });
104
+ };
105
+ /**
106
+ * Abort the current request immediately, keep the generated tokens if any.
107
+ */
108
+ stop = () => {
109
+ try {
110
+ this.#abortController?.abort();
111
+ }
112
+ catch {
113
+ // ignore
114
+ }
115
+ finally {
116
+ this.#store.status = 'ready';
117
+ this.#abortController = undefined;
118
+ }
119
+ };
120
+ /** Form submission handler to automatically reset input and append a user message */
121
+ handleSubmit = async (event, options = {}) => {
122
+ event?.preventDefault?.();
123
+ if (!this.input && !options.allowEmptySubmit)
124
+ return;
125
+ const attachmentsForRequest = await prepareAttachmentsForRequest(options.experimental_attachments);
126
+ const messages = this.messages.concat({
127
+ id: generateId(),
128
+ createdAt: new Date(),
129
+ role: 'user',
130
+ content: this.input,
131
+ experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
132
+ parts: [{ type: 'text', text: this.input }],
133
+ });
134
+ const chatRequest = {
135
+ messages,
136
+ headers: options.headers,
137
+ body: options.body,
138
+ data: options.data,
139
+ };
140
+ const request = this.#triggerRequest(chatRequest);
141
+ this.input = '';
142
+ await request;
143
+ };
144
+ addToolResult = async ({ toolCallId, result, }) => {
145
+ updateToolCallResult({
146
+ messages: this.messages,
147
+ toolCallId,
148
+ toolResult: result,
149
+ });
150
+ const lastMessage = this.messages[this.messages.length - 1];
151
+ if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
152
+ await this.#triggerRequest({ messages: this.messages });
153
+ }
154
+ };
155
+ #triggerRequest = async (chatRequest) => {
156
+ this.#store.status = 'submitted';
157
+ this.#store.error = undefined;
158
+ const messages = fillMessageParts(chatRequest.messages);
159
+ const messageCount = messages.length;
160
+ const maxStep = extractMaxToolInvocationStep(messages[messages.length - 1]?.toolInvocations);
161
+ try {
162
+ const abortController = new AbortController();
163
+ this.#abortController = abortController;
164
+ // Optimistically update messages
165
+ this.messages = messages;
166
+ const constructedMessagesPayload = this.#options.sendExtraMessageFields
167
+ ? messages
168
+ : messages.map(({ role, content, experimental_attachments, data, annotations, toolInvocations, parts, }) => ({
169
+ role,
170
+ content,
171
+ ...(experimental_attachments !== undefined && {
172
+ experimental_attachments,
173
+ }),
174
+ ...(data !== undefined && { data }),
175
+ ...(annotations !== undefined && { annotations }),
176
+ ...(toolInvocations !== undefined && { toolInvocations }),
177
+ ...(parts !== undefined && { parts }),
178
+ }));
179
+ const existingData = this.data ?? [];
180
+ await callChatApi({
181
+ api: this.#api,
182
+ body: {
183
+ id: this.id,
184
+ messages: constructedMessagesPayload,
185
+ data: chatRequest.data,
186
+ ...$state.snapshot(this.#options.body),
187
+ ...chatRequest.body,
188
+ },
189
+ streamProtocol: this.#streamProtocol,
190
+ credentials: this.#options.credentials,
191
+ headers: {
192
+ ...this.#options.headers,
193
+ ...chatRequest.headers,
194
+ },
195
+ abortController: () => abortController,
196
+ restoreMessagesOnFailure: () => { },
197
+ onResponse: this.#options.onResponse,
198
+ onUpdate: ({ message, data, replaceLastMessage }) => {
199
+ this.#store.status = 'streaming';
200
+ this.messages = messages;
201
+ if (replaceLastMessage) {
202
+ this.messages[this.messages.length - 1] = message;
203
+ }
204
+ else {
205
+ this.messages.push(message);
206
+ }
207
+ if (data?.length) {
208
+ this.data = existingData;
209
+ this.data.push(...data);
210
+ }
211
+ },
212
+ onToolCall: this.#options.onToolCall,
213
+ onFinish: this.#options.onFinish,
214
+ generateId: this.#generateId,
215
+ fetch: this.#options.fetch,
216
+ // callChatApi calls structuredClone on the message
217
+ lastMessage: $state.snapshot(this.messages[this.messages.length - 1]),
218
+ });
219
+ this.#abortController = undefined;
220
+ this.#store.status = 'ready';
221
+ }
222
+ catch (error) {
223
+ if (isAbortError(error)) {
224
+ return;
225
+ }
226
+ const coalescedError = error instanceof Error ? error : new Error(String(error));
227
+ if (this.#options.onError) {
228
+ this.#options.onError(coalescedError);
229
+ }
230
+ this.#store.status = 'error';
231
+ this.#store.error = coalescedError;
232
+ }
233
+ // auto-submit when all tool calls in the last assistant message have results
234
+ // and assistant has not answered yet
235
+ if (shouldResubmitMessages({
236
+ originalMaxToolInvocationStep: maxStep,
237
+ originalMessageCount: messageCount,
238
+ maxSteps: this.#maxSteps,
239
+ messages: this.messages,
240
+ })) {
241
+ await this.#triggerRequest({ messages: this.messages });
242
+ }
243
+ };
244
+ }
@@ -0,0 +1,15 @@
1
+ import type { JSONValue } from '@ai-sdk/ui-utils';
2
+ import { SvelteMap } from 'svelte/reactivity';
3
+ import { KeyedStore } from './utils.svelte.js';
4
+ declare class CompletionStore {
5
+ completions: SvelteMap<string, string>;
6
+ data: JSONValue[];
7
+ loading: boolean;
8
+ error: Error | undefined;
9
+ }
10
+ export declare class KeyedCompletionStore extends KeyedStore<CompletionStore> {
11
+ constructor(value?: Iterable<readonly [string, CompletionStore]> | null | undefined);
12
+ }
13
+ export declare const hasCompletionContext: () => boolean, getCompletionContext: () => KeyedCompletionStore, setCompletionContext: (value: KeyedCompletionStore) => KeyedCompletionStore;
14
+ export {};
15
+ //# sourceMappingURL=completion-context.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"completion-context.svelte.d.ts","sourceRoot":"","sources":["../src/completion-context.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAiB,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE9D,cAAM,eAAe;IACnB,WAAW,4BAAmC;IAC9C,IAAI,cAA2B;IAC/B,OAAO,UAAiB;IACxB,KAAK,oBAAmB;CACzB;AAED,qBAAa,oBAAqB,SAAQ,UAAU,CAAC,eAAe,CAAC;gBAEjE,KAAK,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS;CAI1E;AAED,eAAO,MACO,oBAAoB,iBACpB,oBAAoB,8BACpB,oBAAoB,uDACmB,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { SvelteMap } from 'svelte/reactivity';
2
+ import { createContext, KeyedStore } from './utils.svelte.js';
3
+ class CompletionStore {
4
+ completions = new SvelteMap();
5
+ data = $state([]);
6
+ loading = $state(false);
7
+ error = $state();
8
+ }
9
+ export class KeyedCompletionStore extends KeyedStore {
10
+ constructor(value) {
11
+ super(CompletionStore, value);
12
+ }
13
+ }
14
+ export const { hasContext: hasCompletionContext, getContext: getCompletionContext, setContext: setCompletionContext, } = createContext('Completion');
@@ -0,0 +1,37 @@
1
+ import { type UseCompletionOptions, type JSONValue, type RequestOptions } from '@ai-sdk/ui-utils';
2
+ export type CompletionOptions = Readonly<UseCompletionOptions>;
3
+ export declare class Completion {
4
+ #private;
5
+ /** The current completion result */
6
+ get completion(): string;
7
+ set completion(value: string);
8
+ /**
9
+ * Additional data added on the server via StreamData.
10
+ *
11
+ * This is writable, so you can use it to transform or clear the chat data.
12
+ */
13
+ get data(): JSONValue[];
14
+ set data(value: JSONValue[]);
15
+ /** The error object of the API request */
16
+ get error(): Error | undefined;
17
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
18
+ input: string;
19
+ /**
20
+ * Flag that indicates whether an API request is in progress.
21
+ */
22
+ get loading(): boolean;
23
+ constructor(options?: CompletionOptions);
24
+ /**
25
+ * Abort the current request immediately, keep the generated tokens if any.
26
+ */
27
+ stop: () => void;
28
+ /**
29
+ * Send a new prompt to the API endpoint and update the completion state.
30
+ */
31
+ complete: (prompt: string, options?: RequestOptions) => Promise<string | null | undefined>;
32
+ /** Form submission handler to automatically reset input and call the completion API */
33
+ handleSubmit: (event?: {
34
+ preventDefault?: () => void;
35
+ }) => Promise<void>;
36
+ }
37
+ //# sourceMappingURL=completion.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"completion.svelte.d.ts","sourceRoot":"","sources":["../src/completion.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,oBAAoB,EACzB,KAAK,SAAS,EACd,KAAK,cAAc,EAEpB,MAAM,kBAAkB,CAAC;AAO1B,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC,oBAAoB,CAAC,CAAC;AAE/D,qBAAa,UAAU;;IASrB,oCAAoC;IACpC,IAAI,UAAU,IAAI,MAAM,CAEvB;IACD,IAAI,UAAU,CAAC,KAAK,EAAE,MAAM,EAE3B;IAED;;;;OAIG;IACH,IAAI,IAAI,IAGQ,SAAS,EAAE,CAD1B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,EAE1B;IAED,0CAA0C;IAC1C,IAAI,KAAK,sBAER;IAED,mFAAmF;IACnF,KAAK,SAAqB;IAE1B;;OAEG;IACH,IAAI,OAAO,YAEV;gBAEW,OAAO,GAAE,iBAAsB;IAY3C;;OAEG;IACH,IAAI,aASF;IAEF;;OAEG;IACH,QAAQ,WAAkB,MAAM,YAAY,cAAc,wCAClB;IAExC,uFAAuF;IACvF,YAAY,WAAkB;QAAE,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;KAAE,mBAK3D;CAmCH"}
@@ -0,0 +1,111 @@
1
+ import { generateId, callCompletionApi, } from '@ai-sdk/ui-utils';
2
+ import { KeyedCompletionStore, getCompletionContext, hasCompletionContext, } from './completion-context.svelte.js';
3
+ export class Completion {
4
+ #options = {};
5
+ #api = $derived(this.#options.api ?? '/api/completion');
6
+ #id = $derived(this.#options.id ?? generateId());
7
+ #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
8
+ #keyedStore = $state();
9
+ #store = $derived(this.#keyedStore.get(this.#id));
10
+ #abortController;
11
+ /** The current completion result */
12
+ get completion() {
13
+ return this.#store.completions.get(this.#id) ?? '';
14
+ }
15
+ set completion(value) {
16
+ this.#store.completions.set(this.#id, value);
17
+ }
18
+ /**
19
+ * Additional data added on the server via StreamData.
20
+ *
21
+ * This is writable, so you can use it to transform or clear the chat data.
22
+ */
23
+ get data() {
24
+ return this.#store.data;
25
+ }
26
+ set data(value) {
27
+ this.#store.data = value;
28
+ }
29
+ /** The error object of the API request */
30
+ get error() {
31
+ return this.#store.error;
32
+ }
33
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
34
+ input = $state();
35
+ /**
36
+ * Flag that indicates whether an API request is in progress.
37
+ */
38
+ get loading() {
39
+ return this.#store.loading;
40
+ }
41
+ constructor(options = {}) {
42
+ if (hasCompletionContext()) {
43
+ this.#keyedStore = getCompletionContext();
44
+ }
45
+ else {
46
+ this.#keyedStore = new KeyedCompletionStore();
47
+ }
48
+ this.#options = options;
49
+ this.completion = options.initialCompletion ?? '';
50
+ this.input = options.initialInput ?? '';
51
+ }
52
+ /**
53
+ * Abort the current request immediately, keep the generated tokens if any.
54
+ */
55
+ stop = () => {
56
+ try {
57
+ this.#abortController?.abort();
58
+ }
59
+ catch {
60
+ // ignore
61
+ }
62
+ finally {
63
+ this.#store.loading = false;
64
+ this.#abortController = undefined;
65
+ }
66
+ };
67
+ /**
68
+ * Send a new prompt to the API endpoint and update the completion state.
69
+ */
70
+ complete = async (prompt, options) => this.#triggerRequest(prompt, options);
71
+ /** Form submission handler to automatically reset input and call the completion API */
72
+ handleSubmit = async (event) => {
73
+ event?.preventDefault?.();
74
+ if (this.input) {
75
+ await this.complete(this.input);
76
+ }
77
+ };
78
+ #triggerRequest = async (prompt, options) => {
79
+ return callCompletionApi({
80
+ api: this.#api,
81
+ prompt,
82
+ credentials: this.#options.credentials,
83
+ headers: { ...this.#options.headers, ...options?.headers },
84
+ body: {
85
+ ...this.#options.body,
86
+ ...options?.body,
87
+ },
88
+ streamProtocol: this.#streamProtocol,
89
+ fetch: this.#options.fetch,
90
+ // throttle streamed ui updates:
91
+ setCompletion: completion => {
92
+ this.completion = completion;
93
+ },
94
+ onData: data => {
95
+ this.data.push(...data);
96
+ },
97
+ setLoading: loading => {
98
+ this.#store.loading = loading;
99
+ },
100
+ setError: error => {
101
+ this.#store.error = error;
102
+ },
103
+ setAbortController: abortController => {
104
+ this.#abortController = abortController ?? undefined;
105
+ },
106
+ onResponse: this.#options.onResponse,
107
+ onFinish: this.#options.onFinish,
108
+ onError: this.#options.onError,
109
+ });
110
+ };
111
+ }
@@ -0,0 +1,2 @@
1
+ export declare function createAIContext(): void;
2
+ //# sourceMappingURL=context-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AAUA,wBAAgB,eAAe,SAS9B"}
@@ -0,0 +1,11 @@
1
+ import { KeyedChatStore, setChatContext } from './chat-context.svelte.js';
2
+ import { KeyedCompletionStore, setCompletionContext, } from './completion-context.svelte.js';
3
+ import { KeyedStructuredObjectStore, setStructuredObjectContext, } from './structured-object-context.svelte.js';
4
+ export function createAIContext() {
5
+ const chatStore = new KeyedChatStore();
6
+ setChatContext(chatStore);
7
+ const completionStore = new KeyedCompletionStore();
8
+ setCompletionContext(completionStore);
9
+ const objectStore = new KeyedStructuredObjectStore();
10
+ setStructuredObjectContext(objectStore);
11
+ }