@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
@@ -0,0 +1,341 @@
1
+ import {
2
+ fillMessageParts,
3
+ generateId,
4
+ type UIMessage,
5
+ type UseChatOptions,
6
+ type JSONValue,
7
+ type ChatRequest,
8
+ extractMaxToolInvocationStep,
9
+ callChatApi,
10
+ shouldResubmitMessages,
11
+ type Message,
12
+ type CreateMessage,
13
+ type ChatRequestOptions,
14
+ prepareAttachmentsForRequest,
15
+ getMessageParts,
16
+ updateToolCallResult,
17
+ isAssistantMessageWithCompletedToolCalls,
18
+ } from '@ai-sdk/ui-utils';
19
+ import { isAbortError } from '@ai-sdk/provider-utils';
20
+ import {
21
+ KeyedChatStore,
22
+ getChatContext,
23
+ hasChatContext,
24
+ } from './chat-context.svelte.js';
25
+
26
+ export type ChatOptions = Readonly<
27
+ Omit<UseChatOptions, 'keepLastMessageOnError'> & {
28
+ /**
29
+ * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
30
+ * Must be at least 1.
31
+ * A maximum number is required to prevent infinite loops in the case of misconfigured tools.
32
+ * By default, it's set to 1, which means that only a single LLM call is made.
33
+ * @default 1
34
+ */
35
+ maxSteps?: number;
36
+ }
37
+ >;
38
+
39
+ export type { CreateMessage, Message, UIMessage };
40
+
41
+ export class Chat {
42
+ readonly #options: ChatOptions = {};
43
+ readonly #api = $derived(this.#options.api ?? '/api/chat');
44
+ readonly #generateId = $derived(this.#options.generateId ?? generateId);
45
+ readonly #maxSteps = $derived(this.#options.maxSteps ?? 1);
46
+ readonly #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
47
+ readonly #keyedStore = $state<KeyedChatStore>()!;
48
+ /**
49
+ * The id of the chat. If not provided through the constructor, a random ID will be generated
50
+ * using the provided `generateId` function, or a built-in function if not provided.
51
+ */
52
+ readonly id = $derived(this.#options.id ?? this.#generateId());
53
+ readonly #store = $derived(this.#keyedStore.get(this.id));
54
+ #abortController: AbortController | undefined;
55
+
56
+ /**
57
+ * Additional data added on the server via StreamData.
58
+ *
59
+ * This is writable, so you can use it to transform or clear the chat data.
60
+ */
61
+ get data() {
62
+ return this.#store.data;
63
+ }
64
+ set data(value: JSONValue[] | undefined) {
65
+ this.#store.data = value;
66
+ }
67
+
68
+ /**
69
+ * Hook status:
70
+ *
71
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
72
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
73
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
74
+ * - `error`: An error occurred during the API request, preventing successful completion.
75
+ */
76
+ get status() {
77
+ return this.#store.status;
78
+ }
79
+
80
+ /** The error object of the API request */
81
+ get error() {
82
+ return this.#store.error;
83
+ }
84
+
85
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
86
+ input = $state<string>()!;
87
+
88
+ /**
89
+ * Current messages in the chat.
90
+ *
91
+ * This is writable, which is useful when you want to edit the messages on the client, and then
92
+ * trigger {@link reload} to regenerate the AI response.
93
+ */
94
+ get messages(): UIMessage[] {
95
+ return this.#store.messages;
96
+ }
97
+ set messages(value: Message[]) {
98
+ this.#store.messages = fillMessageParts(value);
99
+ }
100
+
101
+ constructor(options: ChatOptions = {}) {
102
+ if (hasChatContext()) {
103
+ this.#keyedStore = getChatContext();
104
+ } else {
105
+ this.#keyedStore = new KeyedChatStore();
106
+ }
107
+
108
+ this.#options = options;
109
+ this.messages = options.initialMessages ?? [];
110
+ this.input = options.initialInput ?? '';
111
+ }
112
+
113
+ /**
114
+ * Append a user message to the chat list. This triggers the API call to fetch
115
+ * the assistant's response.
116
+ * @param message The message to append
117
+ * @param options Additional options to pass to the API call
118
+ */
119
+ append = async (
120
+ message: Message | CreateMessage,
121
+ { data, headers, body, experimental_attachments }: ChatRequestOptions = {},
122
+ ) => {
123
+ const attachmentsForRequest = await prepareAttachmentsForRequest(
124
+ experimental_attachments,
125
+ );
126
+
127
+ const messages = this.messages.concat({
128
+ ...message,
129
+ id: message.id ?? generateId(),
130
+ createdAt: message.createdAt ?? new Date(),
131
+ experimental_attachments:
132
+ attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
133
+ parts: getMessageParts(message),
134
+ });
135
+
136
+ return this.#triggerRequest({ messages, headers, body, data });
137
+ };
138
+
139
+ /**
140
+ * Reload the last AI chat response for the given chat history. If the last
141
+ * message isn't from the assistant, it will request the API to generate a
142
+ * new response.
143
+ */
144
+ reload = async ({ data, headers, body }: ChatRequestOptions = {}) => {
145
+ if (this.messages.length === 0) {
146
+ return;
147
+ }
148
+
149
+ const lastMessage = this.messages[this.messages.length - 1];
150
+ await this.#triggerRequest({
151
+ messages:
152
+ lastMessage.role === 'assistant'
153
+ ? this.messages.slice(0, -1)
154
+ : this.messages,
155
+ headers,
156
+ body,
157
+ data,
158
+ });
159
+ };
160
+
161
+ /**
162
+ * Abort the current request immediately, keep the generated tokens if any.
163
+ */
164
+ stop = () => {
165
+ try {
166
+ this.#abortController?.abort();
167
+ } catch {
168
+ // ignore
169
+ } finally {
170
+ this.#store.status = 'ready';
171
+ this.#abortController = undefined;
172
+ }
173
+ };
174
+
175
+ /** Form submission handler to automatically reset input and append a user message */
176
+ handleSubmit = async (
177
+ event?: { preventDefault?: () => void },
178
+ options: ChatRequestOptions = {},
179
+ ) => {
180
+ event?.preventDefault?.();
181
+ if (!this.input && !options.allowEmptySubmit) return;
182
+
183
+ const attachmentsForRequest = await prepareAttachmentsForRequest(
184
+ options.experimental_attachments,
185
+ );
186
+
187
+ const messages = this.messages.concat({
188
+ id: generateId(),
189
+ createdAt: new Date(),
190
+ role: 'user',
191
+ content: this.input,
192
+ experimental_attachments:
193
+ attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
194
+ parts: [{ type: 'text', text: this.input }],
195
+ });
196
+
197
+ const chatRequest: ChatRequest = {
198
+ messages,
199
+ headers: options.headers,
200
+ body: options.body,
201
+ data: options.data,
202
+ };
203
+
204
+ const request = this.#triggerRequest(chatRequest);
205
+ this.input = '';
206
+ await request;
207
+ };
208
+
209
+ addToolResult = async ({
210
+ toolCallId,
211
+ result,
212
+ }: {
213
+ toolCallId: string;
214
+ result: unknown;
215
+ }) => {
216
+ updateToolCallResult({
217
+ messages: this.messages,
218
+ toolCallId,
219
+ toolResult: result,
220
+ });
221
+
222
+ const lastMessage = this.messages[this.messages.length - 1];
223
+ if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
224
+ await this.#triggerRequest({ messages: this.messages });
225
+ }
226
+ };
227
+
228
+ #triggerRequest = async (chatRequest: ChatRequest) => {
229
+ this.#store.status = 'submitted';
230
+ this.#store.error = undefined;
231
+
232
+ const messages = fillMessageParts(chatRequest.messages);
233
+ const messageCount = messages.length;
234
+ const maxStep = extractMaxToolInvocationStep(
235
+ messages[messages.length - 1]?.toolInvocations,
236
+ );
237
+
238
+ try {
239
+ const abortController = new AbortController();
240
+ this.#abortController = abortController;
241
+
242
+ // Optimistically update messages
243
+ this.messages = messages;
244
+
245
+ const constructedMessagesPayload = this.#options.sendExtraMessageFields
246
+ ? messages
247
+ : messages.map(
248
+ ({
249
+ role,
250
+ content,
251
+ experimental_attachments,
252
+ data,
253
+ annotations,
254
+ toolInvocations,
255
+ parts,
256
+ }) => ({
257
+ role,
258
+ content,
259
+ ...(experimental_attachments !== undefined && {
260
+ experimental_attachments,
261
+ }),
262
+ ...(data !== undefined && { data }),
263
+ ...(annotations !== undefined && { annotations }),
264
+ ...(toolInvocations !== undefined && { toolInvocations }),
265
+ ...(parts !== undefined && { parts }),
266
+ }),
267
+ );
268
+
269
+ const existingData = this.data ?? [];
270
+ await callChatApi({
271
+ api: this.#api,
272
+ body: {
273
+ id: this.id,
274
+ messages: constructedMessagesPayload,
275
+ data: chatRequest.data,
276
+ ...$state.snapshot(this.#options.body),
277
+ ...chatRequest.body,
278
+ },
279
+ streamProtocol: this.#streamProtocol,
280
+ credentials: this.#options.credentials,
281
+ headers: {
282
+ ...this.#options.headers,
283
+ ...chatRequest.headers,
284
+ },
285
+ abortController: () => abortController,
286
+ restoreMessagesOnFailure: () => {},
287
+ onResponse: this.#options.onResponse,
288
+ onUpdate: ({ message, data, replaceLastMessage }) => {
289
+ this.#store.status = 'streaming';
290
+
291
+ this.messages = messages;
292
+ if (replaceLastMessage) {
293
+ this.messages[this.messages.length - 1] = message;
294
+ } else {
295
+ this.messages.push(message);
296
+ }
297
+
298
+ if (data?.length) {
299
+ this.data = existingData;
300
+ this.data.push(...data);
301
+ }
302
+ },
303
+ onToolCall: this.#options.onToolCall,
304
+ onFinish: this.#options.onFinish,
305
+ generateId: this.#generateId,
306
+ fetch: this.#options.fetch,
307
+ // callChatApi calls structuredClone on the message
308
+ lastMessage: $state.snapshot(this.messages[this.messages.length - 1]),
309
+ });
310
+
311
+ this.#abortController = undefined;
312
+ this.#store.status = 'ready';
313
+ } catch (error) {
314
+ if (isAbortError(error)) {
315
+ return;
316
+ }
317
+
318
+ const coalescedError =
319
+ error instanceof Error ? error : new Error(String(error));
320
+ if (this.#options.onError) {
321
+ this.#options.onError(coalescedError);
322
+ }
323
+
324
+ this.#store.status = 'error';
325
+ this.#store.error = coalescedError;
326
+ }
327
+
328
+ // auto-submit when all tool calls in the last assistant message have results
329
+ // and assistant has not answered yet
330
+ if (
331
+ shouldResubmitMessages({
332
+ originalMaxToolInvocationStep: maxStep,
333
+ originalMessageCount: messageCount,
334
+ maxSteps: this.#maxSteps,
335
+ messages: this.messages,
336
+ })
337
+ ) {
338
+ await this.#triggerRequest({ messages: this.messages });
339
+ }
340
+ };
341
+ }
@@ -0,0 +1,24 @@
1
+ import type { JSONValue } from '@ai-sdk/ui-utils';
2
+ import { SvelteMap } from 'svelte/reactivity';
3
+ import { createContext, KeyedStore } from './utils.svelte.js';
4
+
5
+ class CompletionStore {
6
+ completions = new SvelteMap<string, string>();
7
+ data = $state<JSONValue[]>([]);
8
+ loading = $state(false);
9
+ error = $state<Error>();
10
+ }
11
+
12
+ export class KeyedCompletionStore extends KeyedStore<CompletionStore> {
13
+ constructor(
14
+ value?: Iterable<readonly [string, CompletionStore]> | null | undefined,
15
+ ) {
16
+ super(CompletionStore, value);
17
+ }
18
+ }
19
+
20
+ export const {
21
+ hasContext: hasCompletionContext,
22
+ getContext: getCompletionContext,
23
+ setContext: setCompletionContext,
24
+ } = createContext<KeyedCompletionStore>('Completion');
@@ -0,0 +1,133 @@
1
+ import {
2
+ generateId,
3
+ type UseCompletionOptions,
4
+ type JSONValue,
5
+ type RequestOptions,
6
+ callCompletionApi,
7
+ } from '@ai-sdk/ui-utils';
8
+ import {
9
+ KeyedCompletionStore,
10
+ getCompletionContext,
11
+ hasCompletionContext,
12
+ } from './completion-context.svelte.js';
13
+
14
+ export type CompletionOptions = Readonly<UseCompletionOptions>;
15
+
16
+ export class Completion {
17
+ readonly #options: CompletionOptions = {};
18
+ readonly #api = $derived(this.#options.api ?? '/api/completion');
19
+ readonly #id = $derived(this.#options.id ?? generateId());
20
+ readonly #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
21
+ readonly #keyedStore = $state<KeyedCompletionStore>()!;
22
+ readonly #store = $derived(this.#keyedStore.get(this.#id));
23
+ #abortController: AbortController | undefined;
24
+
25
+ /** The current completion result */
26
+ get completion(): string {
27
+ return this.#store.completions.get(this.#id) ?? '';
28
+ }
29
+ set completion(value: string) {
30
+ this.#store.completions.set(this.#id, value);
31
+ }
32
+
33
+ /**
34
+ * Additional data added on the server via StreamData.
35
+ *
36
+ * This is writable, so you can use it to transform or clear the chat data.
37
+ */
38
+ get data() {
39
+ return this.#store.data;
40
+ }
41
+ set data(value: JSONValue[]) {
42
+ this.#store.data = value;
43
+ }
44
+
45
+ /** The error object of the API request */
46
+ get error() {
47
+ return this.#store.error;
48
+ }
49
+
50
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
51
+ input = $state<string>()!;
52
+
53
+ /**
54
+ * Flag that indicates whether an API request is in progress.
55
+ */
56
+ get loading() {
57
+ return this.#store.loading;
58
+ }
59
+
60
+ constructor(options: CompletionOptions = {}) {
61
+ if (hasCompletionContext()) {
62
+ this.#keyedStore = getCompletionContext();
63
+ } else {
64
+ this.#keyedStore = new KeyedCompletionStore();
65
+ }
66
+
67
+ this.#options = options;
68
+ this.completion = options.initialCompletion ?? '';
69
+ this.input = options.initialInput ?? '';
70
+ }
71
+
72
+ /**
73
+ * Abort the current request immediately, keep the generated tokens if any.
74
+ */
75
+ stop = () => {
76
+ try {
77
+ this.#abortController?.abort();
78
+ } catch {
79
+ // ignore
80
+ } finally {
81
+ this.#store.loading = false;
82
+ this.#abortController = undefined;
83
+ }
84
+ };
85
+
86
+ /**
87
+ * Send a new prompt to the API endpoint and update the completion state.
88
+ */
89
+ complete = async (prompt: string, options?: RequestOptions) =>
90
+ this.#triggerRequest(prompt, options);
91
+
92
+ /** Form submission handler to automatically reset input and call the completion API */
93
+ handleSubmit = async (event?: { preventDefault?: () => void }) => {
94
+ event?.preventDefault?.();
95
+ if (this.input) {
96
+ await this.complete(this.input);
97
+ }
98
+ };
99
+
100
+ #triggerRequest = async (prompt: string, options?: RequestOptions) => {
101
+ return callCompletionApi({
102
+ api: this.#api,
103
+ prompt,
104
+ credentials: this.#options.credentials,
105
+ headers: { ...this.#options.headers, ...options?.headers },
106
+ body: {
107
+ ...this.#options.body,
108
+ ...options?.body,
109
+ },
110
+ streamProtocol: this.#streamProtocol,
111
+ fetch: this.#options.fetch,
112
+ // throttle streamed ui updates:
113
+ setCompletion: completion => {
114
+ this.completion = completion;
115
+ },
116
+ onData: data => {
117
+ this.data.push(...data);
118
+ },
119
+ setLoading: loading => {
120
+ this.#store.loading = loading;
121
+ },
122
+ setError: error => {
123
+ this.#store.error = error;
124
+ },
125
+ setAbortController: abortController => {
126
+ this.#abortController = abortController ?? undefined;
127
+ },
128
+ onResponse: this.#options.onResponse,
129
+ onFinish: this.#options.onFinish,
130
+ onError: this.#options.onError,
131
+ });
132
+ };
133
+ }
@@ -0,0 +1,20 @@
1
+ import { KeyedChatStore, setChatContext } from './chat-context.svelte.js';
2
+ import {
3
+ KeyedCompletionStore,
4
+ setCompletionContext,
5
+ } from './completion-context.svelte.js';
6
+ import {
7
+ KeyedStructuredObjectStore,
8
+ setStructuredObjectContext,
9
+ } from './structured-object-context.svelte.js';
10
+
11
+ export function createAIContext() {
12
+ const chatStore = new KeyedChatStore();
13
+ setChatContext(chatStore);
14
+
15
+ const completionStore = new KeyedCompletionStore();
16
+ setCompletionContext(completionStore);
17
+
18
+ const objectStore = new KeyedStructuredObjectStore();
19
+ setStructuredObjectContext(objectStore);
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ export {
2
+ Chat,
3
+ type ChatOptions,
4
+ type CreateMessage,
5
+ type Message,
6
+ type UIMessage,
7
+ } from './chat.svelte.js';
8
+
9
+ export {
10
+ StructuredObject as Experimental_StructuredObject,
11
+ type Experimental_StructuredObjectOptions,
12
+ } from './structured-object.svelte.js';
13
+
14
+ export { Completion, type CompletionOptions } from './completion.svelte.js';
15
+
16
+ export { createAIContext } from './context-provider.js';
@@ -0,0 +1,27 @@
1
+ import type { DeepPartial } from '@ai-sdk/ui-utils';
2
+ import { createContext, KeyedStore } from './utils.svelte.js';
3
+
4
+ export class StructuredObjectStore<RESULT> {
5
+ object = $state<DeepPartial<RESULT>>();
6
+ loading = $state(false);
7
+ error = $state<Error>();
8
+ }
9
+
10
+ export class KeyedStructuredObjectStore extends KeyedStore<
11
+ StructuredObjectStore<unknown>
12
+ > {
13
+ constructor(
14
+ value?:
15
+ | Iterable<readonly [string, StructuredObjectStore<unknown>]>
16
+ | null
17
+ | undefined,
18
+ ) {
19
+ super(StructuredObjectStore, value);
20
+ }
21
+ }
22
+
23
+ export const {
24
+ hasContext: hasStructuredObjectContext,
25
+ getContext: getStructuredObjectContext,
26
+ setContext: setStructuredObjectContext,
27
+ } = createContext<KeyedStructuredObjectStore>('StructuredObject');