@lostgradient/operative-openai 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +174 -2
- package/dist/batches/openai.d.ts +83 -0
- package/dist/batches/openai.js +101 -0
- package/dist/embeddings/openai.d.ts +36 -0
- package/dist/embeddings/openai.js +37 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +24 -0
- package/dist/openai-catalog.d.ts +44 -0
- package/dist/openai-catalog.js +236 -0
- package/dist/openai-definition.d.ts +24 -0
- package/dist/openai-definition.js +13 -0
- package/dist/openai-errors.d.ts +27 -0
- package/dist/openai-errors.js +43 -0
- package/dist/openai-parts.d.ts +29 -0
- package/dist/openai-parts.js +83 -0
- package/dist/openai-response-format.d.ts +27 -0
- package/dist/openai-response-format.js +26 -0
- package/dist/openai-tool-choice.d.ts +15 -0
- package/dist/openai-tool-choice.js +12 -0
- package/dist/openai-types.d.ts +313 -0
- package/dist/openai-types.js +1 -0
- package/dist/openai.d.ts +28 -0
- package/dist/openai.js +466 -0
- package/dist/streaming/normalize-openai.d.ts +18 -0
- package/dist/streaming/normalize-openai.js +213 -0
- package/dist/test/openai-fixtures.d.ts +19 -0
- package/dist/test/openai-fixtures.js +229 -0
- package/dist/test/openai-mock-clients.d.ts +36 -0
- package/dist/test/openai-mock-clients.js +84 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.js +11 -0
- package/package.json +31 -3
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { FULL_PARAMETER_COMPATIBILITY, aliasesFor, backendPricing, deepFreeze, degradationOf, portableTiers, readEnvironmentConfiguration, } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
// The OpenAI catalog: its models' limits, modalities, prices, aliases and effort support, and the
|
|
3
|
+
// rows the plugin offers. Repricing a model or adding one is an edit to this file alone.
|
|
4
|
+
// ── Modality matrices ───────────────────────────────────────────────────────
|
|
5
|
+
const UNSUPPORTED_MODALITY_ENTRY = {
|
|
6
|
+
input: false,
|
|
7
|
+
output: false,
|
|
8
|
+
sourceForms: [],
|
|
9
|
+
};
|
|
10
|
+
// https://developers.openai.com/api/docs/guides/pdf-files and
|
|
11
|
+
// https://developers.openai.com/api/docs/guides/images-vision — confirmed
|
|
12
|
+
// 2026-09-02: both pages document base64/URL image and file input; neither
|
|
13
|
+
// documents a `file_id` (Files-API) input path for `chat.completions`
|
|
14
|
+
// specifically — that capability is scoped to the Responses API — so
|
|
15
|
+
// `chat.completions` takes a PDF as `inline` bytes, a `data-url`, or a Files API
|
|
16
|
+
// `provider-file` id (https://developers.openai.com/api/docs/guides/pdf-files:
|
|
17
|
+
// "Chat Completions supports only .pdf (application/pdf) for both file_data and
|
|
18
|
+
// file_id"), and a `remote-url` as well for an image.
|
|
19
|
+
// `chat.completions` has no audio or video input/output and no image or
|
|
20
|
+
// audio generation (that is the Responses/Realtime API's surface).
|
|
21
|
+
const OPENAI_MODALITIES = Object.freeze({
|
|
22
|
+
text: { input: true, output: true, sourceForms: ['inline'] },
|
|
23
|
+
image: { input: true, output: false, sourceForms: ['inline', 'data-url', 'remote-url'] },
|
|
24
|
+
document: { input: true, output: false, sourceForms: ['inline', 'data-url', 'provider-file'] },
|
|
25
|
+
audio: UNSUPPORTED_MODALITY_ENTRY,
|
|
26
|
+
video: UNSUPPORTED_MODALITY_ENTRY,
|
|
27
|
+
file: UNSUPPORTED_MODALITY_ENTRY,
|
|
28
|
+
});
|
|
29
|
+
// ── Limits ──────────────────────────────────────────────────────────────────
|
|
30
|
+
export const OPENAI_LIMITS = Object.freeze({
|
|
31
|
+
// https://developers.openai.com/api/docs/models/gpt-4.1 — confirmed
|
|
32
|
+
// 2026-09-02: context 1,047,576, max output 32,768.
|
|
33
|
+
'gpt-4.1': { contextWindowTokens: 1_047_576, maxOutputTokens: 32_768 },
|
|
34
|
+
// Same family; OpenAI documents gpt-4.1-mini and gpt-4.1-nano sharing the
|
|
35
|
+
// gpt-4.1 page's context/output limits. Not separately confirmed live.
|
|
36
|
+
'gpt-4.1-mini': { contextWindowTokens: 1_047_576, maxOutputTokens: 32_768 },
|
|
37
|
+
'gpt-4.1-nano': { contextWindowTokens: 1_047_576, maxOutputTokens: 32_768 },
|
|
38
|
+
// Long-standing published o-series specification (OpenAI's o3/o3-mini/
|
|
39
|
+
// o4-mini model pages); the OpenAI docs domain redirected mid-fetch on
|
|
40
|
+
// 2026-09-02 and the redirected page did not carry this table, so this is
|
|
41
|
+
// not independently reconfirmed live in this change.
|
|
42
|
+
o3: { contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
|
|
43
|
+
'o3-mini': { contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
|
|
44
|
+
'o4-mini': { contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
|
|
45
|
+
// Long-standing published GPT-4o specification, same live-fetch caveat as
|
|
46
|
+
// the o-series rows above.
|
|
47
|
+
'gpt-4o': { contextWindowTokens: 128_000, maxOutputTokens: 16_384 },
|
|
48
|
+
'gpt-4o-mini': { contextWindowTokens: 128_000, maxOutputTokens: 16_384 },
|
|
49
|
+
});
|
|
50
|
+
const OPENAI_MODALITIES_TABLE = Object.freeze({
|
|
51
|
+
// OPENAI_MODALITIES above — https://developers.openai.com/api/docs/guides/pdf-files
|
|
52
|
+
// and https://developers.openai.com/api/docs/guides/images-vision, confirmed 2026-09-02.
|
|
53
|
+
'gpt-4.1': OPENAI_MODALITIES,
|
|
54
|
+
'gpt-4.1-mini': OPENAI_MODALITIES,
|
|
55
|
+
'gpt-4.1-nano': OPENAI_MODALITIES,
|
|
56
|
+
o3: OPENAI_MODALITIES,
|
|
57
|
+
'o3-mini': OPENAI_MODALITIES,
|
|
58
|
+
'o4-mini': OPENAI_MODALITIES,
|
|
59
|
+
'gpt-4o': OPENAI_MODALITIES,
|
|
60
|
+
'gpt-4o-mini': OPENAI_MODALITIES,
|
|
61
|
+
});
|
|
62
|
+
/** One model's limits; throws for a model with no row, so a model added elsewhere without limits fails loudly. */
|
|
63
|
+
function requireLimits(model) {
|
|
64
|
+
const entry = Object.hasOwn(OPENAI_LIMITS, model) ? OPENAI_LIMITS[model] : undefined;
|
|
65
|
+
if (!entry)
|
|
66
|
+
throw new Error(`model-catalog: no limits entry for openai/${model}`);
|
|
67
|
+
return entry;
|
|
68
|
+
}
|
|
69
|
+
/** One model's modality matrix; throws for a model with no row. */
|
|
70
|
+
function requireModalities(model) {
|
|
71
|
+
const entry = Object.hasOwn(OPENAI_MODALITIES_TABLE, model)
|
|
72
|
+
? OPENAI_MODALITIES_TABLE[model]
|
|
73
|
+
: undefined;
|
|
74
|
+
if (!entry)
|
|
75
|
+
throw new Error(`model-catalog: no modalities entry for openai/${model}`);
|
|
76
|
+
return entry;
|
|
77
|
+
}
|
|
78
|
+
// ── Pricing ─────────────────────────────────────────────────────────────────
|
|
79
|
+
const OPENAI_CACHE_READ_MULTIPLIER = 0.5;
|
|
80
|
+
function openAICachePricing(promptCostPerMillionTokens) {
|
|
81
|
+
return {
|
|
82
|
+
cacheReadCostPerMillionTokens: promptCostPerMillionTokens * OPENAI_CACHE_READ_MULTIPLIER,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** OpenAI list prices by model. */
|
|
86
|
+
export const openAIPricingTable = Object.freeze({
|
|
87
|
+
// OpenAI GPT-4o / 4.1 / o3 / o4-mini
|
|
88
|
+
'gpt-4o': {
|
|
89
|
+
promptCostPerMillionTokens: 2.5,
|
|
90
|
+
completionCostPerMillionTokens: 10,
|
|
91
|
+
...openAICachePricing(2.5),
|
|
92
|
+
},
|
|
93
|
+
'gpt-4o-mini': {
|
|
94
|
+
promptCostPerMillionTokens: 0.15,
|
|
95
|
+
completionCostPerMillionTokens: 0.6,
|
|
96
|
+
...openAICachePricing(0.15),
|
|
97
|
+
},
|
|
98
|
+
'gpt-4.1': {
|
|
99
|
+
promptCostPerMillionTokens: 2,
|
|
100
|
+
completionCostPerMillionTokens: 8,
|
|
101
|
+
...openAICachePricing(2),
|
|
102
|
+
},
|
|
103
|
+
'gpt-4.1-mini': {
|
|
104
|
+
promptCostPerMillionTokens: 0.4,
|
|
105
|
+
completionCostPerMillionTokens: 1.6,
|
|
106
|
+
...openAICachePricing(0.4),
|
|
107
|
+
},
|
|
108
|
+
'gpt-4.1-nano': {
|
|
109
|
+
promptCostPerMillionTokens: 0.1,
|
|
110
|
+
completionCostPerMillionTokens: 0.4,
|
|
111
|
+
...openAICachePricing(0.1),
|
|
112
|
+
},
|
|
113
|
+
o3: {
|
|
114
|
+
promptCostPerMillionTokens: 10,
|
|
115
|
+
completionCostPerMillionTokens: 40,
|
|
116
|
+
...openAICachePricing(10),
|
|
117
|
+
},
|
|
118
|
+
'o3-mini': {
|
|
119
|
+
promptCostPerMillionTokens: 1.1,
|
|
120
|
+
completionCostPerMillionTokens: 4.4,
|
|
121
|
+
...openAICachePricing(1.1),
|
|
122
|
+
},
|
|
123
|
+
'o4-mini': {
|
|
124
|
+
promptCostPerMillionTokens: 1.1,
|
|
125
|
+
completionCostPerMillionTokens: 4.4,
|
|
126
|
+
...openAICachePricing(1.1),
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
// ── Aliases ─────────────────────────────────────────────────────────────────
|
|
130
|
+
/**
|
|
131
|
+
* OpenAI shorthand aliases. `gpt`/`gpt-mini`/`gpt-nano` map to the GPT-4.1
|
|
132
|
+
* chat-completion family; `o`/`o-mini` map to the o-series reasoning models
|
|
133
|
+
* that accept `reasoning_effort` (see `./effort.ts`). Targets are drawn from
|
|
134
|
+
* the model IDs already pinned in `cost-estimation.ts`.
|
|
135
|
+
*/
|
|
136
|
+
export const OPENAI_MODEL_ALIASES = Object.freeze({
|
|
137
|
+
gpt: 'gpt-4.1',
|
|
138
|
+
'gpt-mini': 'gpt-4.1-mini',
|
|
139
|
+
'gpt-nano': 'gpt-4.1-nano',
|
|
140
|
+
o: 'o3',
|
|
141
|
+
'o-mini': 'o3-mini',
|
|
142
|
+
});
|
|
143
|
+
function resolveModelAlias(model, aliases) {
|
|
144
|
+
if (model === 'inherit')
|
|
145
|
+
return model;
|
|
146
|
+
return (Object.hasOwn(aliases, model) ? aliases[model] : undefined) ?? model;
|
|
147
|
+
}
|
|
148
|
+
/** Resolves an OpenAI shorthand alias (or full model ID) to a concrete model ID. */
|
|
149
|
+
export function resolveOpenAIModel(model) {
|
|
150
|
+
return resolveModelAlias(model, OPENAI_MODEL_ALIASES);
|
|
151
|
+
}
|
|
152
|
+
// ── Effort ──────────────────────────────────────────────────────────────────
|
|
153
|
+
/**
|
|
154
|
+
* OpenAI models that accept `reasoning_effort` — the o-series reasoning
|
|
155
|
+
* models. The GPT-4o / GPT-4.1 chat-completion family rejects the
|
|
156
|
+
* parameter, so it is degraded to "omit" for those models.
|
|
157
|
+
*/
|
|
158
|
+
export const OPENAI_REASONING_MODELS = new Set(['o3', 'o3-mini', 'o4-mini']);
|
|
159
|
+
/**
|
|
160
|
+
* Resolves the requested effort tier to OpenAI's `reasoning_effort` value.
|
|
161
|
+
* OpenAI's own vocabulary has only three tiers (`low`/`medium`/`high`) —
|
|
162
|
+
* the two provider-neutral tiers above `high` (`xhigh`, `max`) clamp down
|
|
163
|
+
* to `high` rather than erroring. Returns `undefined` for non-reasoning
|
|
164
|
+
* models, where the caller must omit `reasoning_effort` entirely.
|
|
165
|
+
*/
|
|
166
|
+
export function resolveOpenAIEffort(requested, resolvedModel) {
|
|
167
|
+
if (!OPENAI_REASONING_MODELS.has(resolvedModel))
|
|
168
|
+
return undefined;
|
|
169
|
+
if (requested === 'low' || requested === 'medium')
|
|
170
|
+
return requested;
|
|
171
|
+
return 'high';
|
|
172
|
+
}
|
|
173
|
+
// ── Rows ────────────────────────────────────────────────────────────────────
|
|
174
|
+
// OpenAI: https://developers.openai.com/api/docs/guides/images-vision: "Up to
|
|
175
|
+
// 1,500 images per request" (with up to 512 MB total payload per request).
|
|
176
|
+
const OPENAI_MEDIA_COUNTS = deepFreeze([
|
|
177
|
+
{ modality: 'image', maxPerRequest: 1500 },
|
|
178
|
+
]);
|
|
179
|
+
function buildOpenAIRow(model, freshness, endpointAmbiguous) {
|
|
180
|
+
const limits = requireLimits(model);
|
|
181
|
+
const pricingRow = backendPricing(Object.hasOwn(openAIPricingTable, model) ? openAIPricingTable[model] : undefined);
|
|
182
|
+
return {
|
|
183
|
+
provider: 'openai',
|
|
184
|
+
endpoint: 'chat.completions',
|
|
185
|
+
model,
|
|
186
|
+
aliases: aliasesFor(model, OPENAI_MODEL_ALIASES),
|
|
187
|
+
lifecycle: 'stable',
|
|
188
|
+
modalities: requireModalities(model),
|
|
189
|
+
mimeFamilies: ['text', 'image', 'document'],
|
|
190
|
+
mediaLimits: [],
|
|
191
|
+
mediaCounts: OPENAI_MEDIA_COUNTS,
|
|
192
|
+
providerFetchesRemoteUrls: true,
|
|
193
|
+
contextWindowTokens: limits.contextWindowTokens,
|
|
194
|
+
maxOutputTokens: limits.maxOutputTokens,
|
|
195
|
+
streaming: true,
|
|
196
|
+
tools: true,
|
|
197
|
+
parallelTools: true,
|
|
198
|
+
structuredOutput: true,
|
|
199
|
+
parameterCompatibility: FULL_PARAMETER_COMPATIBILITY,
|
|
200
|
+
// OpenAI's chat.completions endpoint never supports request-controlled
|
|
201
|
+
// caching or server-side token counting, ambiguous or not — only
|
|
202
|
+
// batchInference depends on the effective endpoint. The effective
|
|
203
|
+
// endpoint, not the options object: an ambiguous baseURL means operative
|
|
204
|
+
// cannot tell whether the request reaches api.openai.com, a
|
|
205
|
+
// credential-injecting proxy, or an OpenAI-compatible local server — see
|
|
206
|
+
// capabilities.ts's historical rationale, now sourced from here.
|
|
207
|
+
caching: false,
|
|
208
|
+
batchInference: !endpointAmbiguous,
|
|
209
|
+
explicitThinkingRequest: false,
|
|
210
|
+
serverSideTokenCounting: false,
|
|
211
|
+
effort: openAIEffort(model),
|
|
212
|
+
endpointAmbiguous,
|
|
213
|
+
...(pricingRow !== undefined ? { pricing: pricingRow } : {}),
|
|
214
|
+
availability: endpointAmbiguous ? 'unknown' : 'available',
|
|
215
|
+
health: 'unknown',
|
|
216
|
+
source: 'static',
|
|
217
|
+
freshness,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function openAIEffort(model) {
|
|
221
|
+
const degradesTo = degradationOf((tier) => resolveOpenAIEffort(tier, model));
|
|
222
|
+
return {
|
|
223
|
+
portable: portableTiers(degradesTo),
|
|
224
|
+
nativeMapping: OPENAI_REASONING_MODELS.has(model) ? 'native' : 'unsupported',
|
|
225
|
+
degradesTo,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The catalog rows of the OpenAI models, one per model, frozen. The OpenAI plugin passes them as
|
|
230
|
+
* its provider's `rows`.
|
|
231
|
+
*/
|
|
232
|
+
export function openAIRows(options) {
|
|
233
|
+
const freshness = options?.freshness ?? new Date().toISOString();
|
|
234
|
+
const endpointAmbiguous = Boolean(options?.baseURL || readEnvironmentConfiguration().openaiBaseUrl);
|
|
235
|
+
return Object.freeze(Object.keys(OPENAI_LIMITS).map((model) => deepFreeze(buildOpenAIRow(model, freshness, endpointAmbiguous))));
|
|
236
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ProviderConfigurationBase, ProviderDefinition } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
import type { OpenAIClient, OpenAIProviderOptions, OpenAIStreamingClient } from "./openai-types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The configuration {@link openaiProvider} accepts: the shared base plus every option
|
|
5
|
+
* `createOpenAIProvider` takes.
|
|
6
|
+
*
|
|
7
|
+
* An injected `client` has to serve both calls, because one configuration feeds both
|
|
8
|
+
* {@link ProviderDefinition.generate} and {@link ProviderDefinition.stream}; a real `OpenAI`
|
|
9
|
+
* client does. To inject a client that serves only one, call the factory directly.
|
|
10
|
+
*/
|
|
11
|
+
export type OpenAIProviderConfiguration = ProviderConfigurationBase & Omit<OpenAIProviderOptions, 'client'> & {
|
|
12
|
+
client?: (OpenAIClient & OpenAIStreamingClient) | undefined;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* The OpenAI model provider, ready to register with a host.
|
|
16
|
+
*
|
|
17
|
+
* Each method hands the configuration object, whole, to `createOpenAIProvider` or
|
|
18
|
+
* `createOpenAIProviderStream`.
|
|
19
|
+
*/
|
|
20
|
+
export type OpenAIPluginConfiguration = {
|
|
21
|
+
readonly baseURL?: string | undefined;
|
|
22
|
+
};
|
|
23
|
+
/** The OpenAI provider definition, including optional plugin-level endpoint configuration. */
|
|
24
|
+
export declare const openaiProvider: ProviderDefinition<'openai', OpenAIProviderConfiguration, OpenAIPluginConfiguration>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createOpenAIProvider, createOpenAIProviderStream } from "./openai.js";
|
|
2
|
+
/** The OpenAI provider definition, including optional plugin-level endpoint configuration. */
|
|
3
|
+
export const openaiProvider = {
|
|
4
|
+
name: 'openai',
|
|
5
|
+
generate: (configuration, pluginConfiguration) => createOpenAIProvider({
|
|
6
|
+
...configuration,
|
|
7
|
+
baseURL: pluginConfiguration?.baseURL ?? configuration.baseURL,
|
|
8
|
+
}),
|
|
9
|
+
stream: (configuration, pluginConfiguration) => createOpenAIProviderStream({
|
|
10
|
+
...configuration,
|
|
11
|
+
baseURL: pluginConfiguration?.baseURL ?? configuration.baseURL,
|
|
12
|
+
}),
|
|
13
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ProviderContractError, type GenerateResponse } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
/** The Chat Completions finish reason for a response cut off at the output-token limit. */
|
|
3
|
+
export declare const OUTPUT_LIMIT_FINISH_REASON = "length";
|
|
4
|
+
/**
|
|
5
|
+
* Thrown when a Chat Completions response stopped at the output-token limit
|
|
6
|
+
* (`finish_reason: "length"`), whole or streamed. The response is discarded: its text is cut short
|
|
7
|
+
* and any tool call in it may carry cut-off arguments, so nothing in it is returned or executed. A
|
|
8
|
+
* run over this provider ends with `finishReason: 'error'` and this error.
|
|
9
|
+
*
|
|
10
|
+
* It is a {@link ProviderContractError} with the `truncated-stream` reason and keeps that class's
|
|
11
|
+
* `name`, so Operative's loop treats it as one wherever it checks, across package copies included:
|
|
12
|
+
* it is never retried, because the same request would stop at the same limit, and `usage`, the
|
|
13
|
+
* billed usage of the discarded response, still counts toward the run.
|
|
14
|
+
*/
|
|
15
|
+
export declare class OpenAIOutputLimitError extends ProviderContractError {
|
|
16
|
+
/** The Chat Completions finish reason. */
|
|
17
|
+
readonly finishReason = "length";
|
|
18
|
+
/** The completion identifier of the discarded response, when reported. */
|
|
19
|
+
readonly responseId: string | undefined;
|
|
20
|
+
constructor(options: {
|
|
21
|
+
usage: GenerateResponse['usage'];
|
|
22
|
+
responseId?: string | undefined;
|
|
23
|
+
toolCallCount: number;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** Structural guard for {@link OpenAIOutputLimitError}, for a copy loaded from another package instance. */
|
|
27
|
+
export declare function isOpenAIOutputLimitError(error: unknown): error is OpenAIOutputLimitError;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { isProviderContractError, ProviderContractError, } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
const PROVIDER = 'openai';
|
|
3
|
+
/** The Chat Completions finish reason for a response cut off at the output-token limit. */
|
|
4
|
+
export const OUTPUT_LIMIT_FINISH_REASON = 'length';
|
|
5
|
+
/**
|
|
6
|
+
* Thrown when a Chat Completions response stopped at the output-token limit
|
|
7
|
+
* (`finish_reason: "length"`), whole or streamed. The response is discarded: its text is cut short
|
|
8
|
+
* and any tool call in it may carry cut-off arguments, so nothing in it is returned or executed. A
|
|
9
|
+
* run over this provider ends with `finishReason: 'error'` and this error.
|
|
10
|
+
*
|
|
11
|
+
* It is a {@link ProviderContractError} with the `truncated-stream` reason and keeps that class's
|
|
12
|
+
* `name`, so Operative's loop treats it as one wherever it checks, across package copies included:
|
|
13
|
+
* it is never retried, because the same request would stop at the same limit, and `usage`, the
|
|
14
|
+
* billed usage of the discarded response, still counts toward the run.
|
|
15
|
+
*/
|
|
16
|
+
export class OpenAIOutputLimitError extends ProviderContractError {
|
|
17
|
+
/** The Chat Completions finish reason. */
|
|
18
|
+
finishReason = OUTPUT_LIMIT_FINISH_REASON;
|
|
19
|
+
/** The completion identifier of the discarded response, when reported. */
|
|
20
|
+
responseId;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
super({
|
|
23
|
+
provider: PROVIDER,
|
|
24
|
+
reason: 'truncated-stream',
|
|
25
|
+
blockType: options.toolCallCount > 0 ? 'tool_call' : 'text',
|
|
26
|
+
partIndex: 0,
|
|
27
|
+
usage: options.usage,
|
|
28
|
+
});
|
|
29
|
+
const discarded = options.toolCallCount > 0
|
|
30
|
+
? `its text and ${options.toolCallCount} tool call(s) were discarded unexecuted`
|
|
31
|
+
: 'its text was discarded';
|
|
32
|
+
this.message = `[provider:${PROVIDER}] the response stopped at the output-token limit; ${discarded}.`;
|
|
33
|
+
this.responseId = options.responseId;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Structural guard for {@link OpenAIOutputLimitError}, for a copy loaded from another package instance. */
|
|
37
|
+
export function isOpenAIOutputLimitError(error) {
|
|
38
|
+
if (error instanceof OpenAIOutputLimitError)
|
|
39
|
+
return true;
|
|
40
|
+
return (isProviderContractError(error) &&
|
|
41
|
+
error.provider === PROVIDER &&
|
|
42
|
+
error['finishReason'] === OUTPUT_LIMIT_FINISH_REASON);
|
|
43
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { JSONValue, MultiModalContent } from 'conversationalist';
|
|
2
|
+
import type { GenerateResponse } from '@lostgradient/operative/provider-kit';
|
|
3
|
+
/** What {@link mapOpenAIMessage} returns for one assistant message: the ordered parts and the metadata that did not fit a part. */
|
|
4
|
+
export interface OpenAIMessageMapping {
|
|
5
|
+
/** The message's content as ordered parts: one text part, or none when the content is empty or `null`. */
|
|
6
|
+
readonly parts: MultiModalContent[];
|
|
7
|
+
/** The refusal, annotations and unmodeled fields the message carried; `undefined` when none. */
|
|
8
|
+
readonly metadata: Record<string, JSONValue> | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Maps one OpenAI assistant message (a whole completion's, or a stream's accumulation of deltas) to
|
|
12
|
+
* ordered parts and metadata. Every field lands somewhere or fails loudly:
|
|
13
|
+
*
|
|
14
|
+
* - `content` becomes one text part (none when empty or `null`); tool calls are the caller's.
|
|
15
|
+
* - `refusal` and `annotations` are model output that used to vanish; they go to `metadata`.
|
|
16
|
+
* Annotations are not text-part `citations`: that field is Anthropic's replay format, and it
|
|
17
|
+
* would be replayed to Anthropic on a fallover.
|
|
18
|
+
* - `audio` and `function_call` throw a {@link ProviderContractError}: audio output is unadvertised
|
|
19
|
+
* and the factory never asks for it, and the deprecated function call has no mapping.
|
|
20
|
+
* - A field the SDK does not declare (`reasoning_content` on DeepSeek, Groq, LM Studio, and others
|
|
21
|
+
* `baseURL` documents) is kept in `metadata.providerExtensions` when it is JSON-safe.
|
|
22
|
+
*/
|
|
23
|
+
export declare function mapOpenAIMessage(message: Record<string, unknown>, usage: GenerateResponse['usage']): OpenAIMessageMapping;
|
|
24
|
+
/**
|
|
25
|
+
* Folds one streamed delta field into the assembled message: strings concatenate across deltas,
|
|
26
|
+
* anything else keeps its latest value. A provider chooses the field name, so it is stored as an
|
|
27
|
+
* own entry even when it is `__proto__`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function mergeAssembledField(assembled: Record<string, unknown>, field: string, value: unknown): void;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { defineOwn, ProviderContractError } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
/** Message fields the OpenAI Chat Completions mapping table lists. Anything else is an extension. */
|
|
3
|
+
const KNOWN_MESSAGE_FIELDS = new Set([
|
|
4
|
+
'content',
|
|
5
|
+
'role',
|
|
6
|
+
'tool_calls',
|
|
7
|
+
'refusal',
|
|
8
|
+
'annotations',
|
|
9
|
+
'audio',
|
|
10
|
+
'function_call',
|
|
11
|
+
]);
|
|
12
|
+
/** Fields whose presence is output the adapter cannot map; the request never asks for either. */
|
|
13
|
+
const UNMAPPED_MESSAGE_FIELDS = ['audio', 'function_call'];
|
|
14
|
+
function jsonSafe(value) {
|
|
15
|
+
try {
|
|
16
|
+
const serialized = JSON.stringify(value);
|
|
17
|
+
return serialized === undefined ? undefined : JSON.parse(serialized);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Maps one OpenAI assistant message (a whole completion's, or a stream's accumulation of deltas) to
|
|
25
|
+
* ordered parts and metadata. Every field lands somewhere or fails loudly:
|
|
26
|
+
*
|
|
27
|
+
* - `content` becomes one text part (none when empty or `null`); tool calls are the caller's.
|
|
28
|
+
* - `refusal` and `annotations` are model output that used to vanish; they go to `metadata`.
|
|
29
|
+
* Annotations are not text-part `citations`: that field is Anthropic's replay format, and it
|
|
30
|
+
* would be replayed to Anthropic on a fallover.
|
|
31
|
+
* - `audio` and `function_call` throw a {@link ProviderContractError}: audio output is unadvertised
|
|
32
|
+
* and the factory never asks for it, and the deprecated function call has no mapping.
|
|
33
|
+
* - A field the SDK does not declare (`reasoning_content` on DeepSeek, Groq, LM Studio, and others
|
|
34
|
+
* `baseURL` documents) is kept in `metadata.providerExtensions` when it is JSON-safe.
|
|
35
|
+
*/
|
|
36
|
+
export function mapOpenAIMessage(message, usage) {
|
|
37
|
+
for (const field of UNMAPPED_MESSAGE_FIELDS) {
|
|
38
|
+
const value = message[field];
|
|
39
|
+
if (value !== undefined && value !== null) {
|
|
40
|
+
throw new ProviderContractError({
|
|
41
|
+
provider: 'openai',
|
|
42
|
+
reason: 'unlisted-block',
|
|
43
|
+
blockType: field,
|
|
44
|
+
partIndex: 0,
|
|
45
|
+
usage,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const parts = [];
|
|
50
|
+
const content = message['content'];
|
|
51
|
+
if (typeof content === 'string' && content !== '')
|
|
52
|
+
parts.push({ type: 'text', text: content });
|
|
53
|
+
const metadata = {};
|
|
54
|
+
const refusal = message['refusal'];
|
|
55
|
+
if (typeof refusal === 'string' && refusal !== '')
|
|
56
|
+
metadata['refusal'] = refusal;
|
|
57
|
+
const annotations = message['annotations'];
|
|
58
|
+
if (annotations !== undefined && annotations !== null) {
|
|
59
|
+
const safe = jsonSafe(annotations);
|
|
60
|
+
if (safe !== undefined)
|
|
61
|
+
metadata['annotations'] = safe;
|
|
62
|
+
}
|
|
63
|
+
const extensions = {};
|
|
64
|
+
for (const [field, value] of Object.entries(message)) {
|
|
65
|
+
if (KNOWN_MESSAGE_FIELDS.has(field) || value === undefined || value === null)
|
|
66
|
+
continue;
|
|
67
|
+
const safe = jsonSafe(value);
|
|
68
|
+
if (safe !== undefined)
|
|
69
|
+
extensions[field] = safe;
|
|
70
|
+
}
|
|
71
|
+
if (Object.keys(extensions).length > 0)
|
|
72
|
+
metadata['providerExtensions'] = extensions;
|
|
73
|
+
return { parts, metadata: Object.keys(metadata).length > 0 ? metadata : undefined };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Folds one streamed delta field into the assembled message: strings concatenate across deltas,
|
|
77
|
+
* anything else keeps its latest value. A provider chooses the field name, so it is stored as an
|
|
78
|
+
* own entry even when it is `__proto__`.
|
|
79
|
+
*/
|
|
80
|
+
export function mergeAssembledField(assembled, field, value) {
|
|
81
|
+
const previous = Object.hasOwn(assembled, field) ? assembled[field] : undefined;
|
|
82
|
+
defineOwn(assembled, field, typeof value === 'string' && typeof previous === 'string' ? previous + value : value);
|
|
83
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ResponseFormat } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
/**
|
|
3
|
+
* OpenAI response_format parameter shape.
|
|
4
|
+
*/
|
|
5
|
+
type OpenAIResponseFormat = {
|
|
6
|
+
type: 'json_object';
|
|
7
|
+
} | {
|
|
8
|
+
type: 'json_schema';
|
|
9
|
+
json_schema: {
|
|
10
|
+
name: string;
|
|
11
|
+
schema: Record<string, unknown>;
|
|
12
|
+
strict: boolean;
|
|
13
|
+
};
|
|
14
|
+
} | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Converts a ResponseFormat to the OpenAI API's response_format parameter.
|
|
17
|
+
*
|
|
18
|
+
* Returns `undefined` for text format since OpenAI defaults to text.
|
|
19
|
+
*
|
|
20
|
+
* `strict: true` is sent only when the schema passes `isStrictCompatible`;
|
|
21
|
+
* otherwise the `json_schema` shape is kept with `strict: false`. Schemas
|
|
22
|
+
* derived from `z.object()` via `toOutputJsonSchema` lack
|
|
23
|
+
* `additionalProperties: false`, so `strict: false` is their expected steady
|
|
24
|
+
* state, not a silent downgrade.
|
|
25
|
+
*/
|
|
26
|
+
export declare function toOpenAIResponseFormat(format: ResponseFormat): OpenAIResponseFormat;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { isStrictCompatible } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
/**
|
|
3
|
+
* Converts a ResponseFormat to the OpenAI API's response_format parameter.
|
|
4
|
+
*
|
|
5
|
+
* Returns `undefined` for text format since OpenAI defaults to text.
|
|
6
|
+
*
|
|
7
|
+
* `strict: true` is sent only when the schema passes `isStrictCompatible`;
|
|
8
|
+
* otherwise the `json_schema` shape is kept with `strict: false`. Schemas
|
|
9
|
+
* derived from `z.object()` via `toOutputJsonSchema` lack
|
|
10
|
+
* `additionalProperties: false`, so `strict: false` is their expected steady
|
|
11
|
+
* state, not a silent downgrade.
|
|
12
|
+
*/
|
|
13
|
+
export function toOpenAIResponseFormat(format) {
|
|
14
|
+
if (format.type === 'text')
|
|
15
|
+
return undefined;
|
|
16
|
+
if (format.type === 'json')
|
|
17
|
+
return { type: 'json_object' };
|
|
18
|
+
return {
|
|
19
|
+
type: 'json_schema',
|
|
20
|
+
json_schema: {
|
|
21
|
+
name: format.name ?? 'response',
|
|
22
|
+
schema: format.schema,
|
|
23
|
+
strict: isStrictCompatible(format.schema),
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ToolChoice } from '@lostgradient/operative/provider-kit';
|
|
2
|
+
/**
|
|
3
|
+
* OpenAI tool_choice parameter shape.
|
|
4
|
+
*/
|
|
5
|
+
type OpenAIToolChoice = 'auto' | 'required' | 'none' | {
|
|
6
|
+
type: 'function';
|
|
7
|
+
function: {
|
|
8
|
+
name: string;
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Converts a ToolChoice to the OpenAI API's tool_choice format.
|
|
13
|
+
*/
|
|
14
|
+
export declare function toOpenAIToolChoice(choice: ToolChoice): OpenAIToolChoice;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Converts a ToolChoice to the OpenAI API's tool_choice format.
|
|
3
|
+
*/
|
|
4
|
+
export function toOpenAIToolChoice(choice) {
|
|
5
|
+
if (choice === 'auto')
|
|
6
|
+
return 'auto';
|
|
7
|
+
if (choice === 'required')
|
|
8
|
+
return 'required';
|
|
9
|
+
if (choice === 'none')
|
|
10
|
+
return 'none';
|
|
11
|
+
return { type: 'function', function: { name: choice.tool } };
|
|
12
|
+
}
|