@ai-gui/vercel-ai 0.3.0

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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Liang Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @ai-gui/vercel-ai
2
+
3
+ Convert Vercel AI SDK streams into AIGUI's provider-neutral `ModelStreamEvent` protocol. The `ai` package is not required.
4
+
5
+ ```ts
6
+ import { contentDeltas } from "@ai-gui/core"
7
+ import { vercelAIStream } from "@ai-gui/vercel-ai"
8
+
9
+ const response = await fetch("/api/chat")
10
+ await renderer.feed(contentDeltas(vercelAIStream(response)))
11
+ ```
12
+
13
+ `vercelAIStream(source, options)` accepts AI SDK `fullStream` object parts, a fetch `Response`, a byte stream using the data stream protocol, or SSE UI message parts. Set `protocol: "sse" | "data"` when a raw stream does not carry response headers. Tool calls and tool results are ignored and never executed.
package/dist/index.cjs ADDED
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+
24
+ //#endregion
25
+ const __ai_gui_core = __toESM(require("@ai-gui/core"));
26
+
27
+ //#region src/index.ts
28
+ async function* vercelAIStream(source, options = {}) {
29
+ for await (const part of parts(source, options)) yield* convert(part);
30
+ }
31
+ async function* parts(source, options) {
32
+ if (!isTransport(source)) {
33
+ const iterator = source[Symbol.asyncIterator]();
34
+ let done = false;
35
+ let delegated = false;
36
+ try {
37
+ const first = await next(iterator, options.signal);
38
+ if (first.done) {
39
+ done = true;
40
+ return;
41
+ }
42
+ if (typeof first.value === "string" || first.value instanceof Uint8Array) {
43
+ delegated = true;
44
+ yield* transportParts(prepend(first.value, iterator), options, options.protocol === "sse" ? "sse" : "data");
45
+ return;
46
+ }
47
+ yield first.value;
48
+ for (;;) {
49
+ const result = await next(iterator, options.signal);
50
+ if (result.done) {
51
+ done = true;
52
+ return;
53
+ }
54
+ yield result.value;
55
+ }
56
+ } finally {
57
+ if (!done && !delegated) await iterator.return?.();
58
+ }
59
+ }
60
+ const protocol = options.protocol === "sse" || options.protocol !== "data" && isSSEResponse(source) ? "sse" : "data";
61
+ yield* transportParts(source, options, protocol);
62
+ }
63
+ async function* transportParts(source, options, protocol) {
64
+ if (protocol === "sse") {
65
+ for await (const event of (0, __ai_gui_core.parseSSE)(source, {
66
+ ...options,
67
+ parseJSON: true
68
+ })) yield event.data;
69
+ return;
70
+ }
71
+ for await (const line of (0, __ai_gui_core.textLines)(source, options)) {
72
+ if (!line) continue;
73
+ const colon = line.indexOf(":");
74
+ if (colon < 0) {
75
+ malformed(options, `Invalid Vercel AI data stream line: ${line}`, line);
76
+ continue;
77
+ }
78
+ const code = line.slice(0, colon);
79
+ const input = line.slice(colon + 1);
80
+ try {
81
+ yield {
82
+ __dataCode: code,
83
+ value: JSON.parse(input)
84
+ };
85
+ } catch (cause) {
86
+ const error = new SyntaxError(`Invalid Vercel AI data stream JSON: ${input}`, { cause });
87
+ if (options.onMalformed?.(error, input) !== "skip") throw error;
88
+ }
89
+ }
90
+ }
91
+ async function* convert(value) {
92
+ const part = object(value);
93
+ if (!part) return;
94
+ const code = text(part.__dataCode);
95
+ if (code !== void 0) {
96
+ const payload = part.value;
97
+ if (code === "0") {
98
+ if (typeof payload === "string") yield {
99
+ type: "content",
100
+ delta: payload
101
+ };
102
+ } else if (code === "8") for (const item of Array.isArray(payload) ? payload : [payload]) {
103
+ const data = citation(item);
104
+ if (data) yield {
105
+ type: "citation",
106
+ data
107
+ };
108
+ }
109
+ else if (code === "d" || code === "e") {
110
+ const data = usage(object(payload)?.usage);
111
+ if (data) yield {
112
+ type: "usage",
113
+ data
114
+ };
115
+ } else if (code === "3") yield {
116
+ type: "error",
117
+ error: payload
118
+ };
119
+ else if (code === "g") yield* convert(payload);
120
+ return;
121
+ }
122
+ const type = text(part.type);
123
+ if (type === "text-delta") {
124
+ const delta = text(part.textDelta) ?? text(part.delta);
125
+ if (delta) yield {
126
+ type: "content",
127
+ delta
128
+ };
129
+ } else if (type === "reasoning-delta") {
130
+ const delta = text(part.textDelta) ?? text(part.delta);
131
+ if (delta) yield {
132
+ type: "reasoning",
133
+ delta
134
+ };
135
+ } else if (type === "source" || type === "source-url" || type === "source-document") {
136
+ const data = citation(part.source ?? part);
137
+ if (data) yield {
138
+ type: "citation",
139
+ data
140
+ };
141
+ } else if (type === "finish" || type === "finish-step") {
142
+ const data = usage(part.totalUsage ?? part.usage);
143
+ if (data) yield {
144
+ type: "usage",
145
+ data
146
+ };
147
+ } else if (type === "error") yield {
148
+ type: "error",
149
+ error: part.errorText ?? part.error
150
+ };
151
+ }
152
+ function citation(value) {
153
+ const source = object(value);
154
+ if (!source) return void 0;
155
+ const result = defined({
156
+ type: text(source.type),
157
+ sourceType: text(source.sourceType),
158
+ id: text(source.id) ?? text(source.sourceId),
159
+ url: text(source.url),
160
+ title: text(source.title)
161
+ });
162
+ return Object.keys(result).length ? result : void 0;
163
+ }
164
+ function usage(value) {
165
+ const source = object(value);
166
+ if (!source) return void 0;
167
+ const inputTokens = numeric(source.inputTokens) ?? numeric(source.promptTokens);
168
+ const outputTokens = numeric(source.outputTokens) ?? numeric(source.completionTokens);
169
+ const totalTokens = numeric(source.totalTokens) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0);
170
+ return inputTokens === void 0 && outputTokens === void 0 && totalTokens === void 0 ? void 0 : defined({
171
+ inputTokens,
172
+ outputTokens,
173
+ totalTokens
174
+ });
175
+ }
176
+ function malformed(options, message, input) {
177
+ const error = new SyntaxError(message);
178
+ if (options.onMalformed?.(error, input) !== "skip") throw error;
179
+ }
180
+ function isSSEResponse(value) {
181
+ return typeof Response !== "undefined" && value instanceof Response && (value.headers.get("content-type") ?? "").includes("text/event-stream");
182
+ }
183
+ function isTransport(value) {
184
+ return typeof Response !== "undefined" && value instanceof Response || typeof value === "object" && value !== null && "getReader" in value;
185
+ }
186
+ async function* prepend(first, iterator) {
187
+ let done = false;
188
+ try {
189
+ yield first;
190
+ for (;;) {
191
+ const result = await iterator.next();
192
+ if (result.done) {
193
+ done = true;
194
+ return;
195
+ }
196
+ if (typeof result.value !== "string" && !(result.value instanceof Uint8Array)) throw new TypeError("Mixed Vercel AI stream chunk types");
197
+ yield result.value;
198
+ }
199
+ } finally {
200
+ if (!done) await iterator.return?.();
201
+ }
202
+ }
203
+ async function next(iterator, signal) {
204
+ if (!signal) return iterator.next();
205
+ if (signal.aborted) throw abortReason(signal);
206
+ const pending = Promise.resolve(iterator.next());
207
+ let abort;
208
+ const aborted = new Promise((_resolve, reject) => {
209
+ abort = () => reject(abortReason(signal));
210
+ signal.addEventListener("abort", abort, { once: true });
211
+ });
212
+ try {
213
+ const result = await Promise.race([pending, aborted]);
214
+ if (signal.aborted) throw abortReason(signal);
215
+ return result;
216
+ } finally {
217
+ signal.removeEventListener("abort", abort);
218
+ }
219
+ }
220
+ function abortReason(signal) {
221
+ if (signal.reason !== void 0) return signal.reason;
222
+ const error = new Error("The operation was aborted");
223
+ error.name = "AbortError";
224
+ return error;
225
+ }
226
+ function object(value) {
227
+ return typeof value === "object" && value !== null ? value : void 0;
228
+ }
229
+ function text(value) {
230
+ return typeof value === "string" ? value : void 0;
231
+ }
232
+ function numeric(value) {
233
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
234
+ }
235
+ function defined(value) {
236
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
237
+ }
238
+
239
+ //#endregion
240
+ exports.vercelAIStream = vercelAIStream
@@ -0,0 +1,11 @@
1
+ import { ByteStreamSource, ModelStreamEvent, StreamParseOptions } from "@ai-gui/core";
2
+
3
+ //#region src/index.d.ts
4
+ type VercelAIStreamSource = ByteStreamSource | AsyncIterable<unknown>;
5
+ type VercelAIStreamOptions = StreamParseOptions & {
6
+ protocol?: "auto" | "sse" | "data";
7
+ };
8
+ declare function vercelAIStream(source: VercelAIStreamSource, options?: VercelAIStreamOptions): AsyncGenerator<ModelStreamEvent>;
9
+
10
+ //#endregion
11
+ export { VercelAIStreamOptions, VercelAIStreamSource, vercelAIStream };
@@ -0,0 +1,11 @@
1
+ import { ByteStreamSource, ModelStreamEvent, StreamParseOptions } from "@ai-gui/core";
2
+
3
+ //#region src/index.d.ts
4
+ type VercelAIStreamSource = ByteStreamSource | AsyncIterable<unknown>;
5
+ type VercelAIStreamOptions = StreamParseOptions & {
6
+ protocol?: "auto" | "sse" | "data";
7
+ };
8
+ declare function vercelAIStream(source: VercelAIStreamSource, options?: VercelAIStreamOptions): AsyncGenerator<ModelStreamEvent>;
9
+
10
+ //#endregion
11
+ export { VercelAIStreamOptions, VercelAIStreamSource, vercelAIStream };
package/dist/index.js ADDED
@@ -0,0 +1,216 @@
1
+ import { parseSSE, textLines } from "@ai-gui/core";
2
+
3
+ //#region src/index.ts
4
+ async function* vercelAIStream(source, options = {}) {
5
+ for await (const part of parts(source, options)) yield* convert(part);
6
+ }
7
+ async function* parts(source, options) {
8
+ if (!isTransport(source)) {
9
+ const iterator = source[Symbol.asyncIterator]();
10
+ let done = false;
11
+ let delegated = false;
12
+ try {
13
+ const first = await next(iterator, options.signal);
14
+ if (first.done) {
15
+ done = true;
16
+ return;
17
+ }
18
+ if (typeof first.value === "string" || first.value instanceof Uint8Array) {
19
+ delegated = true;
20
+ yield* transportParts(prepend(first.value, iterator), options, options.protocol === "sse" ? "sse" : "data");
21
+ return;
22
+ }
23
+ yield first.value;
24
+ for (;;) {
25
+ const result = await next(iterator, options.signal);
26
+ if (result.done) {
27
+ done = true;
28
+ return;
29
+ }
30
+ yield result.value;
31
+ }
32
+ } finally {
33
+ if (!done && !delegated) await iterator.return?.();
34
+ }
35
+ }
36
+ const protocol = options.protocol === "sse" || options.protocol !== "data" && isSSEResponse(source) ? "sse" : "data";
37
+ yield* transportParts(source, options, protocol);
38
+ }
39
+ async function* transportParts(source, options, protocol) {
40
+ if (protocol === "sse") {
41
+ for await (const event of parseSSE(source, {
42
+ ...options,
43
+ parseJSON: true
44
+ })) yield event.data;
45
+ return;
46
+ }
47
+ for await (const line of textLines(source, options)) {
48
+ if (!line) continue;
49
+ const colon = line.indexOf(":");
50
+ if (colon < 0) {
51
+ malformed(options, `Invalid Vercel AI data stream line: ${line}`, line);
52
+ continue;
53
+ }
54
+ const code = line.slice(0, colon);
55
+ const input = line.slice(colon + 1);
56
+ try {
57
+ yield {
58
+ __dataCode: code,
59
+ value: JSON.parse(input)
60
+ };
61
+ } catch (cause) {
62
+ const error = new SyntaxError(`Invalid Vercel AI data stream JSON: ${input}`, { cause });
63
+ if (options.onMalformed?.(error, input) !== "skip") throw error;
64
+ }
65
+ }
66
+ }
67
+ async function* convert(value) {
68
+ const part = object(value);
69
+ if (!part) return;
70
+ const code = text(part.__dataCode);
71
+ if (code !== void 0) {
72
+ const payload = part.value;
73
+ if (code === "0") {
74
+ if (typeof payload === "string") yield {
75
+ type: "content",
76
+ delta: payload
77
+ };
78
+ } else if (code === "8") for (const item of Array.isArray(payload) ? payload : [payload]) {
79
+ const data = citation(item);
80
+ if (data) yield {
81
+ type: "citation",
82
+ data
83
+ };
84
+ }
85
+ else if (code === "d" || code === "e") {
86
+ const data = usage(object(payload)?.usage);
87
+ if (data) yield {
88
+ type: "usage",
89
+ data
90
+ };
91
+ } else if (code === "3") yield {
92
+ type: "error",
93
+ error: payload
94
+ };
95
+ else if (code === "g") yield* convert(payload);
96
+ return;
97
+ }
98
+ const type = text(part.type);
99
+ if (type === "text-delta") {
100
+ const delta = text(part.textDelta) ?? text(part.delta);
101
+ if (delta) yield {
102
+ type: "content",
103
+ delta
104
+ };
105
+ } else if (type === "reasoning-delta") {
106
+ const delta = text(part.textDelta) ?? text(part.delta);
107
+ if (delta) yield {
108
+ type: "reasoning",
109
+ delta
110
+ };
111
+ } else if (type === "source" || type === "source-url" || type === "source-document") {
112
+ const data = citation(part.source ?? part);
113
+ if (data) yield {
114
+ type: "citation",
115
+ data
116
+ };
117
+ } else if (type === "finish" || type === "finish-step") {
118
+ const data = usage(part.totalUsage ?? part.usage);
119
+ if (data) yield {
120
+ type: "usage",
121
+ data
122
+ };
123
+ } else if (type === "error") yield {
124
+ type: "error",
125
+ error: part.errorText ?? part.error
126
+ };
127
+ }
128
+ function citation(value) {
129
+ const source = object(value);
130
+ if (!source) return void 0;
131
+ const result = defined({
132
+ type: text(source.type),
133
+ sourceType: text(source.sourceType),
134
+ id: text(source.id) ?? text(source.sourceId),
135
+ url: text(source.url),
136
+ title: text(source.title)
137
+ });
138
+ return Object.keys(result).length ? result : void 0;
139
+ }
140
+ function usage(value) {
141
+ const source = object(value);
142
+ if (!source) return void 0;
143
+ const inputTokens = numeric(source.inputTokens) ?? numeric(source.promptTokens);
144
+ const outputTokens = numeric(source.outputTokens) ?? numeric(source.completionTokens);
145
+ const totalTokens = numeric(source.totalTokens) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0);
146
+ return inputTokens === void 0 && outputTokens === void 0 && totalTokens === void 0 ? void 0 : defined({
147
+ inputTokens,
148
+ outputTokens,
149
+ totalTokens
150
+ });
151
+ }
152
+ function malformed(options, message, input) {
153
+ const error = new SyntaxError(message);
154
+ if (options.onMalformed?.(error, input) !== "skip") throw error;
155
+ }
156
+ function isSSEResponse(value) {
157
+ return typeof Response !== "undefined" && value instanceof Response && (value.headers.get("content-type") ?? "").includes("text/event-stream");
158
+ }
159
+ function isTransport(value) {
160
+ return typeof Response !== "undefined" && value instanceof Response || typeof value === "object" && value !== null && "getReader" in value;
161
+ }
162
+ async function* prepend(first, iterator) {
163
+ let done = false;
164
+ try {
165
+ yield first;
166
+ for (;;) {
167
+ const result = await iterator.next();
168
+ if (result.done) {
169
+ done = true;
170
+ return;
171
+ }
172
+ if (typeof result.value !== "string" && !(result.value instanceof Uint8Array)) throw new TypeError("Mixed Vercel AI stream chunk types");
173
+ yield result.value;
174
+ }
175
+ } finally {
176
+ if (!done) await iterator.return?.();
177
+ }
178
+ }
179
+ async function next(iterator, signal) {
180
+ if (!signal) return iterator.next();
181
+ if (signal.aborted) throw abortReason(signal);
182
+ const pending = Promise.resolve(iterator.next());
183
+ let abort;
184
+ const aborted = new Promise((_resolve, reject) => {
185
+ abort = () => reject(abortReason(signal));
186
+ signal.addEventListener("abort", abort, { once: true });
187
+ });
188
+ try {
189
+ const result = await Promise.race([pending, aborted]);
190
+ if (signal.aborted) throw abortReason(signal);
191
+ return result;
192
+ } finally {
193
+ signal.removeEventListener("abort", abort);
194
+ }
195
+ }
196
+ function abortReason(signal) {
197
+ if (signal.reason !== void 0) return signal.reason;
198
+ const error = new Error("The operation was aborted");
199
+ error.name = "AbortError";
200
+ return error;
201
+ }
202
+ function object(value) {
203
+ return typeof value === "object" && value !== null ? value : void 0;
204
+ }
205
+ function text(value) {
206
+ return typeof value === "string" ? value : void 0;
207
+ }
208
+ function numeric(value) {
209
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
210
+ }
211
+ function defined(value) {
212
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
213
+ }
214
+
215
+ //#endregion
216
+ export { vercelAIStream };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@ai-gui/vercel-ai",
3
+ "version": "0.3.0",
4
+ "description": "Vercel AI SDK model stream adapter for AIGUI.",
5
+ "keywords": [
6
+ "vercel",
7
+ "ai-sdk",
8
+ "llm",
9
+ "streaming",
10
+ "aigui"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Liang Li <ll_faw@hotmail.com>",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/liliang-cn/aigui.git",
17
+ "directory": "packages/vercel-ai"
18
+ },
19
+ "homepage": "https://github.com/liliang-cn/aigui#readme",
20
+ "bugs": "https://github.com/liliang-cn/aigui/issues",
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/index.d.cts",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "dependencies": {
50
+ "@ai-gui/core": "0.3.0"
51
+ },
52
+ "scripts": {
53
+ "build": "tsdown",
54
+ "test": "pnpm --dir ../.. exec vitest run --project vercel-ai",
55
+ "typecheck": "tsc --noEmit"
56
+ }
57
+ }