@mast-ai/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,193 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
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. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claim embodied in the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Contribution, and to permit persons to whom the Contribution is
122
+ furnished to do so.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any conditions of
142
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ workstop, computer failure or malfunction, or all other commercial
156
+ damages or losses), even if such Contributor has been advised of the
157
+ possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may act only
164
+ on Your own behalf and on Your sole responsibility, not on behalf
165
+ of any other Contributor, and only if You agree to indemnify,
166
+ defend, and hold each Contributor harmless for any liability
167
+ incurred by, or claims asserted against, such Contributor by reason
168
+ of your accepting any such warranty or additional liability.
169
+
170
+ END OF TERMS AND CONDITIONS
171
+
172
+ APPENDIX: How to apply the Apache License to your work.
173
+
174
+ To apply the Apache License to your work, attach the following
175
+ boilerplate notice, with the fields enclosed by brackets "[]"
176
+ replaced with your own identifying information. (Don't include
177
+ the brackets!) The text should be enclosed in the appropriate
178
+ comment syntax for the programming language used. Source files
179
+ may also indicate a copyright notice separately from the text below.
180
+
181
+ Copyright 2026 Andre Cipriani Bandarra
182
+
183
+ Licensed under the Apache License, Version 2.0 (the "License");
184
+ you may not use this file except in compliance with the License.
185
+ You may obtain a copy of the License at
186
+
187
+ http://www.apache.org/licenses/LICENSE-2.0
188
+
189
+ Unless required by applicable law or agreed to in writing, software
190
+ distributed under the License is distributed on an "AS IS" BASIS,
191
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
192
+ See the License for the specific language governing permissions and
193
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @mast-ai/openai
2
+
3
+ OpenAI `LlmAdapter`s for [MAST](https://github.com/andreban/mast-ai). Calls OpenAI directly from the browser, bypassing the URP backend entirely.
4
+
5
+ Two adapters ship side by side:
6
+
7
+ - **`OpenAIChatCompletionsAdapter`** wraps the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). Broad model coverage, works against OpenAI-compatible providers (OpenRouter, DeepSeek). Reasoning content from compatible providers is forwarded as `thinking` events; OpenAI itself does not expose reasoning content via this endpoint.
8
+ - **`OpenAIResponsesAdapter`** wraps the [Responses API](https://platform.openai.com/docs/api-reference/responses). Required to surface reasoning summaries from `gpt-5` and `o-series` models as `thinking` events.
9
+
10
+ Both support tool calling, streaming, and structured output.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @mast-ai/core @mast-ai/openai
16
+ ```
17
+
18
+ ## Chat Completions usage
19
+
20
+ ```typescript
21
+ import { AgentRunner, ToolRegistry, createAgent } from '@mast-ai/core';
22
+ import { OpenAIChatCompletionsAdapter } from '@mast-ai/openai';
23
+
24
+ const adapter = new OpenAIChatCompletionsAdapter(
25
+ import.meta.env.VITE_OPENAI_API_KEY,
26
+ 'gpt-4o-mini',
27
+ );
28
+
29
+ const registry = new ToolRegistry();
30
+ // ...register tools...
31
+
32
+ const agent = createAgent({ name: 'Assistant', instructions: '...', tools: [] });
33
+ const runner = new AgentRunner(adapter, registry);
34
+
35
+ const result = await runner.run(agent, 'Hello!');
36
+ ```
37
+
38
+ ## Responses API usage (with reasoning)
39
+
40
+ ```typescript
41
+ import { OpenAIResponsesAdapter } from '@mast-ai/openai';
42
+
43
+ const adapter = new OpenAIResponsesAdapter(apiKey, 'gpt-5', undefined, {
44
+ reasoningEffort: 'medium',
45
+ // reasoningSummary defaults to "auto"; set to false to disable thinking events.
46
+ });
47
+ ```
48
+
49
+ `OpenAIResponsesAdapter` runs statelessly (`store: false`) — the runner's `Conversation` history is replayed on every request. With `reasoningSummary` set, every reasoning model call emits `thinking` events alongside the final text.
50
+
51
+ > **Note:** Calling OpenAI directly from the browser exposes your API key. Use this in trusted contexts (extensions, internal tools, demos) or front it with a proxy that injects the key server-side. Both adapters set `dangerouslyAllowBrowser: true` to permit browser usage of the official OpenAI SDK.
52
+
53
+ ## License
54
+
55
+ Apache-2.0. Copyright 2026 Andre Cipriani Bandarra.
@@ -0,0 +1,54 @@
1
+ import type { LlmAdapter, AdapterRequest, AdapterResponse, AdapterStreamChunk } from '@mast-ai/core';
2
+ /** Token-usage statistics reported by the OpenAI Chat Completions API. */
3
+ export interface UsageMetadata {
4
+ promptTokens?: number;
5
+ completionTokens?: number;
6
+ totalTokens?: number;
7
+ }
8
+ /** Reasoning-effort level for o-series and gpt-5 models. */
9
+ export type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high';
10
+ /** Per-request defaults applied to every call made by an {@link OpenAIChatCompletionsAdapter}. */
11
+ export interface OpenAIChatCompletionsAdapterDefaults {
12
+ /**
13
+ * Forwarded as `reasoning_effort` on every request. Reasoning models honour
14
+ * this; non-reasoning models reject the field, so set it only when the
15
+ * configured `modelName` is a reasoning model.
16
+ */
17
+ reasoningEffort?: ReasoningEffort;
18
+ }
19
+ /**
20
+ * {@link LlmAdapter} implementation backed by the OpenAI Chat Completions API.
21
+ *
22
+ * Supports tool calling, structured output via JSON Schema, and streaming.
23
+ * Reasoning models (o-series, gpt-5, ...) work out of the box: pass
24
+ * `reasoning_effort` through `ModelConfig` and any reasoning content the model
25
+ * exposes via `delta.reasoning_content` (used by OpenAI-compatible providers
26
+ * such as OpenRouter and DeepSeek) is forwarded as `thinking` events.
27
+ *
28
+ * To surface reasoning content from native OpenAI reasoning models, use
29
+ * {@link OpenAIResponsesAdapter} instead — Chat Completions does not return
30
+ * reasoning tokens for OpenAI's own models.
31
+ */
32
+ export declare class OpenAIChatCompletionsAdapter implements LlmAdapter {
33
+ private client;
34
+ private modelName;
35
+ private onUsageUpdate?;
36
+ private defaults;
37
+ /**
38
+ * @param apiKey - OpenAI API key.
39
+ * @param modelName - Model identifier (defaults to `"gpt-4o-mini"`). Any
40
+ * chat-completion-compatible model works, including reasoning models.
41
+ * @param onUsageUpdate - Optional callback invoked with token-usage data after each response.
42
+ * @param defaults - Provider-specific defaults applied to every request
43
+ * (e.g. `reasoningEffort` for o-series / gpt-5).
44
+ */
45
+ constructor(apiKey: string, modelName?: string, onUsageUpdate?: (usage: UsageMetadata) => void, defaults?: OpenAIChatCompletionsAdapterDefaults);
46
+ private buildTools;
47
+ private buildBaseParams;
48
+ /** {@inheritDoc LlmAdapter.generate} */
49
+ generate(request: AdapterRequest): Promise<AdapterResponse>;
50
+ /** {@inheritDoc LlmAdapter.generateStream} */
51
+ generateStream(request: AdapterRequest): AsyncIterable<AdapterStreamChunk>;
52
+ private mapMessages;
53
+ private mapTool;
54
+ }
@@ -0,0 +1,234 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import OpenAI from 'openai';
4
+ /**
5
+ * {@link LlmAdapter} implementation backed by the OpenAI Chat Completions API.
6
+ *
7
+ * Supports tool calling, structured output via JSON Schema, and streaming.
8
+ * Reasoning models (o-series, gpt-5, ...) work out of the box: pass
9
+ * `reasoning_effort` through `ModelConfig` and any reasoning content the model
10
+ * exposes via `delta.reasoning_content` (used by OpenAI-compatible providers
11
+ * such as OpenRouter and DeepSeek) is forwarded as `thinking` events.
12
+ *
13
+ * To surface reasoning content from native OpenAI reasoning models, use
14
+ * {@link OpenAIResponsesAdapter} instead — Chat Completions does not return
15
+ * reasoning tokens for OpenAI's own models.
16
+ */
17
+ export class OpenAIChatCompletionsAdapter {
18
+ client;
19
+ modelName;
20
+ onUsageUpdate;
21
+ defaults;
22
+ /**
23
+ * @param apiKey - OpenAI API key.
24
+ * @param modelName - Model identifier (defaults to `"gpt-4o-mini"`). Any
25
+ * chat-completion-compatible model works, including reasoning models.
26
+ * @param onUsageUpdate - Optional callback invoked with token-usage data after each response.
27
+ * @param defaults - Provider-specific defaults applied to every request
28
+ * (e.g. `reasoningEffort` for o-series / gpt-5).
29
+ */
30
+ constructor(apiKey, modelName = 'gpt-4o-mini', onUsageUpdate, defaults) {
31
+ this.client = new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
32
+ this.modelName = modelName;
33
+ this.onUsageUpdate = onUsageUpdate;
34
+ this.defaults = defaults ?? {};
35
+ }
36
+ buildTools(request) {
37
+ if (request.tools.length === 0)
38
+ return undefined;
39
+ return request.tools.map((t) => this.mapTool(t));
40
+ }
41
+ buildBaseParams(request) {
42
+ const messages = this.mapMessages(request);
43
+ const tools = this.buildTools(request);
44
+ const config = (request.config ?? {});
45
+ const reasoningEffort = (typeof config.reasoning_effort === 'string'
46
+ ? config.reasoning_effort
47
+ : undefined) ?? this.defaults.reasoningEffort;
48
+ const params = {
49
+ model: this.modelName,
50
+ messages,
51
+ ...(tools ? { tools } : {}),
52
+ ...(typeof config.temperature === 'number' ? { temperature: config.temperature } : {}),
53
+ ...(typeof config.maxTokens === 'number' ? { max_completion_tokens: config.maxTokens } : {}),
54
+ ...(typeof config.topP === 'number' ? { top_p: config.topP } : {}),
55
+ ...(Array.isArray(config.stopSequences) ? { stop: config.stopSequences } : {}),
56
+ ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
57
+ ...(request.outputSchema
58
+ ? {
59
+ response_format: {
60
+ type: 'json_schema',
61
+ json_schema: {
62
+ name: 'output',
63
+ schema: request.outputSchema,
64
+ strict: true,
65
+ },
66
+ },
67
+ }
68
+ : {}),
69
+ };
70
+ return params;
71
+ }
72
+ /** {@inheritDoc LlmAdapter.generate} */
73
+ async generate(request) {
74
+ const params = {
75
+ ...this.buildBaseParams(request),
76
+ stream: false,
77
+ };
78
+ const response = await this.client.chat.completions.create(params, { signal: request.signal });
79
+ if (response.usage && this.onUsageUpdate) {
80
+ this.onUsageUpdate({
81
+ promptTokens: response.usage.prompt_tokens,
82
+ completionTokens: response.usage.completion_tokens,
83
+ totalTokens: response.usage.total_tokens,
84
+ });
85
+ }
86
+ const choice = response.choices?.[0];
87
+ if (!choice) {
88
+ throw new Error('No choice returned from OpenAI');
89
+ }
90
+ const message = choice.message;
91
+ return {
92
+ text: typeof message.content === 'string' && message.content.length > 0
93
+ ? message.content
94
+ : undefined,
95
+ toolCalls: (message.tool_calls ?? []).flatMap((tc) => tc.type === 'function'
96
+ ? [
97
+ {
98
+ id: tc.id,
99
+ name: tc.function.name,
100
+ args: parseArguments(tc.function.arguments),
101
+ },
102
+ ]
103
+ : []),
104
+ };
105
+ }
106
+ /** {@inheritDoc LlmAdapter.generateStream} */
107
+ async *generateStream(request) {
108
+ const params = {
109
+ ...this.buildBaseParams(request),
110
+ stream: true,
111
+ stream_options: { include_usage: true },
112
+ };
113
+ const stream = await this.client.chat.completions.create(params, { signal: request.signal });
114
+ const accumulators = new Map();
115
+ for await (const chunk of stream) {
116
+ if (chunk.usage && this.onUsageUpdate) {
117
+ this.onUsageUpdate({
118
+ promptTokens: chunk.usage.prompt_tokens,
119
+ completionTokens: chunk.usage.completion_tokens,
120
+ totalTokens: chunk.usage.total_tokens,
121
+ });
122
+ }
123
+ const choice = chunk.choices?.[0];
124
+ if (!choice)
125
+ continue;
126
+ const delta = choice.delta;
127
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
128
+ if (typeof reasoning === 'string' && reasoning.length > 0) {
129
+ yield { type: 'thinking', delta: reasoning };
130
+ }
131
+ if (typeof delta.content === 'string' && delta.content.length > 0) {
132
+ yield { type: 'text_delta', delta: delta.content };
133
+ }
134
+ if (delta.tool_calls) {
135
+ for (const tcDelta of delta.tool_calls) {
136
+ if (tcDelta.type !== undefined && tcDelta.type !== 'function')
137
+ continue;
138
+ const idx = tcDelta.index;
139
+ let acc = accumulators.get(idx);
140
+ if (!acc) {
141
+ acc = { args: '' };
142
+ accumulators.set(idx, acc);
143
+ }
144
+ if (tcDelta.id)
145
+ acc.id = tcDelta.id;
146
+ if (tcDelta.function?.name)
147
+ acc.name = tcDelta.function.name;
148
+ if (tcDelta.function?.arguments)
149
+ acc.args += tcDelta.function.arguments;
150
+ }
151
+ }
152
+ if (choice.finish_reason === 'tool_calls') {
153
+ const indices = [...accumulators.keys()].sort((a, b) => a - b);
154
+ for (const idx of indices) {
155
+ const acc = accumulators.get(idx);
156
+ if (!acc.name)
157
+ continue;
158
+ yield {
159
+ type: 'tool_call',
160
+ toolCall: {
161
+ id: acc.id ?? crypto.randomUUID(),
162
+ name: acc.name,
163
+ args: parseArguments(acc.args),
164
+ },
165
+ };
166
+ }
167
+ accumulators.clear();
168
+ }
169
+ }
170
+ }
171
+ mapMessages(request) {
172
+ const result = [];
173
+ if (request.system) {
174
+ result.push({ role: 'system', content: request.system });
175
+ }
176
+ for (const message of request.messages) {
177
+ const mapped = mapMessage(message);
178
+ if (mapped.length > 0)
179
+ result.push(...mapped);
180
+ }
181
+ return result;
182
+ }
183
+ mapTool(tool) {
184
+ return {
185
+ type: 'function',
186
+ function: {
187
+ name: tool.name,
188
+ description: tool.description,
189
+ parameters: tool.parameters,
190
+ },
191
+ };
192
+ }
193
+ }
194
+ function mapMessage(message) {
195
+ if (message.content.type === 'text') {
196
+ return [{ role: message.role, content: message.content.text }];
197
+ }
198
+ if (message.content.type === 'tool_calls') {
199
+ return [
200
+ {
201
+ role: 'assistant',
202
+ content: null,
203
+ tool_calls: message.content.calls.map((call) => ({
204
+ id: call.id,
205
+ type: 'function',
206
+ function: {
207
+ name: call.name,
208
+ arguments: typeof call.args === 'string' ? call.args : JSON.stringify(call.args ?? {}),
209
+ },
210
+ })),
211
+ },
212
+ ];
213
+ }
214
+ // tool_result -> { role: 'tool', tool_call_id, content }
215
+ return [
216
+ {
217
+ role: 'tool',
218
+ tool_call_id: message.content.id,
219
+ content: typeof message.content.result === 'string'
220
+ ? message.content.result
221
+ : JSON.stringify(message.content.result),
222
+ },
223
+ ];
224
+ }
225
+ function parseArguments(raw) {
226
+ if (!raw)
227
+ return {};
228
+ try {
229
+ return JSON.parse(raw);
230
+ }
231
+ catch {
232
+ return raw;
233
+ }
234
+ }
@@ -0,0 +1,44 @@
1
+ import type { LlmAdapter, AdapterRequest, AdapterResponse, AdapterStreamChunk } from '@mast-ai/core';
2
+ import type { ReasoningEffort, UsageMetadata } from './OpenAIChatCompletionsAdapter.js';
3
+ /** Reasoning-summary verbosity that gates what the model emits as `thinking` events. */
4
+ export type ReasoningSummary = 'auto' | 'concise' | 'detailed';
5
+ /** Per-request defaults applied to every call made by an {@link OpenAIResponsesAdapter}. */
6
+ export interface OpenAIResponsesAdapterDefaults {
7
+ /** Forwarded as `reasoning.effort` on every request. Reasoning models honour this. */
8
+ reasoningEffort?: ReasoningEffort;
9
+ /**
10
+ * Forwarded as `reasoning.summary` on every request. Required to receive
11
+ * reasoning summary deltas as `thinking` events. Defaults to `"auto"` so
12
+ * reasoning models surface thinking content without extra configuration.
13
+ * Set to `false` to disable.
14
+ */
15
+ reasoningSummary?: ReasoningSummary | false;
16
+ }
17
+ /**
18
+ * {@link LlmAdapter} implementation backed by the OpenAI Responses API
19
+ * (`/v1/responses`).
20
+ *
21
+ * Unlike {@link OpenAIChatCompletionsAdapter}, this adapter surfaces reasoning
22
+ * content from reasoning models — `gpt-5`, `o-series` — as `thinking` events.
23
+ * The adapter runs statelessly (`store: false`); the caller's `Conversation`
24
+ * history is replayed on every request.
25
+ */
26
+ export declare class OpenAIResponsesAdapter implements LlmAdapter {
27
+ private client;
28
+ private modelName;
29
+ private onUsageUpdate?;
30
+ private defaults;
31
+ /**
32
+ * @param apiKey - OpenAI API key.
33
+ * @param modelName - Model identifier (defaults to `"gpt-4o-mini"`). Any
34
+ * Responses-API-compatible model works, including reasoning models.
35
+ * @param onUsageUpdate - Optional callback invoked with token-usage data after each response.
36
+ * @param defaults - Provider-specific defaults applied to every request.
37
+ */
38
+ constructor(apiKey: string, modelName?: string, onUsageUpdate?: (usage: UsageMetadata) => void, defaults?: OpenAIResponsesAdapterDefaults);
39
+ private buildBaseParams;
40
+ /** {@inheritDoc LlmAdapter.generate} */
41
+ generate(request: AdapterRequest): Promise<AdapterResponse>;
42
+ /** {@inheritDoc LlmAdapter.generateStream} */
43
+ generateStream(request: AdapterRequest): AsyncIterable<AdapterStreamChunk>;
44
+ }
@@ -0,0 +1,217 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import OpenAI from 'openai';
4
+ /**
5
+ * {@link LlmAdapter} implementation backed by the OpenAI Responses API
6
+ * (`/v1/responses`).
7
+ *
8
+ * Unlike {@link OpenAIChatCompletionsAdapter}, this adapter surfaces reasoning
9
+ * content from reasoning models — `gpt-5`, `o-series` — as `thinking` events.
10
+ * The adapter runs statelessly (`store: false`); the caller's `Conversation`
11
+ * history is replayed on every request.
12
+ */
13
+ export class OpenAIResponsesAdapter {
14
+ client;
15
+ modelName;
16
+ onUsageUpdate;
17
+ defaults;
18
+ /**
19
+ * @param apiKey - OpenAI API key.
20
+ * @param modelName - Model identifier (defaults to `"gpt-4o-mini"`). Any
21
+ * Responses-API-compatible model works, including reasoning models.
22
+ * @param onUsageUpdate - Optional callback invoked with token-usage data after each response.
23
+ * @param defaults - Provider-specific defaults applied to every request.
24
+ */
25
+ constructor(apiKey, modelName = 'gpt-4o-mini', onUsageUpdate, defaults) {
26
+ this.client = new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
27
+ this.modelName = modelName;
28
+ this.onUsageUpdate = onUsageUpdate;
29
+ this.defaults = defaults ?? {};
30
+ }
31
+ buildBaseParams(request) {
32
+ const input = mapInput(request.messages);
33
+ const tools = mapTools(request.tools);
34
+ const config = (request.config ?? {});
35
+ const reasoningEffort = (typeof config.reasoning_effort === 'string'
36
+ ? config.reasoning_effort
37
+ : undefined) ?? this.defaults.reasoningEffort;
38
+ const reasoningSummary = this.defaults.reasoningSummary === false
39
+ ? undefined
40
+ : (this.defaults.reasoningSummary ?? 'auto');
41
+ const params = {
42
+ model: this.modelName,
43
+ input,
44
+ ...(request.system ? { instructions: request.system } : {}),
45
+ ...(tools ? { tools } : {}),
46
+ store: false,
47
+ ...(typeof config.temperature === 'number' ? { temperature: config.temperature } : {}),
48
+ ...(typeof config.maxTokens === 'number' ? { max_output_tokens: config.maxTokens } : {}),
49
+ ...(typeof config.topP === 'number' ? { top_p: config.topP } : {}),
50
+ ...(reasoningEffort || reasoningSummary
51
+ ? {
52
+ reasoning: {
53
+ ...(reasoningEffort ? { effort: reasoningEffort } : {}),
54
+ ...(reasoningSummary ? { summary: reasoningSummary } : {}),
55
+ },
56
+ }
57
+ : {}),
58
+ ...(request.outputSchema
59
+ ? {
60
+ text: {
61
+ format: {
62
+ type: 'json_schema',
63
+ name: 'output',
64
+ schema: request.outputSchema,
65
+ strict: true,
66
+ },
67
+ },
68
+ }
69
+ : {}),
70
+ };
71
+ return params;
72
+ }
73
+ /** {@inheritDoc LlmAdapter.generate} */
74
+ async generate(request) {
75
+ const params = {
76
+ ...this.buildBaseParams(request),
77
+ stream: false,
78
+ };
79
+ const response = await this.client.responses.create(params, { signal: request.signal });
80
+ if (response.usage && this.onUsageUpdate) {
81
+ this.onUsageUpdate({
82
+ promptTokens: response.usage.input_tokens,
83
+ completionTokens: response.usage.output_tokens,
84
+ totalTokens: response.usage.total_tokens,
85
+ });
86
+ }
87
+ let text;
88
+ const toolCalls = [];
89
+ for (const item of response.output ?? []) {
90
+ const parsed = parseOutputItem(item);
91
+ if (parsed.text !== undefined) {
92
+ text = (text ?? '') + parsed.text;
93
+ }
94
+ if (parsed.toolCall) {
95
+ toolCalls.push(parsed.toolCall);
96
+ }
97
+ }
98
+ return { text, toolCalls };
99
+ }
100
+ /** {@inheritDoc LlmAdapter.generateStream} */
101
+ async *generateStream(request) {
102
+ const params = {
103
+ ...this.buildBaseParams(request),
104
+ stream: true,
105
+ };
106
+ const stream = await this.client.responses.create(params, { signal: request.signal });
107
+ for await (const event of stream) {
108
+ switch (event.type) {
109
+ case 'response.output_text.delta':
110
+ if (event.delta)
111
+ yield { type: 'text_delta', delta: event.delta };
112
+ break;
113
+ case 'response.reasoning_summary_text.delta':
114
+ case 'response.reasoning_text.delta':
115
+ if (event.delta)
116
+ yield { type: 'thinking', delta: event.delta };
117
+ break;
118
+ case 'response.output_item.done':
119
+ if (event.item.type === 'function_call') {
120
+ yield {
121
+ type: 'tool_call',
122
+ toolCall: {
123
+ id: event.item.call_id,
124
+ name: event.item.name,
125
+ args: parseArguments(event.item.arguments),
126
+ },
127
+ };
128
+ }
129
+ break;
130
+ case 'response.completed':
131
+ if (event.response.usage && this.onUsageUpdate) {
132
+ this.onUsageUpdate({
133
+ promptTokens: event.response.usage.input_tokens,
134
+ completionTokens: event.response.usage.output_tokens,
135
+ totalTokens: event.response.usage.total_tokens,
136
+ });
137
+ }
138
+ break;
139
+ default:
140
+ break;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ function mapTools(tools) {
146
+ if (tools.length === 0)
147
+ return undefined;
148
+ return tools.map((t) => ({
149
+ type: 'function',
150
+ name: t.name,
151
+ description: t.description,
152
+ parameters: t.parameters,
153
+ strict: false,
154
+ }));
155
+ }
156
+ function mapInput(messages) {
157
+ const items = [];
158
+ for (const message of messages) {
159
+ if (message.content.type === 'text') {
160
+ items.push({
161
+ type: 'message',
162
+ role: message.role,
163
+ content: message.content.text,
164
+ });
165
+ }
166
+ else if (message.content.type === 'tool_calls') {
167
+ for (const call of message.content.calls) {
168
+ items.push({
169
+ type: 'function_call',
170
+ call_id: call.id,
171
+ name: call.name,
172
+ arguments: typeof call.args === 'string' ? call.args : JSON.stringify(call.args ?? {}),
173
+ });
174
+ }
175
+ }
176
+ else {
177
+ items.push({
178
+ type: 'function_call_output',
179
+ call_id: message.content.id,
180
+ output: typeof message.content.result === 'string'
181
+ ? message.content.result
182
+ : JSON.stringify(message.content.result),
183
+ });
184
+ }
185
+ }
186
+ return items;
187
+ }
188
+ function parseOutputItem(item) {
189
+ if (item.type === 'message') {
190
+ let text = '';
191
+ for (const part of item.content) {
192
+ if (part.type === 'output_text')
193
+ text += part.text;
194
+ }
195
+ return text ? { text } : {};
196
+ }
197
+ if (item.type === 'function_call') {
198
+ return {
199
+ toolCall: {
200
+ id: item.call_id,
201
+ name: item.name,
202
+ args: parseArguments(item.arguments),
203
+ },
204
+ };
205
+ }
206
+ return {};
207
+ }
208
+ function parseArguments(raw) {
209
+ if (!raw)
210
+ return {};
211
+ try {
212
+ return JSON.parse(raw);
213
+ }
214
+ catch {
215
+ return raw;
216
+ }
217
+ }
@@ -0,0 +1,4 @@
1
+ export { OpenAIChatCompletionsAdapter } from './OpenAIChatCompletionsAdapter.js';
2
+ export type { UsageMetadata, ReasoningEffort, OpenAIChatCompletionsAdapterDefaults, } from './OpenAIChatCompletionsAdapter.js';
3
+ export { OpenAIResponsesAdapter } from './OpenAIResponsesAdapter.js';
4
+ export type { ReasoningSummary, OpenAIResponsesAdapterDefaults } from './OpenAIResponsesAdapter.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export { OpenAIChatCompletionsAdapter } from './OpenAIChatCompletionsAdapter.js';
4
+ export { OpenAIResponsesAdapter } from './OpenAIResponsesAdapter.js';
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@mast-ai/openai",
3
+ "version": "0.3.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/andreban/mast-ai.git",
14
+ "directory": "packages/openai"
15
+ },
16
+ "publishConfig": {
17
+ "registry": "https://registry.npmjs.org",
18
+ "access": "public"
19
+ },
20
+ "scripts": {
21
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
22
+ "build": "npm run clean && tsc",
23
+ "prepublishOnly": "npm run build",
24
+ "dev": "tsc --watch",
25
+ "test": "vitest",
26
+ "lint": "eslint src",
27
+ "format": "prettier --write src"
28
+ },
29
+ "dependencies": {
30
+ "@mast-ai/core": "^0.3.0",
31
+ "openai": "^6.37.0"
32
+ },
33
+ "devDependencies": {
34
+ "typescript": "~6.0.2",
35
+ "vitest": "^4.1.4"
36
+ }
37
+ }