@molecule/api-ai-openai 1.0.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,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai-openai` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai-openai is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * OpenAI (GPT) AI provider for molecule.dev.
3
+ *
4
+ * @remarks
5
+ * Config: `OPENAI_API_KEY` (SERVER-side only) plus an optional default model id/base URL.
6
+ *
7
+ * **Missing `OPENAI_API_KEY` fails fast**: the provider throws naming the exact env var on
8
+ * first use (the exported `provider` is a lazy proxy, so this fires on the first `chat()` call,
9
+ * not at bond/module-load time) — it never silently sends an empty key.
10
+ *
11
+ * **Error message disambiguation**: a plain 400 that ISN'T a context-length error (bad param,
12
+ * malformed tool schema) gets its own non-retryable message distinct from the generic
13
+ * "AI service error. Please try again." used for retryable failures.
14
+ *
15
+ * @module
16
+ */
17
+ export * from './browser-guard.js';
18
+ export { createProvider, OpenaiAIProvider } from './provider.js';
19
+ export * from './secrets.js';
20
+ export * from './types.js';
21
+ import type { AIProvider } from '@molecule/api-ai';
22
+ /** The provider implementation. */
23
+ export declare const provider: AIProvider;
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChE,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAE1B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAMlD,mCAAmC;AACnC,eAAO,MAAM,QAAQ,EAAE,UAUrB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * OpenAI (GPT) AI provider for molecule.dev.
3
+ *
4
+ * @remarks
5
+ * Config: `OPENAI_API_KEY` (SERVER-side only) plus an optional default model id/base URL.
6
+ *
7
+ * **Missing `OPENAI_API_KEY` fails fast**: the provider throws naming the exact env var on
8
+ * first use (the exported `provider` is a lazy proxy, so this fires on the first `chat()` call,
9
+ * not at bond/module-load time) — it never silently sends an empty key.
10
+ *
11
+ * **Error message disambiguation**: a plain 400 that ISN'T a context-length error (bad param,
12
+ * malformed tool schema) gets its own non-retryable message distinct from the generic
13
+ * "AI service error. Please try again." used for retryable failures.
14
+ *
15
+ * @module
16
+ */
17
+ export * from './browser-guard.js';
18
+ export { createProvider, OpenaiAIProvider } from './provider.js';
19
+ export * from './secrets.js';
20
+ export * from './types.js';
21
+ import { createProvider } from './provider.js';
22
+ /** Lazily-initialized provider singleton. Defers creation until first use so env vars / secrets are resolved. */
23
+ let _provider = null;
24
+ /** The provider implementation. */
25
+ export const provider = new Proxy({}, {
26
+ get(_, prop, receiver) {
27
+ if (!_provider)
28
+ _provider = createProvider();
29
+ return Reflect.get(_provider, prop, receiver);
30
+ },
31
+ // set trap: methods run with `this` bound to the proxy — without it, instance-state writes land on the dummy target and are lost (see api-push-notifications-web-push)
32
+ set(_, prop, value) {
33
+ if (!_provider)
34
+ _provider = createProvider();
35
+ return Reflect.set(_provider, prop, value);
36
+ },
37
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * OpenAI implementation of AIProvider.
3
+ *
4
+ * Uses the OpenAI HTTP API (`/v1/chat/completions`) for streaming chat
5
+ * completions. Mirrors the shape of `@molecule/api-ai-anthropic` so the
6
+ * same handler code can dispatch to either provider.
7
+ *
8
+ * @module
9
+ */
10
+ import './secrets.js';
11
+ import type { AIProvider, ChatEvent, ChatParams } from '@molecule/api-ai';
12
+ import type { OpenaiConfig } from './types.js';
13
+ /**
14
+ * OpenAI Chat Completions provider implementing the `AIProvider` interface.
15
+ */
16
+ export declare class OpenaiAIProvider implements AIProvider {
17
+ readonly name = "openai";
18
+ private apiKey;
19
+ private defaultModel;
20
+ private maxTokens;
21
+ private baseUrl;
22
+ private onRateLimit?;
23
+ constructor(config?: OpenaiConfig);
24
+ /**
25
+ * Send a chat request and yield streamed `ChatEvent`s.
26
+ *
27
+ * @param params - Chat parameters.
28
+ * @yields {ChatEvent}
29
+ */
30
+ chat(params: ChatParams): AsyncIterable<ChatEvent>;
31
+ /**
32
+ * Convert internal `ChatMessage` objects to the OpenAI message format.
33
+ * The system prompt becomes a leading `{role:'system'}` message.
34
+ */
35
+ private formatMessages;
36
+ /** Map a generic `ContentBlock` to OpenAI's content-part shape. */
37
+ private formatBlock;
38
+ /** Convert internal `AITool` definitions to OpenAI's `tools` array. */
39
+ private formatTools;
40
+ /**
41
+ * Parse a non-streaming `/v1/chat/completions` response.
42
+ *
43
+ * @param data - The parsed JSON response body.
44
+ * @yields {ChatEvent} Text, tool-use, and done events extracted from the response.
45
+ */
46
+ private parseNonStreamingResponse;
47
+ /**
48
+ * Parse a streaming SSE response from `/v1/chat/completions`.
49
+ *
50
+ * @param response - The fetch Response whose body is an SSE stream.
51
+ * @yields {ChatEvent} Incremental text, keep-alive, tool-use, and done events.
52
+ */
53
+ private parseStreamingResponse;
54
+ /**
55
+ * Process SSE lines from OpenAI's `chat/completions` stream.
56
+ *
57
+ * @param lines - Individual SSE lines to parse.
58
+ * @param state - Mutable stream state tracking tokens and pending tool calls.
59
+ * @yields {ChatEvent} Text and no-op events parsed from the SSE data lines.
60
+ */
61
+ private processSSELines;
62
+ }
63
+ /**
64
+ * Create an OpenAI AI provider instance.
65
+ *
66
+ * @param config - OpenAI-specific configuration.
67
+ * @returns An `AIProvider` backed by OpenAI's Chat Completions API.
68
+ */
69
+ export declare function createProvider(config?: OpenaiConfig): AIProvider;
70
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EACV,UAAU,EAGV,SAAS,EAET,UAAU,EAEX,MAAM,kBAAkB,CAAA;AAGzB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAc9C;;GAEG;AACH,qBAAa,gBAAiB,YAAW,UAAU;IACjD,QAAQ,CAAC,IAAI,YAAW;IACxB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAQ;IAC5B,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,WAAW,CAAC,CAAqB;gBAE7B,MAAM,GAAE,YAAiB;IAkBrC;;;;;OAKG;IACI,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,aAAa,CAAC,SAAS,CAAC;IAsKzD;;;OAGG;IACH,OAAO,CAAC,cAAc;IAoBtB,mEAAmE;IACnE,OAAO,CAAC,WAAW;IAiCnB,uEAAuE;IACvE,OAAO,CAAC,WAAW;IAWnB;;;;;OAKG;IACH,OAAO,CAAE,yBAAyB;IA8ClC;;;;;OAKG;YACY,sBAAsB;IA4ErC;;;;;;OAMG;IACH,OAAO,CAAE,eAAe;CA0EzB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,YAAY,GAAG,UAAU,CAEhE"}
@@ -0,0 +1,482 @@
1
+ /**
2
+ * OpenAI implementation of AIProvider.
3
+ *
4
+ * Uses the OpenAI HTTP API (`/v1/chat/completions`) for streaming chat
5
+ * completions. Mirrors the shape of `@molecule/api-ai-anthropic` so the
6
+ * same handler code can dispatch to either provider.
7
+ *
8
+ * @module
9
+ */
10
+ // Side-effect import: registers this bond's secret definitions so the
11
+ // runtime registry is populated even when provider.js is imported directly
12
+ // (not through the package barrel).
13
+ import './secrets.js';
14
+ import { getLogger } from '@molecule/api-bond';
15
+ const logger = getLogger();
16
+ /**
17
+ * OpenAI Chat Completions provider implementing the `AIProvider` interface.
18
+ */
19
+ export class OpenaiAIProvider {
20
+ name = 'openai';
21
+ apiKey;
22
+ defaultModel;
23
+ maxTokens;
24
+ baseUrl;
25
+ onRateLimit;
26
+ constructor(config = {}) {
27
+ this.apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? '';
28
+ this.defaultModel = config.defaultModel ?? 'gpt-5.6-luna';
29
+ this.maxTokens = config.maxTokens ?? 4096;
30
+ this.baseUrl = config.baseUrl ?? process.env.OPENAI_BASE_URL ?? 'https://api.openai.com';
31
+ this.onRateLimit = config.onRateLimit;
32
+ // Fail fast with an actionable local error rather than a cryptic 401 on the
33
+ // first request. The default `provider` export constructs lazily on first
34
+ // use (see index.ts), so this surfaces the moment the provider is actually
35
+ // used, not at bond/module-load time.
36
+ if (!this.apiKey) {
37
+ throw new Error('OPENAI_API_KEY is not set. Add it to your environment to use the OpenAI AI provider.');
38
+ }
39
+ }
40
+ /**
41
+ * Send a chat request and yield streamed `ChatEvent`s.
42
+ *
43
+ * @param params - Chat parameters.
44
+ * @yields {ChatEvent}
45
+ */
46
+ async *chat(params) {
47
+ const model = params.model ?? this.defaultModel;
48
+ const maxTokens = params.maxTokens ?? this.maxTokens;
49
+ const messages = this.formatMessages(params.messages, params.system);
50
+ const body = {
51
+ // Abuse attribution (see ChatParams.endUserId). OpenAI DEPRECATED `user`
52
+ // and replaced it with `safety_identifier` for exactly this purpose —
53
+ // their guidance is a hashed, stable per-user string, which is what
54
+ // endUserId already is. Sibling OpenAI-compatible bonds keep `user`: it is
55
+ // the field they actually implement, verified accepted by deepseek, xai,
56
+ // moonshot, alibaba and zhipu against their live APIs.
57
+ //
58
+ // This bond is also pointed at arbitrary BYO OpenAI-compatible endpoints
59
+ // (molecule-dev's custom providers), so the unknown-field question matters
60
+ // here: those same five providers all returned 200 when sent an unknown
61
+ // `safety_identifier`, i.e. tolerating unknown body params is the norm.
62
+ // A BYO endpoint therefore ignores this rather than rejecting it — and BYO
63
+ // runs on the user's OWN key, where attribution protects nothing of ours.
64
+ ...(params.endUserId ? { safety_identifier: params.endUserId } : {}),
65
+ model,
66
+ messages,
67
+ // `max_completion_tokens`, NOT `max_tokens`. Every GPT-5-family model
68
+ // hard-rejects the latter — "Unsupported parameter: 'max_tokens' is not
69
+ // supported with this model" (400) — and the catalog's OpenAI entries are
70
+ // all gpt-5.6-*, so this bond could not call any of its own models. The
71
+ // newer name is accepted by the older generations too (verified 200 on
72
+ // gpt-4o-mini and gpt-3.5-turbo), so there is no need to branch per model.
73
+ max_completion_tokens: maxTokens,
74
+ };
75
+ if (params.temperature !== undefined)
76
+ body.temperature = params.temperature;
77
+ // Reasoning depth: the caller resolves the model's native reasoning_effort
78
+ // value (none | low | medium | high | xhigh on GPT-5.4/5.5-family) from the
79
+ // model catalog and passes it as `thinking.effort`. Without it, omit the
80
+ // param entirely (the model's own default applies — medium on gpt-5.5).
81
+ if (params.thinking?.effort) {
82
+ body.reasoning_effort = params.thinking.effort;
83
+ }
84
+ const tools = params.tools?.length ? this.formatTools(params.tools) : null;
85
+ if (tools) {
86
+ body.tools = tools;
87
+ if (params.toolChoice === 'required') {
88
+ body.tool_choice = 'required';
89
+ }
90
+ else if (typeof params.toolChoice === 'object' && params.toolChoice?.type === 'tool') {
91
+ body.tool_choice = { type: 'function', function: { name: params.toolChoice.name } };
92
+ }
93
+ }
94
+ const useStream = params.stream !== false;
95
+ if (useStream) {
96
+ body.stream = true;
97
+ body.stream_options = { include_usage: true };
98
+ }
99
+ const headers = {
100
+ 'Content-Type': 'application/json',
101
+ Authorization: `Bearer ${this.apiKey}`,
102
+ };
103
+ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
104
+ const signal = params.signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS);
105
+ const MAX_RETRIES = 3;
106
+ let response = null;
107
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
108
+ response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
109
+ method: 'POST',
110
+ headers,
111
+ body: JSON.stringify(body),
112
+ signal,
113
+ });
114
+ if (response.status === 429 || response.status === 503) {
115
+ const willRetry = attempt < MAX_RETRIES;
116
+ // Retry-After is equally-valid as delta-seconds or an HTTP-date;
117
+ // parseInt on the date form yields NaN, degrading the backoff to a
118
+ // ~0ms retry against an already rate-limiting API. Guard it.
119
+ const retryAfter = response.headers.get('retry-after');
120
+ const parsedRetryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : NaN;
121
+ const hasRetryAfter = Number.isFinite(parsedRetryAfterSeconds) && parsedRetryAfterSeconds >= 0;
122
+ // Additive jitter (<500ms): concurrent callers rejected together must
123
+ // not sleep identical delays and re-arrive as the same burst.
124
+ const delayMs = willRetry
125
+ ? (hasRetryAfter
126
+ ? Math.min(parsedRetryAfterSeconds * 1000, 60_000)
127
+ : Math.min(1000 * 2 ** attempt, 30_000)) + Math.floor(Math.random() * 500)
128
+ : 0;
129
+ try {
130
+ this.onRateLimit?.({
131
+ provider: this.name,
132
+ model,
133
+ status: response.status,
134
+ attempt: attempt + 1,
135
+ willRetry,
136
+ retryInMs: delayMs,
137
+ ...(hasRetryAfter ? { retryAfterSeconds: parsedRetryAfterSeconds } : {}),
138
+ });
139
+ }
140
+ catch (error) {
141
+ // Host-app telemetry; its failure must never break the request.
142
+ logger.warn('onRateLimit callback threw', { error });
143
+ }
144
+ if (willRetry) {
145
+ logger.warn('OpenAI API rate limited, retrying', {
146
+ status: response.status,
147
+ attempt: attempt + 1,
148
+ delayMs,
149
+ });
150
+ await new Promise((resolve) => {
151
+ const timer = setTimeout(resolve, delayMs);
152
+ signal.addEventListener('abort', () => {
153
+ clearTimeout(timer);
154
+ resolve();
155
+ }, { once: true });
156
+ });
157
+ if (signal.aborted)
158
+ break;
159
+ continue;
160
+ }
161
+ }
162
+ break;
163
+ }
164
+ if (!response.ok) {
165
+ const errorBody = await response.text();
166
+ let detail = `HTTP ${response.status}`;
167
+ try {
168
+ const parsed = JSON.parse(errorBody);
169
+ if (parsed.error?.message)
170
+ detail = parsed.error.message;
171
+ }
172
+ catch (_error) {
173
+ // Best-effort: detail already has an HTTP-status fallback; malformed body just stays as-is.
174
+ if (errorBody.length > 0 && errorBody.length < 200)
175
+ detail = errorBody;
176
+ }
177
+ logger.error('OpenAI API error', { status: response.status, detail });
178
+ const clientMessage = response.status === 429
179
+ ? 'AI rate limit exceeded. Please try again shortly.'
180
+ : response.status === 401
181
+ ? 'AI service configuration error.'
182
+ : response.status === 400 &&
183
+ /context.*length|maximum context|too many tokens|prompt is too long/i.test(detail)
184
+ ? "Conversation too long for the model's context window."
185
+ : response.status === 400
186
+ ? 'AI request was invalid — check the model and request parameters.'
187
+ : response.status === 503 || response.status === 502
188
+ ? 'AI service is temporarily overloaded. Please try again in a moment.'
189
+ : 'AI service error. Please try again.';
190
+ yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' };
191
+ return;
192
+ }
193
+ if (!useStream) {
194
+ const data = (await response.json());
195
+ yield* this.parseNonStreamingResponse(data);
196
+ return;
197
+ }
198
+ yield* this.parseStreamingResponse(response);
199
+ }
200
+ /**
201
+ * Convert internal `ChatMessage` objects to the OpenAI message format.
202
+ * The system prompt becomes a leading `{role:'system'}` message.
203
+ */
204
+ formatMessages(messages, systemPrompt) {
205
+ const out = [];
206
+ if (systemPrompt)
207
+ out.push({ role: 'system', content: systemPrompt });
208
+ for (const m of messages) {
209
+ if (m.role === 'system') {
210
+ out.push({ role: 'system', content: typeof m.content === 'string' ? m.content : '' });
211
+ continue;
212
+ }
213
+ const content = typeof m.content === 'string'
214
+ ? m.content
215
+ : m.content.map((b) => this.formatBlock(b));
216
+ out.push({ role: m.role, content });
217
+ }
218
+ return out;
219
+ }
220
+ /** Map a generic `ContentBlock` to OpenAI's content-part shape. */
221
+ formatBlock(block) {
222
+ switch (block.type) {
223
+ case 'text':
224
+ return { type: 'text', text: block.text };
225
+ case 'image':
226
+ return {
227
+ type: 'image_url',
228
+ image_url: { url: `data:${block.mediaType};base64,${block.data}` },
229
+ };
230
+ case 'document':
231
+ return {
232
+ type: 'text',
233
+ text: `[Document attachment (${block.mediaType}) — not supported by this provider]`,
234
+ };
235
+ case 'audio':
236
+ return {
237
+ type: 'text',
238
+ text: `[Audio attachment (${block.mediaType}) — not supported by this provider]`,
239
+ };
240
+ case 'video':
241
+ return {
242
+ type: 'text',
243
+ text: `[Video attachment (${block.mediaType}) — not supported by this provider]`,
244
+ };
245
+ case 'tool_use':
246
+ return { type: 'text', text: `[tool_use ${block.name}]` };
247
+ case 'tool_result':
248
+ return { type: 'text', text: `[tool_result for ${block.tool_use_id}]` };
249
+ default:
250
+ return block;
251
+ }
252
+ }
253
+ /** Convert internal `AITool` definitions to OpenAI's `tools` array. */
254
+ formatTools(tools) {
255
+ return tools.map((tool) => ({
256
+ type: 'function',
257
+ function: {
258
+ name: tool.name,
259
+ description: tool.description,
260
+ parameters: tool.parameters,
261
+ },
262
+ }));
263
+ }
264
+ /**
265
+ * Parse a non-streaming `/v1/chat/completions` response.
266
+ *
267
+ * @param data - The parsed JSON response body.
268
+ * @yields {ChatEvent} Text, tool-use, and done events extracted from the response.
269
+ */
270
+ *parseNonStreamingResponse(data) {
271
+ const choices = data.choices;
272
+ const message = choices?.[0]?.message;
273
+ const content = message?.content;
274
+ if (typeof content === 'string' && content.length > 0) {
275
+ yield { type: 'text', content };
276
+ }
277
+ const toolCalls = message?.tool_calls;
278
+ if (toolCalls) {
279
+ for (const call of toolCalls) {
280
+ const fn = call.function;
281
+ let input = {};
282
+ try {
283
+ input = fn?.arguments ? JSON.parse(fn.arguments) : {};
284
+ }
285
+ catch (_error) {
286
+ // Best-effort: malformed tool-call arguments are unusable; fall back to empty object.
287
+ }
288
+ yield {
289
+ type: 'tool_use',
290
+ id: String(call.id ?? ''),
291
+ name: String(fn?.name ?? ''),
292
+ input,
293
+ };
294
+ }
295
+ }
296
+ const usage = data.usage;
297
+ const cached = usage?.prompt_tokens_details?.cached_tokens ?? 0;
298
+ yield {
299
+ type: 'done',
300
+ usage: {
301
+ // Report uncached input + cached separately (Anthropic semantics) so the
302
+ // consumer's context/cost math doesn't double-count the cached subset.
303
+ inputTokens: Math.max(0, (usage?.prompt_tokens ?? 0) - cached),
304
+ outputTokens: usage?.completion_tokens ?? 0,
305
+ cacheReadInputTokens: cached,
306
+ },
307
+ };
308
+ }
309
+ /**
310
+ * Parse a streaming SSE response from `/v1/chat/completions`.
311
+ *
312
+ * @param response - The fetch Response whose body is an SSE stream.
313
+ * @yields {ChatEvent} Incremental text, keep-alive, tool-use, and done events.
314
+ */
315
+ async *parseStreamingResponse(response) {
316
+ const reader = response.body?.getReader();
317
+ if (!reader) {
318
+ yield {
319
+ type: 'error',
320
+ message: 'No response body from OpenAI.',
321
+ errorKey: 'ai.error.noResponseBody',
322
+ };
323
+ return;
324
+ }
325
+ const decoder = new TextDecoder();
326
+ let buffer = '';
327
+ const state = {
328
+ inputTokens: 0,
329
+ outputTokens: 0,
330
+ cachedTokens: 0,
331
+ pendingTools: new Map(),
332
+ };
333
+ try {
334
+ while (true) {
335
+ const { done, value } = await reader.read();
336
+ if (done)
337
+ break;
338
+ buffer += decoder.decode(value, { stream: true });
339
+ const lines = buffer.split('\n');
340
+ buffer = lines.pop() ?? '';
341
+ let yielded = false;
342
+ for (const event of this.processSSELines(lines, state)) {
343
+ yielded = true;
344
+ yield event;
345
+ // A mid-stream error (rate-limit/overload during high load, sent as a
346
+ // `data: {"error": {...}}` chunk) means the turn was truncated. Stop
347
+ // here and do NOT fall through to the trailing `done`, which would
348
+ // report the truncated turn as a successful completion and skip the
349
+ // consumer's overload/retry recovery.
350
+ if (event.type === 'error')
351
+ return;
352
+ }
353
+ // Received data but produced no ChatEvent (a keepalive comment, an empty
354
+ // delta, or buffered tool-call arguments streaming in). The model is
355
+ // still alive — signal liveness so the consumer's inter-event stream
356
+ // timeout doesn't false-fire mid-generation.
357
+ if (!yielded)
358
+ yield { type: 'keep_alive' };
359
+ }
360
+ if (buffer.trim()) {
361
+ for (const event of this.processSSELines(buffer.split('\n'), state)) {
362
+ yield event;
363
+ if (event.type === 'error')
364
+ return;
365
+ }
366
+ }
367
+ // Flush any pending tool calls
368
+ for (const tool of state.pendingTools.values()) {
369
+ let input = {};
370
+ try {
371
+ input = tool.argsJson ? JSON.parse(tool.argsJson) : {};
372
+ }
373
+ catch (_error) {
374
+ // Best-effort: streaming tool arguments arrived malformed; fall back to empty object.
375
+ }
376
+ yield { type: 'tool_use', id: tool.id, name: tool.name, input };
377
+ }
378
+ state.pendingTools.clear();
379
+ }
380
+ finally {
381
+ reader.releaseLock();
382
+ }
383
+ yield {
384
+ type: 'done',
385
+ usage: {
386
+ inputTokens: Math.max(0, state.inputTokens - state.cachedTokens),
387
+ outputTokens: state.outputTokens,
388
+ cacheReadInputTokens: state.cachedTokens,
389
+ },
390
+ };
391
+ }
392
+ /**
393
+ * Process SSE lines from OpenAI's `chat/completions` stream.
394
+ *
395
+ * @param lines - Individual SSE lines to parse.
396
+ * @param state - Mutable stream state tracking tokens and pending tool calls.
397
+ * @yields {ChatEvent} Text and no-op events parsed from the SSE data lines.
398
+ */
399
+ *processSSELines(lines, state) {
400
+ for (const line of lines) {
401
+ if (!line.startsWith('data: '))
402
+ continue;
403
+ const json = line.slice(6).trim();
404
+ if (json === '[DONE]')
405
+ continue;
406
+ try {
407
+ const event = JSON.parse(json);
408
+ // A mid-stream error arrives as a `data: {"error": {...}}` chunk (no
409
+ // `choices`) — most importantly rate-limit/overload during high load.
410
+ // Without this it matches no branch below and is silently dropped, so the
411
+ // stream falls through to a misleading `done` and the truncated turn reads
412
+ // as a successful completion. Surface it as a real error event (also
413
+ // satisfies the no-silent-swallow rule).
414
+ const streamError = event.error;
415
+ if (streamError) {
416
+ const detail = `${streamError.code ?? streamError.type ?? ''} ${streamError.message ?? ''}`;
417
+ logger.error('OpenAI streaming error event', {
418
+ type: streamError.type,
419
+ code: streamError.code,
420
+ message: streamError.message,
421
+ });
422
+ const clientMessage = /overload|capacity|503|529/i.test(detail)
423
+ ? 'AI service is temporarily overloaded. Please try again in a moment.'
424
+ : /rate.?limit|429|quota/i.test(detail)
425
+ ? 'AI rate limit exceeded. Please try again shortly.'
426
+ : 'AI service error. Please try again.';
427
+ yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' };
428
+ continue;
429
+ }
430
+ const choices = event.choices;
431
+ if (choices) {
432
+ for (const choice of choices) {
433
+ const delta = choice.delta;
434
+ if (typeof delta?.content === 'string' && delta.content.length > 0) {
435
+ yield { type: 'text', content: delta.content };
436
+ }
437
+ const toolCalls = delta?.tool_calls;
438
+ if (toolCalls) {
439
+ for (const call of toolCalls) {
440
+ const idx = Number(call.index ?? 0);
441
+ const fn = call.function;
442
+ const existing = state.pendingTools.get(idx) ?? {
443
+ id: String(call.id ?? ''),
444
+ name: '',
445
+ argsJson: '',
446
+ };
447
+ if (call.id)
448
+ existing.id = String(call.id);
449
+ if (fn?.name)
450
+ existing.name = String(fn.name);
451
+ if (typeof fn?.arguments === 'string')
452
+ existing.argsJson += fn.arguments;
453
+ state.pendingTools.set(idx, existing);
454
+ }
455
+ }
456
+ }
457
+ }
458
+ const usage = event.usage;
459
+ if (usage) {
460
+ if (typeof usage.prompt_tokens === 'number')
461
+ state.inputTokens = usage.prompt_tokens;
462
+ if (typeof usage.completion_tokens === 'number')
463
+ state.outputTokens = usage.completion_tokens;
464
+ if (typeof usage.prompt_tokens_details?.cached_tokens === 'number')
465
+ state.cachedTokens = usage.prompt_tokens_details.cached_tokens;
466
+ }
467
+ }
468
+ catch (error) {
469
+ logger.debug('Skipping malformed OpenAI SSE JSON line', { json, error });
470
+ }
471
+ }
472
+ }
473
+ }
474
+ /**
475
+ * Create an OpenAI AI provider instance.
476
+ *
477
+ * @param config - OpenAI-specific configuration.
478
+ * @returns An `AIProvider` backed by OpenAI's Chat Completions API.
479
+ */
480
+ export function createProvider(config) {
481
+ return new OpenaiAIProvider(config);
482
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * OpenAI secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import type { SecretDefinition } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the OpenAI AI bond. */
15
+ export declare const aiOpenaiSecretDefinitions: SecretDefinition[];
16
+ //# sourceMappingURL=secrets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,yDAAyD;AACzD,eAAO,MAAM,yBAAyB,EAAE,gBAAgB,EAQvD,CAAA"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * OpenAI secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import { registerSecrets } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the OpenAI AI bond. */
15
+ export const aiOpenaiSecretDefinitions = [
16
+ {
17
+ key: 'OPENAI_API_KEY',
18
+ description: 'OpenAI API key — Create a secret key on the OpenAI platform (API keys page).',
19
+ helpUrl: 'https://platform.openai.com/api-keys',
20
+ required: true,
21
+ example: 'sk-proj-...',
22
+ },
23
+ ];
24
+ registerSecrets(aiOpenaiSecretDefinitions);
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Openai AI provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ import type { AiRateLimitCallback } from '@molecule/api-ai';
7
+ /** OpenAI provider configuration. */
8
+ export interface OpenaiConfig {
9
+ /** Override the API key (defaults to `process.env.OPENAI_API_KEY`). */
10
+ apiKey?: string;
11
+ /** Default model when callers don't specify one. */
12
+ defaultModel?: string;
13
+ /** Default max output tokens. */
14
+ maxTokens?: number;
15
+ /** Override the API base URL (for proxies / Azure). */
16
+ baseUrl?: string;
17
+ /** Called on each rate-limited/overloaded upstream response, before any retry sleep. */
18
+ onRateLimit?: AiRateLimitCallback;
19
+ }
20
+ /** Environment variables read by this provider. */
21
+ export interface ProcessEnv {
22
+ /** OpenAI API key (required unless `config.apiKey` is passed). */
23
+ OPENAI_API_KEY: string;
24
+ /** Base URL override (for proxies / Azure-compatible gateways). Defaults to `https://api.openai.com`. */
25
+ OPENAI_BASE_URL?: string;
26
+ }
27
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAA;AAE3D,qCAAqC;AACrC,MAAM,WAAW,YAAY;IAC3B,uEAAuE;IACvE,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oDAAoD;IACpD,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,iCAAiC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,wFAAwF;IACxF,WAAW,CAAC,EAAE,mBAAmB,CAAA;CAClC;AAED,mDAAmD;AACnD,MAAM,WAAW,UAAU;IACzB,kEAAkE;IAClE,cAAc,EAAE,MAAM,CAAA;IACtB,yGAAyG;IACzG,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Openai AI provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@molecule/api-ai-openai",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "ai",
25
+ "openai"
26
+ ],
27
+ "license": "Apache-2.0",
28
+ "devDependencies": {
29
+ "@molecule/api-ai": "1.0.0",
30
+ "@molecule/api-bond": "1.0.0",
31
+ "@types/node": "26.1.2",
32
+ "typescript": "6.0.3",
33
+ "vitest": "4.1.10"
34
+ },
35
+ "peerDependencies": {
36
+ "@molecule/api-ai": "^1.0.0",
37
+ "@molecule/api-bond": "^1.0.0",
38
+ "@molecule/api-secrets": "^1.0.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "@molecule/api-ai": {
42
+ "optional": true
43
+ }
44
+ }
45
+ }