@ai-sdk/svelte 3.0.0-alpha.8 → 3.0.0-beta.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/CHANGELOG.md CHANGED
@@ -1,5 +1,107 @@
1
1
  # @ai-sdk/svelte
2
2
 
3
+ ## 3.0.0-beta.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [d88455d]
8
+ - Updated dependencies [45c1ea2]
9
+ - Updated dependencies [9ad0484]
10
+ - Updated dependencies [e025824]
11
+ - Updated dependencies [4048ce3]
12
+ - Updated dependencies [f2b041e]
13
+ - Updated dependencies [cb68df0]
14
+ - Updated dependencies [26695a3]
15
+ - Updated dependencies [bfdca8d]
16
+ - Updated dependencies [e7d2ce3]
17
+ - Updated dependencies [102b066]
18
+ - Updated dependencies [71f938d]
19
+ - Updated dependencies [28a5ed5]
20
+ - Updated dependencies [e862b5b]
21
+ - Updated dependencies [7bd025b]
22
+ - ai@5.0.0-beta.1
23
+ - @ai-sdk/provider-utils@3.0.0-beta.1
24
+
25
+ ## 3.0.0-alpha.15
26
+
27
+ ### Patch Changes
28
+
29
+ - Updated dependencies [b1e3abd]
30
+ - Updated dependencies [8ba77a7]
31
+ - Updated dependencies [04d5063]
32
+ - Updated dependencies [b4b4bb2]
33
+ - Updated dependencies [d884051]
34
+ - Updated dependencies [954aa73]
35
+ - Updated dependencies [142576e]
36
+ - Updated dependencies [395c85e]
37
+ - Updated dependencies [60e2c56]
38
+ - ai@5.0.0-alpha.15
39
+ - @ai-sdk/provider-utils@3.0.0-alpha.15
40
+
41
+ ## 3.0.0-alpha.14
42
+
43
+ ### Patch Changes
44
+
45
+ - Updated dependencies [63f9e9b]
46
+ - ai@5.0.0-alpha.14
47
+ - @ai-sdk/provider-utils@3.0.0-alpha.14
48
+
49
+ ## 3.0.0-alpha.13
50
+
51
+ ### Major Changes
52
+
53
+ - 0a710d8: feat (ui): typed tool parts in ui messages
54
+ - 901df02: feat (ui): use UI_MESSAGE generic
55
+
56
+ ### Patch Changes
57
+
58
+ - Updated dependencies [0a710d8]
59
+ - Updated dependencies [6a83f7d]
60
+ - Updated dependencies [1f55c21]
61
+ - Updated dependencies [33eb499]
62
+ - Updated dependencies [901df02]
63
+ - ai@5.0.0-alpha.13
64
+ - @ai-sdk/provider-utils@3.0.0-alpha.13
65
+
66
+ ## 3.0.0-alpha.12
67
+
68
+ ### Patch Changes
69
+
70
+ - Updated dependencies [da1e6f0]
71
+ - Updated dependencies [4892798]
72
+ - ai@5.0.0-alpha.12
73
+ - @ai-sdk/provider-utils@3.0.0-alpha.12
74
+
75
+ ## 3.0.0-alpha.11
76
+
77
+ ### Patch Changes
78
+
79
+ - Updated dependencies [e8324c5]
80
+ - ai@5.0.0-alpha.11
81
+ - @ai-sdk/provider-utils@3.0.0-alpha.11
82
+
83
+ ## 3.0.0-alpha.10
84
+
85
+ ### Major Changes
86
+
87
+ - 98f25e5: chore (ui): remove managed chat inputs
88
+
89
+ ### Patch Changes
90
+
91
+ - Updated dependencies [98f25e5]
92
+ - Updated dependencies [7bb58d4]
93
+ - ai@5.0.0-alpha.10
94
+ - @ai-sdk/provider-utils@3.0.0-alpha.10
95
+
96
+ ## 3.0.0-alpha.9
97
+
98
+ ### Patch Changes
99
+
100
+ - Updated dependencies [8255639]
101
+ - Updated dependencies [9ae327d]
102
+ - ai@5.0.0-alpha.9
103
+ - @ai-sdk/provider-utils@3.0.0-alpha.9
104
+
3
105
  ## 3.0.0-alpha.8
4
106
 
5
107
  ### Patch Changes
@@ -1,63 +1,6 @@
1
- import { type ChatRequestOptions, type ChatStatus, type CreateUIMessage, type InferUIDataParts, type UIDataPartSchemas, type UIMessage, type UseChatOptions } from 'ai';
2
- export type ChatOptions<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = Readonly<UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>>;
1
+ import { AbstractChat, type ChatInit, type CreateUIMessage, type UIMessage } from 'ai';
3
2
  export type { CreateUIMessage, UIMessage };
4
- export declare class Chat<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> {
5
- #private;
6
- /**
7
- * The id of the chat. If not provided through the constructor, a random ID will be generated
8
- * using the provided `generateId` function, or a built-in function if not provided.
9
- */
10
- readonly chatId: string;
11
- /** The current value of the input. Writable, so it can be bound to form inputs. */
12
- input: string;
13
- /**
14
- * Current messages in the chat.
15
- *
16
- * This is writable, which is useful when you want to edit the messages on the client, and then
17
- * trigger {@link reload} to regenerate the AI response.
18
- */
19
- get messages(): UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[];
20
- set messages(messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]);
21
- /**
22
- * Hook status:
23
- *
24
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
25
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
26
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
27
- * - `error`: An error occurred during the API request, preventing successful completion.
28
- */
29
- get status(): ChatStatus;
30
- set status(value: ChatStatus);
31
- /** The error object of the API request */
32
- get error(): Error | undefined;
33
- set error(value: Error | undefined);
34
- constructor(options?: () => ChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>);
35
- /**
36
- * Append a user message to the chat list. This triggers the API call to fetch
37
- * the assistant's response.
38
- * @param message The message to append
39
- * @param options Additional options to pass to the API call
40
- */
41
- append: (message: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>> | CreateUIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>, { headers, body }?: ChatRequestOptions) => Promise<void>;
42
- /**
43
- * Reload the last AI chat response for the given chat history. If the last
44
- * message isn't from the assistant, it will request the API to generate a
45
- * new response.
46
- */
47
- reload: ({ headers, body }?: ChatRequestOptions) => Promise<void>;
48
- /**
49
- * Abort the current request immediately, keep the generated tokens if any.
50
- */
51
- stop: () => void;
52
- /** Form submission handler to automatically reset input and append a user message */
53
- handleSubmit: (event?: {
54
- preventDefault?: () => void;
55
- }, options?: ChatRequestOptions & {
56
- files?: FileList;
57
- }) => Promise<void>;
58
- addToolResult: ({ toolCallId, result, }: {
59
- toolCallId: string;
60
- result: unknown;
61
- }) => Promise<void>;
3
+ export declare class Chat<UI_MESSAGE extends UIMessage = UIMessage> extends AbstractChat<UI_MESSAGE> {
4
+ constructor(init: ChatInit<UI_MESSAGE>);
62
5
  }
63
6
  //# sourceMappingURL=chat.svelte.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"chat.svelte.d.ts","sourceRoot":"","sources":["../src/chat.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,kBAAkB,EACvB,KAAK,UAAU,EACf,KAAK,eAAe,EAEpB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,cAAc,EACpB,MAAM,IAAI,CAAC;AAOZ,MAAM,MAAM,WAAW,CACrB,gBAAgB,GAAG,OAAO,EAC1B,iBAAiB,SAAS,iBAAiB,GAAG,iBAAiB,IAC7D,QAAQ,CAAC,cAAc,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAElE,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAE3C,qBAAa,IAAI,CACf,gBAAgB,GAAG,OAAO,EAC1B,iBAAiB,SAAS,iBAAiB,GAAG,iBAAiB;;IAK/D;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,mFAAmF;IACnF,KAAK,SAAsB;IAE3B;;;;;OAKG;IACH,IAAI,QAAQ,IAAI,SAAS,CACvB,gBAAgB,EAChB,gBAAgB,CAAC,iBAAiB,CAAC,CACpC,EAAE,CAEF;IACD,IAAI,QAAQ,CACV,QAAQ,EAAE,SAAS,CACjB,gBAAgB,EAChB,gBAAgB,CAAC,iBAAiB,CAAC,CACpC,EAAE,EAGJ;IAED;;;;;;;OAOG;IACH,IAAI,MAAM,IAAI,UAAU,CAEvB;IACD,IAAI,MAAM,CAAC,KAAK,EAAE,UAAU,EAE3B;IAED,0CAA0C;IAC1C,IAAI,KAAK,IAAI,KAAK,GAAG,SAAS,CAE7B;IACD,IAAI,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,SAAS,EAMjC;gBAGC,OAAO,GAAE,MAAM,WAAW,CACxB,gBAAgB,EAChB,iBAAiB,CACL;IAkChB;;;;;OAKG;IACH,MAAM,YAEA,SAAS,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,GAChE,eAAe,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,sBACvD,kBAAkB,mBAWrC;IAEF;;;;OAIG;IACH,MAAM,uBAA6B,kBAAkB,mBASnD;IAEF;;OAEG;IACH,IAAI,aAEF;IAEF,qFAAqF;IACrF,YAAY,WACF;QAAE,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;KAAE,YAC9B,kBAAkB,GAAG;QAAE,KAAK,CAAC,EAAE,QAAQ,CAAA;KAAE,mBAwBlD;IAEF,aAAa,4BAGV;QACD,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,OAAO,CAAC;KACjB,mBAMC;CACH"}
1
+ {"version":3,"file":"chat.svelte.d.ts","sourceRoot":"","sources":["../src/chat.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,KAAK,QAAQ,EAGb,KAAK,eAAe,EACpB,KAAK,SAAS,EACf,MAAM,IAAI,CAAC;AAEZ,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAE3C,qBAAa,IAAI,CACf,UAAU,SAAS,SAAS,GAAG,SAAS,CACxC,SAAQ,YAAY,CAAC,UAAU,CAAC;gBACpB,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC;CAMvC"}
@@ -1,142 +1,30 @@
1
- import { ChatStore, convertFileListToFileUIParts, defaultChatStoreOptions, generateId, } from 'ai';
2
- import { getChatStoreContext, hasChatStoreContext, createChatStore, } from './chat-store.svelte.js';
3
- export class Chat {
4
- #options;
5
- #generateId;
6
- #chatStore;
7
- /**
8
- * The id of the chat. If not provided through the constructor, a random ID will be generated
9
- * using the provided `generateId` function, or a built-in function if not provided.
10
- */
11
- chatId;
12
- /** The current value of the input. Writable, so it can be bound to form inputs. */
13
- input = $state('');
14
- /**
15
- * Current messages in the chat.
16
- *
17
- * This is writable, which is useful when you want to edit the messages on the client, and then
18
- * trigger {@link reload} to regenerate the AI response.
19
- */
20
- get messages() {
21
- return this.#chatStore.getMessages(this.chatId);
22
- }
23
- set messages(messages) {
24
- this.#chatStore.setMessages({ id: this.chatId, messages });
25
- }
26
- /**
27
- * Hook status:
28
- *
29
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
30
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
31
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
32
- * - `error`: An error occurred during the API request, preventing successful completion.
33
- */
34
- get status() {
35
- return this.#chatStore.getStatus(this.chatId);
36
- }
37
- set status(value) {
38
- this.#chatStore.setStatus({ id: this.chatId, status: value });
39
- }
40
- /** The error object of the API request */
41
- get error() {
42
- return this.#chatStore.getError(this.chatId);
43
- }
44
- set error(value) {
45
- this.#chatStore.setStatus({
46
- id: this.chatId,
47
- status: 'error',
48
- error: value,
1
+ import { AbstractChat, } from 'ai';
2
+ export class Chat extends AbstractChat {
3
+ constructor(init) {
4
+ super({
5
+ ...init,
6
+ state: new SvelteChatState(init.messages),
49
7
  });
50
8
  }
51
- constructor(options = () => ({})) {
52
- this.#options = $derived.by(options);
53
- this.#generateId = $derived(this.#options.generateId ?? generateId);
54
- this.chatId = $derived(this.#options.chatId ?? this.#generateId());
55
- if (this.#options.chatStore) {
56
- if (typeof this.#options.chatStore === 'function') {
57
- this.#chatStore = createChatStore(this.#options.chatStore());
58
- }
59
- else {
60
- this.#chatStore = this.#options.chatStore;
61
- }
62
- }
63
- else if (hasChatStoreContext()) {
64
- this.#chatStore = getChatStoreContext();
65
- }
66
- else {
67
- this.#chatStore = createChatStore(defaultChatStoreOptions({
68
- api: '/api/chat',
69
- generateId: this.#options.generateId || generateId,
70
- })());
71
- }
72
- this.input = this.#options.initialInput ?? '';
73
- if (!this.#chatStore.hasChat(this.chatId)) {
74
- const messages = $state([]);
75
- this.#chatStore.addChat(this.chatId, messages);
76
- }
9
+ }
10
+ class SvelteChatState {
11
+ messages;
12
+ status = $state('ready');
13
+ error = $state(undefined);
14
+ constructor(messages = []) {
15
+ this.messages = $state(messages);
77
16
  }
78
- /**
79
- * Append a user message to the chat list. This triggers the API call to fetch
80
- * the assistant's response.
81
- * @param message The message to append
82
- * @param options Additional options to pass to the API call
83
- */
84
- append = async (message, { headers, body } = {}) => {
85
- await this.#chatStore.submitMessage({
86
- chatId: this.chatId,
87
- message,
88
- headers,
89
- body,
90
- onError: this.#options.onError,
91
- onToolCall: this.#options.onToolCall,
92
- onFinish: this.#options.onFinish,
93
- });
17
+ setMessages = (messages) => {
18
+ this.messages = messages;
94
19
  };
95
- /**
96
- * Reload the last AI chat response for the given chat history. If the last
97
- * message isn't from the assistant, it will request the API to generate a
98
- * new response.
99
- */
100
- reload = async ({ headers, body } = {}) => {
101
- await this.#chatStore.resubmitLastUserMessage({
102
- chatId: this.chatId,
103
- headers,
104
- body,
105
- onError: this.#options.onError,
106
- onToolCall: this.#options.onToolCall,
107
- onFinish: this.#options.onFinish,
108
- });
20
+ pushMessage = (message) => {
21
+ this.messages.push(message);
109
22
  };
110
- /**
111
- * Abort the current request immediately, keep the generated tokens if any.
112
- */
113
- stop = () => {
114
- this.#chatStore.stopStream({ chatId: this.chatId });
23
+ popMessage = () => {
24
+ this.messages.pop();
115
25
  };
116
- /** Form submission handler to automatically reset input and append a user message */
117
- handleSubmit = async (event, options = {}) => {
118
- event?.preventDefault?.();
119
- const fileParts = Array.isArray(options?.files)
120
- ? options.files
121
- : await convertFileListToFileUIParts(options?.files);
122
- if (!this.input && fileParts.length === 0)
123
- return;
124
- const request = this.append({
125
- id: this.#generateId(),
126
- role: 'user',
127
- parts: [...fileParts, { type: 'text', text: this.input }],
128
- }, {
129
- headers: options.headers,
130
- body: options.body,
131
- });
132
- this.input = '';
133
- await request;
134
- };
135
- addToolResult = async ({ toolCallId, result, }) => {
136
- await this.#chatStore.addToolResult({
137
- chatId: this.chatId,
138
- toolCallId,
139
- result,
140
- });
26
+ replaceMessage = (index, message) => {
27
+ this.messages[index] = message;
141
28
  };
29
+ snapshot = (thing) => $state.snapshot(thing);
142
30
  }
@@ -1,4 +1,2 @@
1
- import { type ChatStore } from 'ai';
2
- export declare function createAIContext(chatStore?: ChatStore): void;
3
- export declare function createChatStoreContext(chatStore?: ChatStore): void;
1
+ export declare function createAIContext(): void;
4
2
  //# sourceMappingURL=context-provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,SAAS,EAAE,MAAM,IAAI,CAAC;AAW7D,wBAAgB,eAAe,CAAC,SAAS,CAAC,EAAE,SAAS,QAQpD;AAED,wBAAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,SAAS,QAS3D"}
1
+ {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AASA,wBAAgB,eAAe,SAM9B"}
@@ -1,17 +1,8 @@
1
- import { defaultChatStoreOptions } from 'ai';
2
- import { createChatStore, setChatStoreContext } from './chat-store.svelte.js';
3
1
  import { KeyedCompletionStore, setCompletionContext, } from './completion-context.svelte.js';
4
2
  import { KeyedStructuredObjectStore, setStructuredObjectContext, } from './structured-object-context.svelte.js';
5
- export function createAIContext(chatStore) {
6
- createChatStoreContext(chatStore);
3
+ export function createAIContext() {
7
4
  const completionStore = new KeyedCompletionStore();
8
5
  setCompletionContext(completionStore);
9
6
  const objectStore = new KeyedStructuredObjectStore();
10
7
  setStructuredObjectContext(objectStore);
11
8
  }
12
- export function createChatStoreContext(chatStore) {
13
- setChatStoreContext(chatStore ??
14
- createChatStore(defaultChatStoreOptions({
15
- api: '/api/chat',
16
- })()));
17
- }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- export { Chat, type ChatOptions, type CreateUIMessage, type UIMessage, } from './chat.svelte.js';
2
- export { StructuredObject as Experimental_StructuredObject, type Experimental_StructuredObjectOptions, } from './structured-object.svelte.js';
1
+ export { Chat, type CreateUIMessage, type UIMessage } from './chat.svelte.js';
3
2
  export { Completion, type CompletionOptions } from './completion.svelte.js';
4
3
  export { createAIContext } from './context-provider.js';
5
- export { createChatStore } from './chat-store.svelte.js';
4
+ export { StructuredObject as Experimental_StructuredObject, type Experimental_StructuredObjectOptions, } from './structured-object.svelte.js';
6
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,SAAS,GACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,gBAAgB,IAAI,6BAA6B,EACjD,KAAK,oCAAoC,GAC1C,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EACL,gBAAgB,IAAI,6BAA6B,EACjD,KAAK,oCAAoC,GAC1C,MAAM,+BAA+B,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
- export { Chat, } from './chat.svelte.js';
2
- export { StructuredObject as Experimental_StructuredObject, } from './structured-object.svelte.js';
1
+ export { Chat } from './chat.svelte.js';
3
2
  export { Completion } from './completion.svelte.js';
4
3
  export { createAIContext } from './context-provider.js';
5
- export { createChatStore } from './chat-store.svelte.js';
4
+ export { StructuredObject as Experimental_StructuredObject, } from './structured-object.svelte.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/svelte",
3
- "version": "3.0.0-alpha.8",
3
+ "version": "3.0.0-beta.1",
4
4
  "license": "Apache-2.0",
5
5
  "files": [
6
6
  "dist",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "peerDependencies": {
30
30
  "svelte": "^5.31.0",
31
- "zod": "^3.25.46"
31
+ "zod": "^3.25.49"
32
32
  },
33
33
  "peerDependenciesMeta": {
34
34
  "zod": {
@@ -36,8 +36,8 @@
36
36
  }
37
37
  },
38
38
  "dependencies": {
39
- "@ai-sdk/provider-utils": "3.0.0-alpha.8",
40
- "ai": "5.0.0-alpha.8"
39
+ "ai": "5.0.0-beta.1",
40
+ "@ai-sdk/provider-utils": "3.0.0-beta.1"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "20.17.24",
@@ -58,7 +58,7 @@
58
58
  "typescript-eslint": "^8.20.0",
59
59
  "vite": "^6.0.0",
60
60
  "vitest": "^3.0.0",
61
- "zod": "3.25.46",
61
+ "zod": "3.25.49",
62
62
  "@vercel/ai-tsconfig": "0.0.0"
63
63
  },
64
64
  "homepage": "https://ai-sdk.dev/docs",
@@ -1,218 +1,51 @@
1
1
  import {
2
- ChatStore,
3
- convertFileListToFileUIParts,
4
- defaultChatStoreOptions,
5
- generateId,
6
- type ChatRequestOptions,
2
+ AbstractChat,
3
+ type ChatInit,
4
+ type ChatState,
7
5
  type ChatStatus,
8
6
  type CreateUIMessage,
9
- type IdGenerator,
10
- type InferUIDataParts,
11
- type UIDataPartSchemas,
12
7
  type UIMessage,
13
- type UseChatOptions,
14
8
  } from 'ai';
15
- import {
16
- getChatStoreContext,
17
- hasChatStoreContext,
18
- createChatStore,
19
- } from './chat-store.svelte.js';
20
-
21
- export type ChatOptions<
22
- MESSAGE_METADATA = unknown,
23
- DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,
24
- > = Readonly<UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>>;
25
9
 
26
10
  export type { CreateUIMessage, UIMessage };
27
11
 
28
12
  export class Chat<
29
- MESSAGE_METADATA = unknown,
30
- DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,
31
- > {
32
- readonly #options: ChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>;
33
- readonly #generateId: IdGenerator;
34
- readonly #chatStore: ChatStore<MESSAGE_METADATA, DATA_PART_SCHEMAS>;
35
- /**
36
- * The id of the chat. If not provided through the constructor, a random ID will be generated
37
- * using the provided `generateId` function, or a built-in function if not provided.
38
- */
39
- readonly chatId: string;
40
-
41
- /** The current value of the input. Writable, so it can be bound to form inputs. */
42
- input = $state<string>('');
43
-
44
- /**
45
- * Current messages in the chat.
46
- *
47
- * This is writable, which is useful when you want to edit the messages on the client, and then
48
- * trigger {@link reload} to regenerate the AI response.
49
- */
50
- get messages(): UIMessage<
51
- MESSAGE_METADATA,
52
- InferUIDataParts<DATA_PART_SCHEMAS>
53
- >[] {
54
- return this.#chatStore.getMessages(this.chatId);
55
- }
56
- set messages(
57
- messages: UIMessage<
58
- MESSAGE_METADATA,
59
- InferUIDataParts<DATA_PART_SCHEMAS>
60
- >[],
61
- ) {
62
- this.#chatStore.setMessages({ id: this.chatId, messages });
63
- }
64
-
65
- /**
66
- * Hook status:
67
- *
68
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
69
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
70
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
71
- * - `error`: An error occurred during the API request, preventing successful completion.
72
- */
73
- get status(): ChatStatus {
74
- return this.#chatStore.getStatus(this.chatId);
75
- }
76
- set status(value: ChatStatus) {
77
- this.#chatStore.setStatus({ id: this.chatId, status: value });
78
- }
79
-
80
- /** The error object of the API request */
81
- get error(): Error | undefined {
82
- return this.#chatStore.getError(this.chatId);
83
- }
84
- set error(value: Error | undefined) {
85
- this.#chatStore.setStatus({
86
- id: this.chatId,
87
- status: 'error',
88
- error: value,
13
+ UI_MESSAGE extends UIMessage = UIMessage,
14
+ > extends AbstractChat<UI_MESSAGE> {
15
+ constructor(init: ChatInit<UI_MESSAGE>) {
16
+ super({
17
+ ...init,
18
+ state: new SvelteChatState(init.messages),
89
19
  });
90
20
  }
21
+ }
91
22
 
92
- constructor(
93
- options: () => ChatOptions<
94
- MESSAGE_METADATA,
95
- DATA_PART_SCHEMAS
96
- > = () => ({}),
97
- ) {
98
- this.#options = $derived.by(options);
99
- this.#generateId = $derived(this.#options.generateId ?? generateId);
100
- this.chatId = $derived(this.#options.chatId ?? this.#generateId());
101
-
102
- if (this.#options.chatStore) {
103
- if (typeof this.#options.chatStore === 'function') {
104
- this.#chatStore = createChatStore(this.#options.chatStore());
105
- } else {
106
- this.#chatStore = this.#options.chatStore;
107
- }
108
- } else if (hasChatStoreContext()) {
109
- this.#chatStore = getChatStoreContext() as ChatStore<
110
- MESSAGE_METADATA,
111
- DATA_PART_SCHEMAS
112
- >;
113
- } else {
114
- this.#chatStore = createChatStore(
115
- defaultChatStoreOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>({
116
- api: '/api/chat',
117
- generateId: this.#options.generateId || generateId,
118
- })(),
119
- );
120
- }
121
-
122
- this.input = this.#options.initialInput ?? '';
23
+ class SvelteChatState<UI_MESSAGE extends UIMessage>
24
+ implements ChatState<UI_MESSAGE>
25
+ {
26
+ messages: UI_MESSAGE[];
27
+ status = $state<ChatStatus>('ready');
28
+ error = $state<Error | undefined>(undefined);
123
29
 
124
- if (!this.#chatStore.hasChat(this.chatId)) {
125
- const messages = $state([]);
126
- this.#chatStore.addChat(this.chatId, messages);
127
- }
30
+ constructor(messages: UI_MESSAGE[] = []) {
31
+ this.messages = $state(messages);
128
32
  }
129
33
 
130
- /**
131
- * Append a user message to the chat list. This triggers the API call to fetch
132
- * the assistant's response.
133
- * @param message The message to append
134
- * @param options Additional options to pass to the API call
135
- */
136
- append = async (
137
- message:
138
- | UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>
139
- | CreateUIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>,
140
- { headers, body }: ChatRequestOptions = {},
141
- ) => {
142
- await this.#chatStore.submitMessage({
143
- chatId: this.chatId,
144
- message,
145
- headers,
146
- body,
147
- onError: this.#options.onError,
148
- onToolCall: this.#options.onToolCall,
149
- onFinish: this.#options.onFinish,
150
- });
34
+ setMessages = (messages: UI_MESSAGE[]) => {
35
+ this.messages = messages;
151
36
  };
152
37
 
153
- /**
154
- * Reload the last AI chat response for the given chat history. If the last
155
- * message isn't from the assistant, it will request the API to generate a
156
- * new response.
157
- */
158
- reload = async ({ headers, body }: ChatRequestOptions = {}) => {
159
- await this.#chatStore.resubmitLastUserMessage({
160
- chatId: this.chatId,
161
- headers,
162
- body,
163
- onError: this.#options.onError,
164
- onToolCall: this.#options.onToolCall,
165
- onFinish: this.#options.onFinish,
166
- });
38
+ pushMessage = (message: UI_MESSAGE) => {
39
+ this.messages.push(message);
167
40
  };
168
41
 
169
- /**
170
- * Abort the current request immediately, keep the generated tokens if any.
171
- */
172
- stop = () => {
173
- this.#chatStore.stopStream({ chatId: this.chatId });
42
+ popMessage = () => {
43
+ this.messages.pop();
174
44
  };
175
45
 
176
- /** Form submission handler to automatically reset input and append a user message */
177
- handleSubmit = async (
178
- event?: { preventDefault?: () => void },
179
- options: ChatRequestOptions & { files?: FileList } = {},
180
- ) => {
181
- event?.preventDefault?.();
182
-
183
- const fileParts = Array.isArray(options?.files)
184
- ? options.files
185
- : await convertFileListToFileUIParts(options?.files);
186
-
187
- if (!this.input && fileParts.length === 0) return;
188
-
189
- const request = this.append(
190
- {
191
- id: this.#generateId(),
192
- role: 'user',
193
- parts: [...fileParts, { type: 'text', text: this.input }],
194
- },
195
- {
196
- headers: options.headers,
197
- body: options.body,
198
- },
199
- );
200
-
201
- this.input = '';
202
- await request;
46
+ replaceMessage = (index: number, message: UI_MESSAGE) => {
47
+ this.messages[index] = message;
203
48
  };
204
49
 
205
- addToolResult = async ({
206
- toolCallId,
207
- result,
208
- }: {
209
- toolCallId: string;
210
- result: unknown;
211
- }) => {
212
- await this.#chatStore.addToolResult({
213
- chatId: this.chatId,
214
- toolCallId,
215
- result,
216
- });
217
- };
50
+ snapshot = <T>(thing: T): T => $state.snapshot(thing) as T;
218
51
  }
@@ -1,5 +1,3 @@
1
- import { defaultChatStoreOptions, type ChatStore } from 'ai';
2
- import { createChatStore, setChatStoreContext } from './chat-store.svelte.js';
3
1
  import {
4
2
  KeyedCompletionStore,
5
3
  setCompletionContext,
@@ -9,23 +7,10 @@ import {
9
7
  setStructuredObjectContext,
10
8
  } from './structured-object-context.svelte.js';
11
9
 
12
- export function createAIContext(chatStore?: ChatStore) {
13
- createChatStoreContext(chatStore);
14
-
10
+ export function createAIContext() {
15
11
  const completionStore = new KeyedCompletionStore();
16
12
  setCompletionContext(completionStore);
17
13
 
18
14
  const objectStore = new KeyedStructuredObjectStore();
19
15
  setStructuredObjectContext(objectStore);
20
16
  }
21
-
22
- export function createChatStoreContext(chatStore?: ChatStore) {
23
- setChatStoreContext(
24
- chatStore ??
25
- createChatStore(
26
- defaultChatStoreOptions({
27
- api: '/api/chat',
28
- })(),
29
- ),
30
- );
31
- }
package/src/index.ts CHANGED
@@ -1,17 +1,7 @@
1
- export {
2
- Chat,
3
- type ChatOptions,
4
- type CreateUIMessage,
5
- type UIMessage,
6
- } from './chat.svelte.js';
7
-
1
+ export { Chat, type CreateUIMessage, type UIMessage } from './chat.svelte.js';
2
+ export { Completion, type CompletionOptions } from './completion.svelte.js';
3
+ export { createAIContext } from './context-provider.js';
8
4
  export {
9
5
  StructuredObject as Experimental_StructuredObject,
10
6
  type Experimental_StructuredObjectOptions,
11
7
  } from './structured-object.svelte.js';
12
-
13
- export { Completion, type CompletionOptions } from './completion.svelte.js';
14
-
15
- export { createAIContext } from './context-provider.js';
16
-
17
- export { createChatStore } from './chat-store.svelte.js';
@@ -1,4 +0,0 @@
1
- import { ChatStore, type ChatStoreOptions, type UIDataPartSchemas } from 'ai';
2
- export declare const hasChatStoreContext: () => boolean, getChatStoreContext: () => ChatStore<unknown, UIDataPartSchemas>, setChatStoreContext: (value: ChatStore<unknown, UIDataPartSchemas>) => ChatStore<unknown, UIDataPartSchemas>;
3
- export declare function createChatStore<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas>(options: ChatStoreOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>): ChatStore<MESSAGE_METADATA, DATA_PART_SCHEMAS>;
4
- //# sourceMappingURL=chat-store.svelte.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat-store.svelte.d.ts","sourceRoot":"","sources":["../src/chat-store.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAKT,KAAK,gBAAgB,EAErB,KAAK,iBAAiB,EAGvB,MAAM,IAAI,CAAC;AAGZ,eAAO,MACO,mBAAmB,iBACnB,mBAAmB,+CACnB,mBAAmB,yFACQ,CAAC;AAqD1C,wBAAgB,eAAe,CAC7B,gBAAgB,GAAG,OAAO,EAC1B,iBAAiB,SAAS,iBAAiB,GAAG,iBAAiB,EAE/D,OAAO,EAAE,gBAAgB,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,GAC7D,SAAS,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,CAQhD"}
@@ -1,43 +0,0 @@
1
- import { ChatStore, SerialJobExecutor, } from 'ai';
2
- import { createContext } from './utils.svelte.js';
3
- export const { hasContext: hasChatStoreContext, getContext: getChatStoreContext, setContext: setChatStoreContext, } = createContext('ChatStore');
4
- class SvelteChat {
5
- messages;
6
- status = $state('ready');
7
- error = $state(undefined);
8
- activeResponse = undefined;
9
- jobExecutor = new SerialJobExecutor();
10
- constructor(messages) {
11
- this.messages = $state(messages ?? []);
12
- }
13
- setStatus = (status) => {
14
- this.status = status;
15
- };
16
- setError = (error) => {
17
- this.error = error;
18
- };
19
- setActiveResponse = (activeResponse) => {
20
- this.activeResponse = activeResponse;
21
- };
22
- setMessages = (messages) => {
23
- this.messages = messages;
24
- };
25
- pushMessage = (message) => {
26
- this.messages.push(message);
27
- };
28
- popMessage = () => {
29
- this.messages.pop();
30
- };
31
- replaceMessage = (index, message) => {
32
- this.messages[index] = message;
33
- };
34
- snapshot = (thing) => {
35
- return $state.snapshot(thing);
36
- };
37
- }
38
- export function createChatStore(options) {
39
- return new ChatStore({
40
- ...options,
41
- createChat: options => new SvelteChat(options.messages),
42
- });
43
- }
@@ -1,16 +0,0 @@
1
- <script lang="ts">
2
- import { createChatStore } from '../chat-store.svelte.js';
3
- import { Chat } from '../chat.svelte.js';
4
- import { defaultChatStoreOptions } from 'ai';
5
- import { createAIContext } from '../context-provider.js';
6
-
7
- let { chatId }: { chatId?: string } = $props();
8
-
9
- createAIContext(
10
- createChatStore(defaultChatStoreOptions({ api: '/api/chat' })()),
11
- );
12
- const chat1 = new Chat(() => ({ chatId }));
13
- const chat2 = new Chat(() => ({ chatId }));
14
-
15
- export { chat1, chat2 };
16
- </script>
@@ -1,11 +0,0 @@
1
- import { Chat } from '../chat.svelte.js';
2
- type $$ComponentProps = {
3
- chatId?: string;
4
- };
5
- declare const ChatSynchronization: import("svelte").Component<$$ComponentProps, {
6
- chat1: Chat<unknown, import("ai").UIDataPartSchemas>;
7
- chat2: Chat<unknown, import("ai").UIDataPartSchemas>;
8
- }, "">;
9
- type ChatSynchronization = ReturnType<typeof ChatSynchronization>;
10
- export default ChatSynchronization;
11
- //# sourceMappingURL=chat-synchronization.svelte.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat-synchronization.svelte.d.ts","sourceRoot":"","sources":["../../src/tests/chat-synchronization.svelte.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAIxC,KAAK,gBAAgB,GAAI;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAoB9C,QAAA,MAAM,mBAAmB;;;MAAsC,CAAC;AAChE,KAAK,mBAAmB,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAClE,eAAe,mBAAmB,CAAC"}
@@ -1,85 +0,0 @@
1
- import {
2
- ChatStore,
3
- SerialJobExecutor,
4
- type ActiveResponse,
5
- type Chat,
6
- type ChatStatus,
7
- type ChatStoreOptions,
8
- type InferUIDataParts,
9
- type UIDataPartSchemas,
10
- type UIDataTypes,
11
- type UIMessage,
12
- } from 'ai';
13
- import { createContext } from './utils.svelte.js';
14
-
15
- export const {
16
- hasContext: hasChatStoreContext,
17
- getContext: getChatStoreContext,
18
- setContext: setChatStoreContext,
19
- } = createContext<ChatStore>('ChatStore');
20
-
21
- class SvelteChat<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes>
22
- implements Chat<MESSAGE_METADATA, DATA_TYPES>
23
- {
24
- messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
25
- status = $state<ChatStatus>('ready');
26
- error = $state<Error | undefined>(undefined);
27
- activeResponse: ActiveResponse<MESSAGE_METADATA> | undefined = undefined;
28
- jobExecutor = new SerialJobExecutor();
29
-
30
- constructor(messages?: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) {
31
- this.messages = $state(messages ?? []);
32
- }
33
-
34
- setStatus = (status: ChatStatus) => {
35
- this.status = status;
36
- };
37
-
38
- setError = (error: Error | undefined) => {
39
- this.error = error;
40
- };
41
-
42
- setActiveResponse = (
43
- activeResponse: ActiveResponse<MESSAGE_METADATA> | undefined,
44
- ) => {
45
- this.activeResponse = activeResponse;
46
- };
47
-
48
- setMessages = (messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) => {
49
- this.messages = messages;
50
- };
51
-
52
- pushMessage = (message: UIMessage<MESSAGE_METADATA, DATA_TYPES>) => {
53
- this.messages.push(message);
54
- };
55
-
56
- popMessage = () => {
57
- this.messages.pop();
58
- };
59
-
60
- replaceMessage = (
61
- index: number,
62
- message: UIMessage<MESSAGE_METADATA, DATA_TYPES>,
63
- ) => {
64
- this.messages[index] = message;
65
- };
66
-
67
- snapshot = <T>(thing: T): T => {
68
- return $state.snapshot(thing) as T;
69
- };
70
- }
71
-
72
- export function createChatStore<
73
- MESSAGE_METADATA = unknown,
74
- DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,
75
- >(
76
- options: ChatStoreOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>,
77
- ): ChatStore<MESSAGE_METADATA, DATA_PART_SCHEMAS> {
78
- return new ChatStore<MESSAGE_METADATA, DATA_PART_SCHEMAS>({
79
- ...options,
80
- createChat: options =>
81
- new SvelteChat<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>(
82
- options.messages,
83
- ),
84
- });
85
- }
@@ -1,16 +0,0 @@
1
- <script lang="ts">
2
- import { createChatStore } from '../chat-store.svelte.js';
3
- import { Chat } from '../chat.svelte.js';
4
- import { defaultChatStoreOptions } from 'ai';
5
- import { createAIContext } from '../context-provider.js';
6
-
7
- let { chatId }: { chatId?: string } = $props();
8
-
9
- createAIContext(
10
- createChatStore(defaultChatStoreOptions({ api: '/api/chat' })()),
11
- );
12
- const chat1 = new Chat(() => ({ chatId }));
13
- const chat2 = new Chat(() => ({ chatId }));
14
-
15
- export { chat1, chat2 };
16
- </script>