@rulvar/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 +202 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +698 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { CanonicalId, ChatEvent, ChatRequest, Effort, ModelCaps, ProviderAdapter, Usage, WireError } from "@rulvar/core";
|
|
2
|
+
|
|
3
|
+
//#region src/caps.d.ts
|
|
4
|
+
interface OpenAiModelInfo {
|
|
5
|
+
caps: ModelCaps;
|
|
6
|
+
api: "responses" | "chat";
|
|
7
|
+
/** Reasoning models reject non-default sampling parameters (docs/04, section 5.1). */
|
|
8
|
+
reasoning: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** Static seed table; docs/04 section 5 names the current model set. */
|
|
11
|
+
declare const OPENAI_MODELS: Record<string, OpenAiModelInfo>;
|
|
12
|
+
/** Unknown OpenAI models are assumed current-generation Responses models. */
|
|
13
|
+
declare function openAiModelInfo(model: string): OpenAiModelInfo;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/adapter.d.ts
|
|
16
|
+
/** The client sub-surface the adapter consumes; injectable for tests. */
|
|
17
|
+
interface OpenAiClientLike {
|
|
18
|
+
responses: {
|
|
19
|
+
create(params: Record<string, unknown>, opts?: {
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}): Promise<unknown>;
|
|
22
|
+
};
|
|
23
|
+
chat: {
|
|
24
|
+
completions: {
|
|
25
|
+
create(params: Record<string, unknown>, opts?: {
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}): Promise<unknown>;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
interface OpenAiAdapterOptions {
|
|
32
|
+
apiKey?: string;
|
|
33
|
+
baseURL?: string;
|
|
34
|
+
/** Test seam: a preconstructed client; production uses the openai SDK. */
|
|
35
|
+
client?: OpenAiClientLike;
|
|
36
|
+
}
|
|
37
|
+
/** Creates the first-class OpenAI adapter (id 'openai'); maxRetries 0. */
|
|
38
|
+
declare function openai(options?: OpenAiAdapterOptions): ProviderAdapter;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/compatible.d.ts
|
|
41
|
+
/**
|
|
42
|
+
* Gateways cannot be introspected reliably: when caps are not supplied
|
|
43
|
+
* the factory assumes the most conservative capability set (docs/04,
|
|
44
|
+
* section 6). Callers SHOULD supply caps for anything beyond it; the
|
|
45
|
+
* window and output floors here are deliberately small so an unprobed
|
|
46
|
+
* endpoint is never overcommitted. Absent pricing is legitimate for
|
|
47
|
+
* local models: they surface as unpriced in CostReport.
|
|
48
|
+
*/
|
|
49
|
+
declare const CONSERVATIVE_COMPATIBLE_CAPS: ModelCaps;
|
|
50
|
+
interface OpenAiCompatibleConfig {
|
|
51
|
+
/** Explicit adapter id, e.g. 'ollama', 'vllm', 'openrouter'. */
|
|
52
|
+
id: string;
|
|
53
|
+
baseURL: string;
|
|
54
|
+
apiKey?: string;
|
|
55
|
+
/** Per-model capability overrides merged over the conservative set. */
|
|
56
|
+
caps?: (model: string) => ModelCaps | Partial<ModelCaps>;
|
|
57
|
+
/** Test seam: a preconstructed client; production uses the openai SDK. */
|
|
58
|
+
client?: OpenAiClientLike;
|
|
59
|
+
}
|
|
60
|
+
/** Creates a Chat Completions dialect adapter for a compatible endpoint. */
|
|
61
|
+
declare function openaiCompatible(cfg: OpenAiCompatibleConfig): ProviderAdapter;
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/wire.d.ts
|
|
64
|
+
/** Bijective canonical-to-wire (call_*) id map (docs/04, section 1.2). */
|
|
65
|
+
declare class OpenAiIdMap {
|
|
66
|
+
private readonly toWire;
|
|
67
|
+
private readonly toCanonical;
|
|
68
|
+
private readonly mint;
|
|
69
|
+
constructor(mint: () => CanonicalId);
|
|
70
|
+
canonicalFor(wireId: string): CanonicalId;
|
|
71
|
+
wireFor(canonicalId: CanonicalId): string;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Canonical-to-wire effort (docs/04, sections 3.3 and 5.5): low through
|
|
75
|
+
* xhigh pass through; canonical max downmaps to xhigh (documented lossy;
|
|
76
|
+
* recorded in providerMetadata); provider 'none' is reachable only via
|
|
77
|
+
* providerOptions.openai.reasoningEffort.
|
|
78
|
+
*/
|
|
79
|
+
declare function mapOpenAiEffort(effort: Effort): {
|
|
80
|
+
wire: string;
|
|
81
|
+
downmapped: boolean;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Builds Responses API params. Manual item replay ONLY: store: false plus
|
|
85
|
+
* include reasoning.encrypted_content; previous_response_id and the
|
|
86
|
+
* Conversations API place state server-side, break replay identity, and
|
|
87
|
+
* are REJECTED as a typed ConfigError (docs/04, section 5.1). Role
|
|
88
|
+
* 'system' messages project into top-level instructions on every request.
|
|
89
|
+
*/
|
|
90
|
+
declare function buildResponsesParams(req: ChatRequest, ids: OpenAiIdMap): {
|
|
91
|
+
params: Record<string, unknown>;
|
|
92
|
+
effortDownmapped: boolean;
|
|
93
|
+
};
|
|
94
|
+
/** Raw Responses SSE events, structurally typed. */
|
|
95
|
+
type ResponsesStreamEvent = Record<string, unknown> & {
|
|
96
|
+
type: string;
|
|
97
|
+
};
|
|
98
|
+
/** Normalizes Responses usage: input_tokens already includes cached reads. */
|
|
99
|
+
declare function normalizeOpenAiUsage(raw: Record<string, unknown> | undefined): Usage;
|
|
100
|
+
/**
|
|
101
|
+
* Maps the typed Responses SSE stream to ChatEvents per the docs/04
|
|
102
|
+
* section 5.4 table. Canonical parts come from the typed output array,
|
|
103
|
+
* never the output_text aggregate. Raw output items ride
|
|
104
|
+
* finish.providerMetadata.openai.outputItems so the runtime can retain
|
|
105
|
+
* reasoning items as provider-raw parts.
|
|
106
|
+
*/
|
|
107
|
+
declare function mapResponsesStream(stream: AsyncIterable<ResponsesStreamEvent>, ids: OpenAiIdMap, emit: (event: ChatEvent) => void, options?: {
|
|
108
|
+
effortDownmapped?: boolean;
|
|
109
|
+
}): Promise<void>;
|
|
110
|
+
/** Projects SDK/API errors into the retryable WireError vocabulary. */
|
|
111
|
+
declare function openAiErrorToWire(error: unknown): WireError;
|
|
112
|
+
/**
|
|
113
|
+
* The Chat Completions degraded path (docs/04, section 5.6): delta-patched
|
|
114
|
+
* chunk assembly instead of typed SSE, nested function tools with explicit
|
|
115
|
+
* strict where supported, response_format instead of text.format, no
|
|
116
|
+
* reasoning item replay. Selected by caps (api: 'chat'), visible in
|
|
117
|
+
* events, never silent.
|
|
118
|
+
*/
|
|
119
|
+
declare function buildChatCompletionsParams(req: ChatRequest, ids: OpenAiIdMap): Record<string, unknown>;
|
|
120
|
+
/** Delta-patched chunk assembly for the degraded path. */
|
|
121
|
+
declare function mapChatCompletionsStream(stream: AsyncIterable<Record<string, unknown>>, ids: OpenAiIdMap, emit: (event: ChatEvent) => void): Promise<void>;
|
|
122
|
+
//#endregion
|
|
123
|
+
export { CONSERVATIVE_COMPATIBLE_CAPS, OPENAI_MODELS, type OpenAiAdapterOptions, type OpenAiClientLike, type OpenAiCompatibleConfig, OpenAiIdMap, type OpenAiModelInfo, type ResponsesStreamEvent, buildChatCompletionsParams, buildResponsesParams, mapChatCompletionsStream, mapOpenAiEffort, mapResponsesStream, normalizeOpenAiUsage, openAiErrorToWire, openAiModelInfo, openai, openaiCompatible };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,698 @@
|
|
|
1
|
+
import OpenAI from "openai";
|
|
2
|
+
import { ConfigError, createCanonicalIdMinter, isStrictCompatibleSchema } from "@rulvar/core";
|
|
3
|
+
//#region src/caps.ts
|
|
4
|
+
const REASONING_EFFORTS = [
|
|
5
|
+
"low",
|
|
6
|
+
"medium",
|
|
7
|
+
"high",
|
|
8
|
+
"xhigh"
|
|
9
|
+
];
|
|
10
|
+
function responses(contextWindow, maxOutputTokens, pricing) {
|
|
11
|
+
return {
|
|
12
|
+
caps: {
|
|
13
|
+
structuredOutput: "native",
|
|
14
|
+
supportsTemperature: false,
|
|
15
|
+
supportsParallelTools: true,
|
|
16
|
+
reasoningEfforts: [...REASONING_EFFORTS, "max"],
|
|
17
|
+
contextWindow,
|
|
18
|
+
maxOutputTokens,
|
|
19
|
+
pricing: {
|
|
20
|
+
inputUsdPerMTok: pricing.in,
|
|
21
|
+
outputUsdPerMTok: pricing.out,
|
|
22
|
+
cacheReadUsdPerMTok: pricing.cacheRead
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
api: "responses",
|
|
26
|
+
reasoning: true
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Static seed table; docs/04 section 5 names the current model set. */
|
|
30
|
+
const OPENAI_MODELS = {
|
|
31
|
+
"gpt-5.5": responses(4e5, 128e3, {
|
|
32
|
+
in: 10,
|
|
33
|
+
out: 40,
|
|
34
|
+
cacheRead: 1
|
|
35
|
+
}),
|
|
36
|
+
"gpt-5.5-pro": responses(4e5, 128e3, {
|
|
37
|
+
in: 40,
|
|
38
|
+
out: 160,
|
|
39
|
+
cacheRead: 4
|
|
40
|
+
}),
|
|
41
|
+
"gpt-5.4": responses(272e3, 1e5, {
|
|
42
|
+
in: 6,
|
|
43
|
+
out: 24,
|
|
44
|
+
cacheRead: .6
|
|
45
|
+
}),
|
|
46
|
+
"gpt-5.4-mini": responses(272e3, 1e5, {
|
|
47
|
+
in: 1.2,
|
|
48
|
+
out: 4.8,
|
|
49
|
+
cacheRead: .12
|
|
50
|
+
})
|
|
51
|
+
};
|
|
52
|
+
/** Unknown OpenAI models are assumed current-generation Responses models. */
|
|
53
|
+
function openAiModelInfo(model) {
|
|
54
|
+
const exact = OPENAI_MODELS[model];
|
|
55
|
+
if (exact !== void 0) return exact;
|
|
56
|
+
for (const [name, info] of Object.entries(OPENAI_MODELS)) if (model.startsWith(`${name}-`)) return info;
|
|
57
|
+
return responses(272e3, 1e5, {
|
|
58
|
+
in: 6,
|
|
59
|
+
out: 24,
|
|
60
|
+
cacheRead: .6
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/wire.ts
|
|
65
|
+
/**
|
|
66
|
+
* Canonical-to-wire mapping for the OpenAI Responses API (M1-T13): manual
|
|
67
|
+
* item replay only (store: false plus reasoning.encrypted_content, with
|
|
68
|
+
* reasoning items echoed verbatim between function calls), flattened
|
|
69
|
+
* strict function tools, text.format json_schema, the typed SSE catalog
|
|
70
|
+
* mapped to ChatEvent, effort mapping with the documented lossy max
|
|
71
|
+
* downmap, and usage normalization.
|
|
72
|
+
*
|
|
73
|
+
* Owning spec: docs/04-model-layer-spec.md, section "@rulvar/openai
|
|
74
|
+
* (Responses API)". Pure functions; adapter.ts owns the SDK client.
|
|
75
|
+
*/
|
|
76
|
+
/** Bijective canonical-to-wire (call_*) id map (docs/04, section 1.2). */
|
|
77
|
+
var OpenAiIdMap = class {
|
|
78
|
+
toWire = /* @__PURE__ */ new Map();
|
|
79
|
+
toCanonical = /* @__PURE__ */ new Map();
|
|
80
|
+
mint;
|
|
81
|
+
constructor(mint) {
|
|
82
|
+
this.mint = mint;
|
|
83
|
+
}
|
|
84
|
+
canonicalFor(wireId) {
|
|
85
|
+
const existing = this.toCanonical.get(wireId);
|
|
86
|
+
if (existing !== void 0) return existing;
|
|
87
|
+
const canonical = this.mint();
|
|
88
|
+
this.toCanonical.set(wireId, canonical);
|
|
89
|
+
this.toWire.set(canonical, wireId);
|
|
90
|
+
return canonical;
|
|
91
|
+
}
|
|
92
|
+
wireFor(canonicalId) {
|
|
93
|
+
const existing = this.toWire.get(canonicalId);
|
|
94
|
+
if (existing !== void 0) return existing;
|
|
95
|
+
const wireId = `call_${canonicalId}`;
|
|
96
|
+
this.toWire.set(canonicalId, wireId);
|
|
97
|
+
this.toCanonical.set(wireId, canonicalId);
|
|
98
|
+
return wireId;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Canonical-to-wire effort (docs/04, sections 3.3 and 5.5): low through
|
|
103
|
+
* xhigh pass through; canonical max downmaps to xhigh (documented lossy;
|
|
104
|
+
* recorded in providerMetadata); provider 'none' is reachable only via
|
|
105
|
+
* providerOptions.openai.reasoningEffort.
|
|
106
|
+
*/
|
|
107
|
+
function mapOpenAiEffort(effort) {
|
|
108
|
+
if (effort === "max") return {
|
|
109
|
+
wire: "xhigh",
|
|
110
|
+
downmapped: true
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
wire: effort,
|
|
114
|
+
downmapped: false
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Builds Responses API params. Manual item replay ONLY: store: false plus
|
|
119
|
+
* include reasoning.encrypted_content; previous_response_id and the
|
|
120
|
+
* Conversations API place state server-side, break replay identity, and
|
|
121
|
+
* are REJECTED as a typed ConfigError (docs/04, section 5.1). Role
|
|
122
|
+
* 'system' messages project into top-level instructions on every request.
|
|
123
|
+
*/
|
|
124
|
+
function buildResponsesParams(req, ids) {
|
|
125
|
+
const openaiOptions = req.providerOptions?.openai ?? {};
|
|
126
|
+
for (const forbidden of [
|
|
127
|
+
"previous_response_id",
|
|
128
|
+
"previousResponseId",
|
|
129
|
+
"conversation"
|
|
130
|
+
]) if (openaiOptions[forbidden] !== void 0) throw new ConfigError(`providerOptions.openai.${forbidden} is rejected: server-side conversation state is incompatible with content-addressed journal determinism (docs/04, section 5.1)`);
|
|
131
|
+
const instructions = [];
|
|
132
|
+
const input = [];
|
|
133
|
+
for (const msg of req.messages) {
|
|
134
|
+
if (msg.role === "system") {
|
|
135
|
+
for (const part of msg.parts) if (part.type === "text") instructions.push(part.text);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const content = [];
|
|
139
|
+
const flushContent = () => {
|
|
140
|
+
if (content.length > 0) input.push({
|
|
141
|
+
role: msg.role === "tool" ? "user" : msg.role,
|
|
142
|
+
content: content.splice(0)
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
for (const part of msg.parts) switch (part.type) {
|
|
146
|
+
case "text":
|
|
147
|
+
content.push({
|
|
148
|
+
type: msg.role === "assistant" ? "output_text" : "input_text",
|
|
149
|
+
text: part.text
|
|
150
|
+
});
|
|
151
|
+
break;
|
|
152
|
+
case "image":
|
|
153
|
+
content.push({
|
|
154
|
+
type: "input_image",
|
|
155
|
+
image_url: typeof part.data === "string" ? part.data : `data:${part.mediaType};base64,${Buffer.from(part.data).toString("base64")}`
|
|
156
|
+
});
|
|
157
|
+
break;
|
|
158
|
+
case "tool-call":
|
|
159
|
+
flushContent();
|
|
160
|
+
input.push({
|
|
161
|
+
type: "function_call",
|
|
162
|
+
call_id: ids.wireFor(part.id),
|
|
163
|
+
name: part.name,
|
|
164
|
+
arguments: JSON.stringify(part.args ?? {})
|
|
165
|
+
});
|
|
166
|
+
break;
|
|
167
|
+
case "tool-result":
|
|
168
|
+
flushContent();
|
|
169
|
+
input.push({
|
|
170
|
+
type: "function_call_output",
|
|
171
|
+
call_id: ids.wireFor(part.id),
|
|
172
|
+
output: typeof part.result === "string" ? part.result : JSON.stringify(part.result ?? null)
|
|
173
|
+
});
|
|
174
|
+
break;
|
|
175
|
+
case "provider-raw":
|
|
176
|
+
if (part.provider === "openai") {
|
|
177
|
+
flushContent();
|
|
178
|
+
input.push(part.block);
|
|
179
|
+
}
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
flushContent();
|
|
183
|
+
}
|
|
184
|
+
const params = {
|
|
185
|
+
model: req.model,
|
|
186
|
+
input,
|
|
187
|
+
store: false,
|
|
188
|
+
include: ["reasoning.encrypted_content"]
|
|
189
|
+
};
|
|
190
|
+
if (instructions.length > 0) params.instructions = instructions.join("\n\n");
|
|
191
|
+
if (req.maxOutputTokens !== void 0) params.max_output_tokens = req.maxOutputTokens;
|
|
192
|
+
if (req.tools !== void 0) {
|
|
193
|
+
params.tools = req.tools.map((tool) => ({
|
|
194
|
+
type: "function",
|
|
195
|
+
name: tool.name,
|
|
196
|
+
description: tool.description,
|
|
197
|
+
parameters: tool.parameters,
|
|
198
|
+
strict: isStrictCompatibleSchema(tool.parameters)
|
|
199
|
+
}));
|
|
200
|
+
if (req.toolChoice === "required") params.tool_choice = "required";
|
|
201
|
+
else if (typeof req.toolChoice === "object") params.tool_choice = {
|
|
202
|
+
type: "function",
|
|
203
|
+
name: req.toolChoice.name
|
|
204
|
+
};
|
|
205
|
+
else if (req.toolChoice === "auto") params.tool_choice = "auto";
|
|
206
|
+
else if (req.toolChoice === "none") params.tool_choice = "none";
|
|
207
|
+
}
|
|
208
|
+
if (req.schema !== void 0) {
|
|
209
|
+
const text = { format: {
|
|
210
|
+
type: "json_schema",
|
|
211
|
+
name: "output",
|
|
212
|
+
schema: req.schema,
|
|
213
|
+
strict: isStrictCompatibleSchema(req.schema)
|
|
214
|
+
} };
|
|
215
|
+
if (typeof openaiOptions.verbosity === "string") text.verbosity = openaiOptions.verbosity;
|
|
216
|
+
params.text = text;
|
|
217
|
+
} else if (typeof openaiOptions.verbosity === "string") params.text = { verbosity: openaiOptions.verbosity };
|
|
218
|
+
let effortDownmapped = false;
|
|
219
|
+
const explicitEffort = openaiOptions.reasoningEffort;
|
|
220
|
+
if (typeof explicitEffort === "string") params.reasoning = { effort: explicitEffort };
|
|
221
|
+
else if (req.effort !== void 0) {
|
|
222
|
+
const mapped = mapOpenAiEffort(req.effort);
|
|
223
|
+
effortDownmapped = mapped.downmapped;
|
|
224
|
+
params.reasoning = { effort: mapped.wire };
|
|
225
|
+
}
|
|
226
|
+
for (const key of ["temperature", "top_p"]) if (openaiOptions[key] !== void 0) params[key] = openaiOptions[key];
|
|
227
|
+
return {
|
|
228
|
+
params,
|
|
229
|
+
effortDownmapped
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** Normalizes Responses usage: input_tokens already includes cached reads. */
|
|
233
|
+
function normalizeOpenAiUsage(raw) {
|
|
234
|
+
const inputDetails = raw?.input_tokens_details;
|
|
235
|
+
const outputDetails = raw?.output_tokens_details;
|
|
236
|
+
const usage = {
|
|
237
|
+
inputTokens: typeof raw?.input_tokens === "number" ? raw.input_tokens : 0,
|
|
238
|
+
outputTokens: typeof raw?.output_tokens === "number" ? raw.output_tokens : 0,
|
|
239
|
+
cacheReadTokens: typeof inputDetails?.cached_tokens === "number" ? inputDetails.cached_tokens : 0,
|
|
240
|
+
cacheWriteTokens: 0
|
|
241
|
+
};
|
|
242
|
+
const reasoning = outputDetails?.reasoning_tokens;
|
|
243
|
+
if (typeof reasoning === "number" && reasoning > 0) usage.reasoningTokens = reasoning;
|
|
244
|
+
return usage;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Maps the typed Responses SSE stream to ChatEvents per the docs/04
|
|
248
|
+
* section 5.4 table. Canonical parts come from the typed output array,
|
|
249
|
+
* never the output_text aggregate. Raw output items ride
|
|
250
|
+
* finish.providerMetadata.openai.outputItems so the runtime can retain
|
|
251
|
+
* reasoning items as provider-raw parts.
|
|
252
|
+
*/
|
|
253
|
+
async function mapResponsesStream(stream, ids, emit, options) {
|
|
254
|
+
const callIdByItemId = /* @__PURE__ */ new Map();
|
|
255
|
+
for await (const event of stream) switch (event.type) {
|
|
256
|
+
case "response.output_item.added": {
|
|
257
|
+
const item = event.item;
|
|
258
|
+
if (item?.type === "function_call") {
|
|
259
|
+
const callId = item.call_id ?? item.id;
|
|
260
|
+
if (typeof item.id === "string") callIdByItemId.set(item.id, callId);
|
|
261
|
+
emit({
|
|
262
|
+
type: "tool-call-start",
|
|
263
|
+
id: ids.canonicalFor(callId),
|
|
264
|
+
name: item.name ?? ""
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
case "response.function_call_arguments.delta": {
|
|
270
|
+
const itemId = event.item_id;
|
|
271
|
+
const callId = itemId === void 0 ? void 0 : callIdByItemId.get(itemId);
|
|
272
|
+
if (callId !== void 0) emit({
|
|
273
|
+
type: "tool-call-delta",
|
|
274
|
+
id: ids.canonicalFor(callId),
|
|
275
|
+
argsTextDelta: event.delta ?? ""
|
|
276
|
+
});
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
case "response.output_item.done": {
|
|
280
|
+
const item = event.item;
|
|
281
|
+
if (item?.type === "function_call") {
|
|
282
|
+
const callId = item.call_id ?? item.id;
|
|
283
|
+
let args = {};
|
|
284
|
+
try {
|
|
285
|
+
args = typeof item.arguments === "string" && item.arguments !== "" ? JSON.parse(item.arguments) : {};
|
|
286
|
+
} catch {
|
|
287
|
+
args = { __unparsed: item.arguments };
|
|
288
|
+
}
|
|
289
|
+
emit({
|
|
290
|
+
type: "tool-call-end",
|
|
291
|
+
id: ids.canonicalFor(callId),
|
|
292
|
+
args
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
case "response.output_text.delta":
|
|
298
|
+
emit({
|
|
299
|
+
type: "text-delta",
|
|
300
|
+
text: event.delta ?? ""
|
|
301
|
+
});
|
|
302
|
+
break;
|
|
303
|
+
case "response.reasoning_summary_text.delta":
|
|
304
|
+
case "response.reasoning_text.delta":
|
|
305
|
+
emit({
|
|
306
|
+
type: "reasoning-delta",
|
|
307
|
+
text: event.delta ?? ""
|
|
308
|
+
});
|
|
309
|
+
break;
|
|
310
|
+
case "response.completed":
|
|
311
|
+
case "response.incomplete": {
|
|
312
|
+
const response = event.response;
|
|
313
|
+
const usage = normalizeOpenAiUsage(response?.usage);
|
|
314
|
+
emit({
|
|
315
|
+
type: "usage",
|
|
316
|
+
usage
|
|
317
|
+
});
|
|
318
|
+
let finish = { reason: "stop" };
|
|
319
|
+
if (event.type === "response.incomplete") {
|
|
320
|
+
const details = response?.incomplete_details;
|
|
321
|
+
finish = details?.reason === "max_output_tokens" ? { reason: "max-tokens" } : details?.reason === "content_filter" ? {
|
|
322
|
+
reason: "refusal",
|
|
323
|
+
refusal: { provider: "openai" }
|
|
324
|
+
} : { reason: "context-window-exceeded" };
|
|
325
|
+
} else {
|
|
326
|
+
const outputItems = response?.output ?? [];
|
|
327
|
+
const sawFunctionCall = outputItems.some((item) => item.type === "function_call");
|
|
328
|
+
if (outputItems.some((item) => Array.isArray(item.content) && item.content.some((part) => part.type === "refusal"))) finish = {
|
|
329
|
+
reason: "refusal",
|
|
330
|
+
refusal: { provider: "openai" }
|
|
331
|
+
};
|
|
332
|
+
else if (sawFunctionCall) finish = { reason: "tool-calls" };
|
|
333
|
+
}
|
|
334
|
+
const meta = { outputItems: response?.output ?? [] };
|
|
335
|
+
const reasoningItems = (response?.output ?? []).filter((item) => item.type === "reasoning");
|
|
336
|
+
if (reasoningItems.length > 0) meta.retainedParts = reasoningItems;
|
|
337
|
+
if (typeof response?.id === "string") meta.responseId = response.id;
|
|
338
|
+
if (options?.effortDownmapped === true) meta.effortDownmapped = "max->xhigh";
|
|
339
|
+
emit({
|
|
340
|
+
type: "finish",
|
|
341
|
+
finish,
|
|
342
|
+
usage,
|
|
343
|
+
providerMetadata: { openai: meta }
|
|
344
|
+
});
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
case "response.failed": {
|
|
348
|
+
const error = event.response?.error;
|
|
349
|
+
emit({
|
|
350
|
+
type: "error",
|
|
351
|
+
error: {
|
|
352
|
+
code: "agent",
|
|
353
|
+
message: error?.message ?? "response.failed",
|
|
354
|
+
retryable: false,
|
|
355
|
+
data: { kind: "transport" }
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
case "error":
|
|
361
|
+
emit({
|
|
362
|
+
type: "error",
|
|
363
|
+
error: {
|
|
364
|
+
code: "agent",
|
|
365
|
+
message: event.message ?? "stream error",
|
|
366
|
+
retryable: false,
|
|
367
|
+
data: { kind: "transport" }
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
return;
|
|
371
|
+
default: break;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/** Projects SDK/API errors into the retryable WireError vocabulary. */
|
|
375
|
+
function openAiErrorToWire(error) {
|
|
376
|
+
const record = error;
|
|
377
|
+
const status = typeof record.status === "number" ? record.status : void 0;
|
|
378
|
+
const message = typeof record.message === "string" ? record.message : String(error);
|
|
379
|
+
if (status === 429) {
|
|
380
|
+
let retryAfterMs;
|
|
381
|
+
const headers = record.headers;
|
|
382
|
+
if (headers !== void 0 && headers !== null) {
|
|
383
|
+
const value = typeof headers.get === "function" ? headers.get("retry-after") ?? void 0 : headers["retry-after"];
|
|
384
|
+
if (value !== void 0) retryAfterMs = Number(value) * 1e3;
|
|
385
|
+
}
|
|
386
|
+
return {
|
|
387
|
+
code: "agent",
|
|
388
|
+
message,
|
|
389
|
+
retryable: true,
|
|
390
|
+
data: {
|
|
391
|
+
kind: "rate-limit",
|
|
392
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs },
|
|
393
|
+
status: 429
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
code: "agent",
|
|
399
|
+
message,
|
|
400
|
+
retryable: status === void 0 || status >= 500,
|
|
401
|
+
data: {
|
|
402
|
+
kind: "transport",
|
|
403
|
+
...status === void 0 ? {} : { status }
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* The Chat Completions degraded path (docs/04, section 5.6): delta-patched
|
|
409
|
+
* chunk assembly instead of typed SSE, nested function tools with explicit
|
|
410
|
+
* strict where supported, response_format instead of text.format, no
|
|
411
|
+
* reasoning item replay. Selected by caps (api: 'chat'), visible in
|
|
412
|
+
* events, never silent.
|
|
413
|
+
*/
|
|
414
|
+
function buildChatCompletionsParams(req, ids) {
|
|
415
|
+
const messages = [];
|
|
416
|
+
for (const msg of req.messages) {
|
|
417
|
+
if (msg.role === "system") {
|
|
418
|
+
const text = msg.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
|
|
419
|
+
messages.push({
|
|
420
|
+
role: "system",
|
|
421
|
+
content: text
|
|
422
|
+
});
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
if (msg.role === "assistant") {
|
|
426
|
+
const text = msg.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
427
|
+
const toolCalls = msg.parts.filter((part) => part.type === "tool-call").map((part) => {
|
|
428
|
+
const call = part;
|
|
429
|
+
return {
|
|
430
|
+
id: ids.wireFor(call.id),
|
|
431
|
+
type: "function",
|
|
432
|
+
function: {
|
|
433
|
+
name: call.name,
|
|
434
|
+
arguments: JSON.stringify(call.args ?? {})
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
});
|
|
438
|
+
const item = { role: "assistant" };
|
|
439
|
+
if (text !== "") item.content = text;
|
|
440
|
+
if (toolCalls.length > 0) item.tool_calls = toolCalls;
|
|
441
|
+
messages.push(item);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
for (const part of msg.parts) if (part.type === "tool-result") messages.push({
|
|
445
|
+
role: "tool",
|
|
446
|
+
tool_call_id: ids.wireFor(part.id),
|
|
447
|
+
content: typeof part.result === "string" ? part.result : JSON.stringify(part.result ?? null)
|
|
448
|
+
});
|
|
449
|
+
else if (part.type === "text") messages.push({
|
|
450
|
+
role: "user",
|
|
451
|
+
content: part.text
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
const params = {
|
|
455
|
+
model: req.model,
|
|
456
|
+
messages
|
|
457
|
+
};
|
|
458
|
+
if (req.maxOutputTokens !== void 0) params.max_completion_tokens = req.maxOutputTokens;
|
|
459
|
+
if (req.stopSequences !== void 0) params.stop = req.stopSequences;
|
|
460
|
+
if (req.tools !== void 0) {
|
|
461
|
+
params.tools = req.tools.map((tool) => ({
|
|
462
|
+
type: "function",
|
|
463
|
+
function: {
|
|
464
|
+
name: tool.name,
|
|
465
|
+
description: tool.description,
|
|
466
|
+
parameters: tool.parameters,
|
|
467
|
+
strict: isStrictCompatibleSchema(tool.parameters)
|
|
468
|
+
}
|
|
469
|
+
}));
|
|
470
|
+
if (req.toolChoice === "required") params.tool_choice = "required";
|
|
471
|
+
else if (typeof req.toolChoice === "object") params.tool_choice = {
|
|
472
|
+
type: "function",
|
|
473
|
+
function: { name: req.toolChoice.name }
|
|
474
|
+
};
|
|
475
|
+
else if (req.toolChoice === "none") params.tool_choice = "none";
|
|
476
|
+
}
|
|
477
|
+
if (req.schema !== void 0) params.response_format = {
|
|
478
|
+
type: "json_schema",
|
|
479
|
+
json_schema: {
|
|
480
|
+
name: "output",
|
|
481
|
+
schema: req.schema,
|
|
482
|
+
strict: isStrictCompatibleSchema(req.schema)
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
return params;
|
|
486
|
+
}
|
|
487
|
+
/** Delta-patched chunk assembly for the degraded path. */
|
|
488
|
+
async function mapChatCompletionsStream(stream, ids, emit) {
|
|
489
|
+
const pendingCalls = /* @__PURE__ */ new Map();
|
|
490
|
+
let finishReason;
|
|
491
|
+
let usage = {
|
|
492
|
+
inputTokens: 0,
|
|
493
|
+
outputTokens: 0,
|
|
494
|
+
cacheReadTokens: 0,
|
|
495
|
+
cacheWriteTokens: 0
|
|
496
|
+
};
|
|
497
|
+
for await (const chunk of stream) {
|
|
498
|
+
const choice = chunk.choices?.[0];
|
|
499
|
+
const delta = choice?.delta;
|
|
500
|
+
if (typeof delta?.content === "string" && delta.content !== "") emit({
|
|
501
|
+
type: "text-delta",
|
|
502
|
+
text: delta.content
|
|
503
|
+
});
|
|
504
|
+
const toolCalls = delta?.tool_calls;
|
|
505
|
+
if (toolCalls !== void 0) for (const call of toolCalls) {
|
|
506
|
+
const index = call.index ?? 0;
|
|
507
|
+
const fn = call.function;
|
|
508
|
+
let pending = pendingCalls.get(index);
|
|
509
|
+
if (pending === void 0) {
|
|
510
|
+
pending = {
|
|
511
|
+
id: call.id ?? `call_${index}`,
|
|
512
|
+
name: "",
|
|
513
|
+
args: ""
|
|
514
|
+
};
|
|
515
|
+
pendingCalls.set(index, pending);
|
|
516
|
+
emit({
|
|
517
|
+
type: "tool-call-start",
|
|
518
|
+
id: ids.canonicalFor(pending.id),
|
|
519
|
+
name: fn?.name ?? ""
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
if (typeof fn?.name === "string") pending.name += fn.name;
|
|
523
|
+
if (typeof fn?.arguments === "string" && fn.arguments !== "") {
|
|
524
|
+
pending.args += fn.arguments;
|
|
525
|
+
emit({
|
|
526
|
+
type: "tool-call-delta",
|
|
527
|
+
id: ids.canonicalFor(pending.id),
|
|
528
|
+
argsTextDelta: fn.arguments
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
if (typeof choice?.finish_reason === "string") finishReason = choice.finish_reason;
|
|
533
|
+
const chunkUsage = chunk.usage;
|
|
534
|
+
if (chunkUsage !== void 0 && chunkUsage !== null) {
|
|
535
|
+
const promptDetails = chunkUsage.prompt_tokens_details;
|
|
536
|
+
usage = {
|
|
537
|
+
inputTokens: typeof chunkUsage.prompt_tokens === "number" ? chunkUsage.prompt_tokens : 0,
|
|
538
|
+
outputTokens: typeof chunkUsage.completion_tokens === "number" ? chunkUsage.completion_tokens : 0,
|
|
539
|
+
cacheReadTokens: typeof promptDetails?.cached_tokens === "number" ? promptDetails.cached_tokens : 0,
|
|
540
|
+
cacheWriteTokens: 0
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
for (const [, pending] of pendingCalls) {
|
|
545
|
+
let args = {};
|
|
546
|
+
try {
|
|
547
|
+
args = pending.args === "" ? {} : JSON.parse(pending.args);
|
|
548
|
+
} catch {
|
|
549
|
+
args = { __unparsed: pending.args };
|
|
550
|
+
}
|
|
551
|
+
emit({
|
|
552
|
+
type: "tool-call-end",
|
|
553
|
+
id: ids.canonicalFor(pending.id),
|
|
554
|
+
args
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
emit({
|
|
558
|
+
type: "usage",
|
|
559
|
+
usage
|
|
560
|
+
});
|
|
561
|
+
emit({
|
|
562
|
+
type: "finish",
|
|
563
|
+
finish: finishReason === "length" ? { reason: "max-tokens" } : finishReason === "tool_calls" ? { reason: "tool-calls" } : finishReason === "content_filter" ? {
|
|
564
|
+
reason: "refusal",
|
|
565
|
+
refusal: { provider: "openai" }
|
|
566
|
+
} : { reason: "stop" },
|
|
567
|
+
usage,
|
|
568
|
+
providerMetadata: { openai: { degradedPath: "chat" } }
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
//#endregion
|
|
572
|
+
//#region src/adapter.ts
|
|
573
|
+
/**
|
|
574
|
+
* The @rulvar/openai ProviderAdapter (M1-T13): Responses API first, Chat
|
|
575
|
+
* Completions as the caps-selected degraded path, SDK autoretries
|
|
576
|
+
* disabled.
|
|
577
|
+
*
|
|
578
|
+
* Owning spec: docs/04-model-layer-spec.md, section "@rulvar/openai
|
|
579
|
+
* (Responses API)". The openaiCompatible factory ships in M3.
|
|
580
|
+
*/
|
|
581
|
+
/** Creates the first-class OpenAI adapter (id 'openai'); maxRetries 0. */
|
|
582
|
+
function openai(options = {}) {
|
|
583
|
+
const client = options.client ?? new OpenAI({
|
|
584
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
|
|
585
|
+
...options.baseURL === void 0 ? {} : { baseURL: options.baseURL },
|
|
586
|
+
maxRetries: 0
|
|
587
|
+
});
|
|
588
|
+
const ids = new OpenAiIdMap(createCanonicalIdMinter());
|
|
589
|
+
return {
|
|
590
|
+
id: "openai",
|
|
591
|
+
provider: "openai",
|
|
592
|
+
caps(model) {
|
|
593
|
+
return openAiModelInfo(model).caps;
|
|
594
|
+
},
|
|
595
|
+
async *stream(req, signal) {
|
|
596
|
+
const info = openAiModelInfo(req.model);
|
|
597
|
+
const pending = [];
|
|
598
|
+
const emit = (event) => {
|
|
599
|
+
pending.push(event);
|
|
600
|
+
};
|
|
601
|
+
try {
|
|
602
|
+
if (info.api === "responses") {
|
|
603
|
+
const { params, effortDownmapped } = buildResponsesParams(req, ids);
|
|
604
|
+
await mapResponsesStream(await client.responses.create({
|
|
605
|
+
...params,
|
|
606
|
+
stream: true
|
|
607
|
+
}, signal === void 0 ? void 0 : { signal }), ids, emit, { effortDownmapped });
|
|
608
|
+
} else {
|
|
609
|
+
const params = buildChatCompletionsParams(req, ids);
|
|
610
|
+
await mapChatCompletionsStream(await client.chat.completions.create({
|
|
611
|
+
...params,
|
|
612
|
+
stream: true,
|
|
613
|
+
stream_options: { include_usage: true }
|
|
614
|
+
}, signal === void 0 ? void 0 : { signal }), ids, emit);
|
|
615
|
+
}
|
|
616
|
+
} catch (thrown) {
|
|
617
|
+
if (signal?.aborted !== true) pending.push({
|
|
618
|
+
type: "error",
|
|
619
|
+
error: openAiErrorToWire(thrown)
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
for (const event of pending) yield event;
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
//#endregion
|
|
627
|
+
//#region src/compatible.ts
|
|
628
|
+
/**
|
|
629
|
+
* openaiCompatible factory (M3-T06): a ProviderAdapter for
|
|
630
|
+
* OpenAI-compatible endpoints (Ollama, vLLM, Mistral, OpenRouter,
|
|
631
|
+
* arbitrary gateways) speaking the Chat Completions dialect by
|
|
632
|
+
* construction. Explicit ids let several endpoints coexist in one
|
|
633
|
+
* engine; a duplicate adapterId at createEngine is a typed ConfigError
|
|
634
|
+
* raised by the adapter registry.
|
|
635
|
+
*
|
|
636
|
+
* Owning spec: docs/04-model-layer-spec.md, section "openaiCompatible
|
|
637
|
+
* factory".
|
|
638
|
+
*/
|
|
639
|
+
/**
|
|
640
|
+
* Gateways cannot be introspected reliably: when caps are not supplied
|
|
641
|
+
* the factory assumes the most conservative capability set (docs/04,
|
|
642
|
+
* section 6). Callers SHOULD supply caps for anything beyond it; the
|
|
643
|
+
* window and output floors here are deliberately small so an unprobed
|
|
644
|
+
* endpoint is never overcommitted. Absent pricing is legitimate for
|
|
645
|
+
* local models: they surface as unpriced in CostReport.
|
|
646
|
+
*/
|
|
647
|
+
const CONSERVATIVE_COMPATIBLE_CAPS = {
|
|
648
|
+
structuredOutput: "prompt",
|
|
649
|
+
supportsTemperature: true,
|
|
650
|
+
supportsParallelTools: false,
|
|
651
|
+
reasoningEfforts: [],
|
|
652
|
+
contextWindow: 8192,
|
|
653
|
+
maxOutputTokens: 4096
|
|
654
|
+
};
|
|
655
|
+
/** Creates a Chat Completions dialect adapter for a compatible endpoint. */
|
|
656
|
+
function openaiCompatible(cfg) {
|
|
657
|
+
if (cfg.id === void 0 || cfg.id === "") throw new ConfigError("openaiCompatible requires an explicit non-empty 'id' (docs/04, section 6)");
|
|
658
|
+
if (cfg.baseURL === void 0 || cfg.baseURL === "") throw new ConfigError("openaiCompatible requires 'baseURL'");
|
|
659
|
+
const client = cfg.client ?? new OpenAI({
|
|
660
|
+
baseURL: cfg.baseURL,
|
|
661
|
+
apiKey: cfg.apiKey ?? "rulvar-no-key",
|
|
662
|
+
maxRetries: 0
|
|
663
|
+
});
|
|
664
|
+
const ids = new OpenAiIdMap(createCanonicalIdMinter());
|
|
665
|
+
return {
|
|
666
|
+
id: cfg.id,
|
|
667
|
+
provider: "openai",
|
|
668
|
+
caps(model) {
|
|
669
|
+
const overrides = cfg.caps?.(model);
|
|
670
|
+
return overrides === void 0 ? CONSERVATIVE_COMPATIBLE_CAPS : {
|
|
671
|
+
...CONSERVATIVE_COMPATIBLE_CAPS,
|
|
672
|
+
...overrides
|
|
673
|
+
};
|
|
674
|
+
},
|
|
675
|
+
async *stream(req, signal) {
|
|
676
|
+
const pending = [];
|
|
677
|
+
const emit = (event) => {
|
|
678
|
+
pending.push(event);
|
|
679
|
+
};
|
|
680
|
+
try {
|
|
681
|
+
const params = buildChatCompletionsParams(req, ids);
|
|
682
|
+
await mapChatCompletionsStream(await client.chat.completions.create({
|
|
683
|
+
...params,
|
|
684
|
+
stream: true,
|
|
685
|
+
stream_options: { include_usage: true }
|
|
686
|
+
}, signal === void 0 ? void 0 : { signal }), ids, emit);
|
|
687
|
+
} catch (thrown) {
|
|
688
|
+
if (signal?.aborted !== true) pending.push({
|
|
689
|
+
type: "error",
|
|
690
|
+
error: openAiErrorToWire(thrown)
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
for (const event of pending) yield event;
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
//#endregion
|
|
698
|
+
export { CONSERVATIVE_COMPATIBLE_CAPS, OPENAI_MODELS, OpenAiIdMap, buildChatCompletionsParams, buildResponsesParams, mapChatCompletionsStream, mapOpenAiEffort, mapResponsesStream, normalizeOpenAiUsage, openAiErrorToWire, openAiModelInfo, openai, openaiCompatible };
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rulvar/openai",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "rulvar first-class provider adapter for the OpenAI Responses API, plus the openaiCompatible factory.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.12.0"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"openai": "^6.45.0",
|
|
26
|
+
"@rulvar/core": "1.0.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.20.0",
|
|
30
|
+
"tsdown": "^0.22.3",
|
|
31
|
+
"typescript": "~6.0.3"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/o-stepper/rulvar.git",
|
|
36
|
+
"directory": "packages/openai"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://rulvar.com",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/o-stepper/rulvar/issues"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsdown",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"lint": "eslint .",
|
|
46
|
+
"pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
|
|
47
|
+
}
|
|
48
|
+
}
|