@ai-gui/openai 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/openai
2
+
3
+ Convert OpenAI Responses API or Chat Completions streams into AIGUI's provider-neutral `ModelStreamEvent` protocol. No OpenAI SDK is required.
4
+
5
+ ```ts
6
+ import { contentDeltas } from "@ai-gui/core"
7
+ import { openAIStream } from "@ai-gui/openai"
8
+
9
+ const response = await fetch("/api/openai")
10
+ await renderer.feed(contentDeltas(openAIStream(response)))
11
+ ```
12
+
13
+ `openAIStream(source, { signal, onMalformed })` accepts a fetch `Response`, `ReadableStream<Uint8Array>`, SSE byte `AsyncIterable`, or an SDK-shaped `AsyncIterable` of Responses/Chat Completions events. It emits content, reasoning, citations, usage, and errors. Tool calls are ignored and never executed.
package/dist/index.cjs ADDED
@@ -0,0 +1,225 @@
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* openAIStream(source, options = {}) {
29
+ for await (const value of events(source, options)) yield* convert(value);
30
+ }
31
+ async function* events(source, options) {
32
+ if (isTransport(source)) {
33
+ for await (const event of (0, __ai_gui_core.parseSSE)(source, {
34
+ ...options,
35
+ parseJSON: true
36
+ })) yield event.data;
37
+ return;
38
+ }
39
+ const iterator = source[Symbol.asyncIterator]();
40
+ let done = false;
41
+ let delegated = false;
42
+ try {
43
+ const first = await next(iterator, options.signal);
44
+ if (first.done) {
45
+ done = true;
46
+ return;
47
+ }
48
+ if (typeof first.value === "string" || first.value instanceof Uint8Array) {
49
+ delegated = true;
50
+ for await (const event of (0, __ai_gui_core.parseSSE)(prepend(first.value, iterator), {
51
+ ...options,
52
+ parseJSON: true
53
+ })) yield event.data;
54
+ return;
55
+ }
56
+ yield first.value;
57
+ for (;;) {
58
+ const result = await next(iterator, options.signal);
59
+ if (result.done) {
60
+ done = true;
61
+ return;
62
+ }
63
+ yield result.value;
64
+ }
65
+ } finally {
66
+ if (!done && !delegated) await iterator.return?.();
67
+ }
68
+ }
69
+ async function* convert(value) {
70
+ const event = object(value);
71
+ if (!event) return;
72
+ if (event.error !== void 0) {
73
+ yield {
74
+ type: "error",
75
+ error: event.error
76
+ };
77
+ return;
78
+ }
79
+ const type = text(event.type);
80
+ if (type === "error" || type === "response.failed" || type === "response.incomplete") yield {
81
+ type: "error",
82
+ error: event.error ?? event.response ?? event
83
+ };
84
+ else if (type === "response.output_text.delta" || type === "response.refusal.delta") {
85
+ if (text(event.delta)) yield {
86
+ type: "content",
87
+ delta: text(event.delta)
88
+ };
89
+ } else if (type === "response.reasoning_summary_text.delta" || type === "response.reasoning_text.delta") {
90
+ if (text(event.delta)) yield {
91
+ type: "reasoning",
92
+ delta: text(event.delta)
93
+ };
94
+ } else if (type === "response.output_text.annotation.added") {
95
+ const data = normalizeCitation(event.annotation);
96
+ if (data) yield {
97
+ type: "citation",
98
+ data
99
+ };
100
+ } else if (type === "response.completed") {
101
+ const data = normalizeUsage(object(event.response)?.usage);
102
+ if (data) yield {
103
+ type: "usage",
104
+ data
105
+ };
106
+ } else {
107
+ for (const choice of Array.isArray(event.choices) ? event.choices : []) {
108
+ const delta = object(object(choice)?.delta);
109
+ const reasoning = text(delta?.reasoning_content) ?? text(delta?.reasoning);
110
+ if (reasoning) yield {
111
+ type: "reasoning",
112
+ delta: reasoning
113
+ };
114
+ const content = contentText(delta?.content);
115
+ if (content) yield {
116
+ type: "content",
117
+ delta: content
118
+ };
119
+ for (const annotation of Array.isArray(delta?.annotations) ? delta.annotations : []) {
120
+ const data$1 = normalizeCitation(annotation);
121
+ if (data$1) yield {
122
+ type: "citation",
123
+ data: data$1
124
+ };
125
+ }
126
+ }
127
+ const data = normalizeUsage(event.usage);
128
+ if (data) yield {
129
+ type: "usage",
130
+ data
131
+ };
132
+ }
133
+ }
134
+ function normalizeUsage(value) {
135
+ const usage = object(value);
136
+ if (!usage) return void 0;
137
+ const inputTokens = numeric(usage.input_tokens) ?? numeric(usage.prompt_tokens);
138
+ const outputTokens = numeric(usage.output_tokens) ?? numeric(usage.completion_tokens);
139
+ const totalTokens = numeric(usage.total_tokens) ?? total(inputTokens, outputTokens);
140
+ return inputTokens === void 0 && outputTokens === void 0 && totalTokens === void 0 ? void 0 : defined({
141
+ inputTokens,
142
+ outputTokens,
143
+ totalTokens
144
+ });
145
+ }
146
+ function normalizeCitation(value) {
147
+ const outer = object(value);
148
+ if (!outer) return void 0;
149
+ const nested = object(outer.url_citation);
150
+ const source = nested ?? outer;
151
+ const result = defined({
152
+ type: text(source.type) ?? (nested ? "url_citation" : void 0),
153
+ id: text(source.id),
154
+ url: text(source.url),
155
+ title: text(source.title),
156
+ citedText: text(source.cited_text)
157
+ });
158
+ return Object.keys(result).length ? result : void 0;
159
+ }
160
+ function contentText(value) {
161
+ if (typeof value === "string") return value;
162
+ if (!Array.isArray(value)) return void 0;
163
+ return value.map((part) => text(object(part)?.text) ?? "").join("") || void 0;
164
+ }
165
+ function isTransport(value) {
166
+ return typeof Response !== "undefined" && value instanceof Response || typeof value === "object" && value !== null && "getReader" in value;
167
+ }
168
+ async function* prepend(first, iterator) {
169
+ let done = false;
170
+ try {
171
+ yield first;
172
+ for (;;) {
173
+ const result = await iterator.next();
174
+ if (result.done) {
175
+ done = true;
176
+ return;
177
+ }
178
+ if (typeof result.value !== "string" && !(result.value instanceof Uint8Array)) throw new TypeError("Mixed OpenAI stream chunk types");
179
+ yield result.value;
180
+ }
181
+ } finally {
182
+ if (!done) await iterator.return?.();
183
+ }
184
+ }
185
+ async function next(iterator, signal) {
186
+ if (!signal) return iterator.next();
187
+ if (signal.aborted) throw abortReason(signal);
188
+ const pending = Promise.resolve(iterator.next());
189
+ let abort;
190
+ const aborted = new Promise((_resolve, reject) => {
191
+ abort = () => reject(abortReason(signal));
192
+ signal.addEventListener("abort", abort, { once: true });
193
+ });
194
+ try {
195
+ const result = await Promise.race([pending, aborted]);
196
+ if (signal.aborted) throw abortReason(signal);
197
+ return result;
198
+ } finally {
199
+ signal.removeEventListener("abort", abort);
200
+ }
201
+ }
202
+ function abortReason(signal) {
203
+ if (signal.reason !== void 0) return signal.reason;
204
+ const error = new Error("The operation was aborted");
205
+ error.name = "AbortError";
206
+ return error;
207
+ }
208
+ function object(value) {
209
+ return typeof value === "object" && value !== null ? value : void 0;
210
+ }
211
+ function text(value) {
212
+ return typeof value === "string" ? value : void 0;
213
+ }
214
+ function numeric(value) {
215
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
216
+ }
217
+ function total(a, b) {
218
+ return a === void 0 || b === void 0 ? void 0 : a + b;
219
+ }
220
+ function defined(value) {
221
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
222
+ }
223
+
224
+ //#endregion
225
+ exports.openAIStream = openAIStream
@@ -0,0 +1,9 @@
1
+ import { ByteStreamSource, ModelStreamEvent, StreamParseOptions } from "@ai-gui/core";
2
+
3
+ //#region src/index.d.ts
4
+ type OpenAIStreamSource = ByteStreamSource | AsyncIterable<unknown>;
5
+ type OpenAIStreamOptions = StreamParseOptions;
6
+ declare function openAIStream(source: OpenAIStreamSource, options?: OpenAIStreamOptions): AsyncGenerator<ModelStreamEvent>;
7
+
8
+ //#endregion
9
+ export { OpenAIStreamOptions, OpenAIStreamSource, openAIStream };
@@ -0,0 +1,9 @@
1
+ import { ByteStreamSource, ModelStreamEvent, StreamParseOptions } from "@ai-gui/core";
2
+
3
+ //#region src/index.d.ts
4
+ type OpenAIStreamSource = ByteStreamSource | AsyncIterable<unknown>;
5
+ type OpenAIStreamOptions = StreamParseOptions;
6
+ declare function openAIStream(source: OpenAIStreamSource, options?: OpenAIStreamOptions): AsyncGenerator<ModelStreamEvent>;
7
+
8
+ //#endregion
9
+ export { OpenAIStreamOptions, OpenAIStreamSource, openAIStream };
package/dist/index.js ADDED
@@ -0,0 +1,201 @@
1
+ import { parseSSE } from "@ai-gui/core";
2
+
3
+ //#region src/index.ts
4
+ async function* openAIStream(source, options = {}) {
5
+ for await (const value of events(source, options)) yield* convert(value);
6
+ }
7
+ async function* events(source, options) {
8
+ if (isTransport(source)) {
9
+ for await (const event of parseSSE(source, {
10
+ ...options,
11
+ parseJSON: true
12
+ })) yield event.data;
13
+ return;
14
+ }
15
+ const iterator = source[Symbol.asyncIterator]();
16
+ let done = false;
17
+ let delegated = false;
18
+ try {
19
+ const first = await next(iterator, options.signal);
20
+ if (first.done) {
21
+ done = true;
22
+ return;
23
+ }
24
+ if (typeof first.value === "string" || first.value instanceof Uint8Array) {
25
+ delegated = true;
26
+ for await (const event of parseSSE(prepend(first.value, iterator), {
27
+ ...options,
28
+ parseJSON: true
29
+ })) yield event.data;
30
+ return;
31
+ }
32
+ yield first.value;
33
+ for (;;) {
34
+ const result = await next(iterator, options.signal);
35
+ if (result.done) {
36
+ done = true;
37
+ return;
38
+ }
39
+ yield result.value;
40
+ }
41
+ } finally {
42
+ if (!done && !delegated) await iterator.return?.();
43
+ }
44
+ }
45
+ async function* convert(value) {
46
+ const event = object(value);
47
+ if (!event) return;
48
+ if (event.error !== void 0) {
49
+ yield {
50
+ type: "error",
51
+ error: event.error
52
+ };
53
+ return;
54
+ }
55
+ const type = text(event.type);
56
+ if (type === "error" || type === "response.failed" || type === "response.incomplete") yield {
57
+ type: "error",
58
+ error: event.error ?? event.response ?? event
59
+ };
60
+ else if (type === "response.output_text.delta" || type === "response.refusal.delta") {
61
+ if (text(event.delta)) yield {
62
+ type: "content",
63
+ delta: text(event.delta)
64
+ };
65
+ } else if (type === "response.reasoning_summary_text.delta" || type === "response.reasoning_text.delta") {
66
+ if (text(event.delta)) yield {
67
+ type: "reasoning",
68
+ delta: text(event.delta)
69
+ };
70
+ } else if (type === "response.output_text.annotation.added") {
71
+ const data = normalizeCitation(event.annotation);
72
+ if (data) yield {
73
+ type: "citation",
74
+ data
75
+ };
76
+ } else if (type === "response.completed") {
77
+ const data = normalizeUsage(object(event.response)?.usage);
78
+ if (data) yield {
79
+ type: "usage",
80
+ data
81
+ };
82
+ } else {
83
+ for (const choice of Array.isArray(event.choices) ? event.choices : []) {
84
+ const delta = object(object(choice)?.delta);
85
+ const reasoning = text(delta?.reasoning_content) ?? text(delta?.reasoning);
86
+ if (reasoning) yield {
87
+ type: "reasoning",
88
+ delta: reasoning
89
+ };
90
+ const content = contentText(delta?.content);
91
+ if (content) yield {
92
+ type: "content",
93
+ delta: content
94
+ };
95
+ for (const annotation of Array.isArray(delta?.annotations) ? delta.annotations : []) {
96
+ const data$1 = normalizeCitation(annotation);
97
+ if (data$1) yield {
98
+ type: "citation",
99
+ data: data$1
100
+ };
101
+ }
102
+ }
103
+ const data = normalizeUsage(event.usage);
104
+ if (data) yield {
105
+ type: "usage",
106
+ data
107
+ };
108
+ }
109
+ }
110
+ function normalizeUsage(value) {
111
+ const usage = object(value);
112
+ if (!usage) return void 0;
113
+ const inputTokens = numeric(usage.input_tokens) ?? numeric(usage.prompt_tokens);
114
+ const outputTokens = numeric(usage.output_tokens) ?? numeric(usage.completion_tokens);
115
+ const totalTokens = numeric(usage.total_tokens) ?? total(inputTokens, outputTokens);
116
+ return inputTokens === void 0 && outputTokens === void 0 && totalTokens === void 0 ? void 0 : defined({
117
+ inputTokens,
118
+ outputTokens,
119
+ totalTokens
120
+ });
121
+ }
122
+ function normalizeCitation(value) {
123
+ const outer = object(value);
124
+ if (!outer) return void 0;
125
+ const nested = object(outer.url_citation);
126
+ const source = nested ?? outer;
127
+ const result = defined({
128
+ type: text(source.type) ?? (nested ? "url_citation" : void 0),
129
+ id: text(source.id),
130
+ url: text(source.url),
131
+ title: text(source.title),
132
+ citedText: text(source.cited_text)
133
+ });
134
+ return Object.keys(result).length ? result : void 0;
135
+ }
136
+ function contentText(value) {
137
+ if (typeof value === "string") return value;
138
+ if (!Array.isArray(value)) return void 0;
139
+ return value.map((part) => text(object(part)?.text) ?? "").join("") || void 0;
140
+ }
141
+ function isTransport(value) {
142
+ return typeof Response !== "undefined" && value instanceof Response || typeof value === "object" && value !== null && "getReader" in value;
143
+ }
144
+ async function* prepend(first, iterator) {
145
+ let done = false;
146
+ try {
147
+ yield first;
148
+ for (;;) {
149
+ const result = await iterator.next();
150
+ if (result.done) {
151
+ done = true;
152
+ return;
153
+ }
154
+ if (typeof result.value !== "string" && !(result.value instanceof Uint8Array)) throw new TypeError("Mixed OpenAI stream chunk types");
155
+ yield result.value;
156
+ }
157
+ } finally {
158
+ if (!done) await iterator.return?.();
159
+ }
160
+ }
161
+ async function next(iterator, signal) {
162
+ if (!signal) return iterator.next();
163
+ if (signal.aborted) throw abortReason(signal);
164
+ const pending = Promise.resolve(iterator.next());
165
+ let abort;
166
+ const aborted = new Promise((_resolve, reject) => {
167
+ abort = () => reject(abortReason(signal));
168
+ signal.addEventListener("abort", abort, { once: true });
169
+ });
170
+ try {
171
+ const result = await Promise.race([pending, aborted]);
172
+ if (signal.aborted) throw abortReason(signal);
173
+ return result;
174
+ } finally {
175
+ signal.removeEventListener("abort", abort);
176
+ }
177
+ }
178
+ function abortReason(signal) {
179
+ if (signal.reason !== void 0) return signal.reason;
180
+ const error = new Error("The operation was aborted");
181
+ error.name = "AbortError";
182
+ return error;
183
+ }
184
+ function object(value) {
185
+ return typeof value === "object" && value !== null ? value : void 0;
186
+ }
187
+ function text(value) {
188
+ return typeof value === "string" ? value : void 0;
189
+ }
190
+ function numeric(value) {
191
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
192
+ }
193
+ function total(a, b) {
194
+ return a === void 0 || b === void 0 ? void 0 : a + b;
195
+ }
196
+ function defined(value) {
197
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
198
+ }
199
+
200
+ //#endregion
201
+ export { openAIStream };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@ai-gui/openai",
3
+ "version": "0.3.0",
4
+ "description": "OpenAI model stream adapter for AIGUI.",
5
+ "keywords": [
6
+ "openai",
7
+ "llm",
8
+ "streaming",
9
+ "sse",
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/openai"
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 openai",
55
+ "typecheck": "tsc --noEmit"
56
+ }
57
+ }