@namzu/openai 4.8.2 → 4.9.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/CHANGELOG.md +21 -0
- package/README.md +5 -5
- package/dist/client.d.ts +18 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +105 -33
- package/dist/client.js.map +1 -1
- package/dist/codex.d.ts +27 -5
- package/dist/codex.d.ts.map +1 -1
- package/dist/codex.js +117 -50
- package/dist/codex.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/listed-chat-models.d.ts +26 -0
- package/dist/listed-chat-models.d.ts.map +1 -0
- package/dist/listed-chat-models.js +33 -0
- package/dist/listed-chat-models.js.map +1 -0
- package/package.json +2 -2
- package/src/client.ts +110 -29
- package/src/codex.ts +143 -46
- package/src/index.ts +1 -0
- package/src/listed-chat-models.ts +37 -0
package/src/client.ts
CHANGED
|
@@ -27,7 +27,9 @@ import type {
|
|
|
27
27
|
ChatCompletionTool,
|
|
28
28
|
ChatCompletionToolChoiceOption,
|
|
29
29
|
} from 'openai/resources/chat/completions'
|
|
30
|
+
import { CodexProvider } from './codex.js'
|
|
30
31
|
import { assertFastModeAccepted, isFirstPartyOpenAIEndpoint, servedSpeed } from './fast-mode.js'
|
|
32
|
+
import { chatModelsOnly } from './listed-chat-models.js'
|
|
31
33
|
import { declaredContextWindow, firstCount } from './model-limits.js'
|
|
32
34
|
import type { OpenAIConfig } from './types.js'
|
|
33
35
|
|
|
@@ -111,38 +113,78 @@ export function openAIReasoningEffortLevels(model: string): readonly ReasoningEf
|
|
|
111
113
|
}
|
|
112
114
|
|
|
113
115
|
/**
|
|
114
|
-
* Whether
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* reasoning
|
|
116
|
+
* Whether OpenAI's own endpoint only takes a request for this model through
|
|
117
|
+
* the Responses API. Measured against the live API: every `gpt-5.6-*` and
|
|
118
|
+
* `gpt-6*` id answers a request that carries function tools on Chat
|
|
119
|
+
* Completions with a 400 ("Function tools with reasoning_effort are not
|
|
120
|
+
* supported"), and `*-pro` ids are not served there at all. `gpt-5.4-mini` and
|
|
121
|
+
* `gpt-5.5` refuse the same pair only when a reasoning effort is sent as well.
|
|
120
122
|
*/
|
|
121
|
-
function
|
|
122
|
-
const
|
|
123
|
-
if (
|
|
124
|
-
if (/^
|
|
125
|
-
|
|
123
|
+
export function openAIModelNeedsResponses(model: string, params: ChatCompletionParams): boolean {
|
|
124
|
+
const id = model.toLowerCase().replace(/^ft:/, '')
|
|
125
|
+
if (/^gpt-5\.6(?![a-z0-9.])/.test(id) || /^gpt-6(?![a-z0-9])/.test(id)) return true
|
|
126
|
+
if (/^gpt-live(?![a-z0-9])/.test(id)) return true
|
|
127
|
+
if (/-pro(?:-\d{4}-\d{2}-\d{2})?$/.test(id)) return true
|
|
128
|
+
if (learnedResponsesModels.has(id)) return true
|
|
129
|
+
const hasTools = (params.tools?.length ?? 0) > 0
|
|
130
|
+
if (hasTools && params.effort !== undefined && /^gpt-5\.(?:4-mini|5)(?![a-z0-9.])/.test(id)) {
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Models this process has seen Chat Completions refuse because they need
|
|
138
|
+
* Responses (the tools-with-reasoning 400, or a 404 naming Responses). They go straight to Responses afterwards.
|
|
139
|
+
*/
|
|
140
|
+
const learnedResponsesModels = new Set<string>()
|
|
141
|
+
|
|
142
|
+
/** Test hook: forget what this process learned about which models need Responses. */
|
|
143
|
+
export function resetLearnedResponsesModels(): void {
|
|
144
|
+
learnedResponsesModels.clear()
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isResponsesOnlyRefusal(error: unknown): boolean {
|
|
148
|
+
const e = error as { status?: unknown; message?: unknown } | null
|
|
149
|
+
if (typeof e?.message !== 'string') return false
|
|
150
|
+
if (e.status === 400)
|
|
151
|
+
return /Function tools with reasoning_effort are not supported/i.test(e.message)
|
|
152
|
+
// Chat Completions answers a Responses-only model with a 404 in one of
|
|
153
|
+
// three wordings.
|
|
154
|
+
return (
|
|
155
|
+
e.status === 404 &&
|
|
156
|
+
/not a chat model|only supported in v1\/responses|not supported in the v1\/chat\/completions endpoint|use the v1\/responses endpoint/i.test(
|
|
157
|
+
e.message,
|
|
158
|
+
)
|
|
159
|
+
)
|
|
126
160
|
}
|
|
127
161
|
|
|
128
|
-
/**
|
|
129
|
-
function
|
|
130
|
-
return /^
|
|
162
|
+
/** The classic families: they take the sampling fields always and refuse `reasoning_effort`. */
|
|
163
|
+
function isClassicChatModel(model: string): boolean {
|
|
164
|
+
return /^(?:ft:)?(?:gpt-3\.5|gpt-4|chatgpt-4)/.test(model.toLowerCase())
|
|
131
165
|
}
|
|
132
166
|
|
|
133
167
|
/**
|
|
134
|
-
*
|
|
135
|
-
*
|
|
168
|
+
* Whether Chat Completions takes a caller-set sampling field for this model
|
|
169
|
+
* with this effort. Measured against the live API: `gpt-3.5`, `gpt-4*` and
|
|
170
|
+
* `chatgpt-4*` always do; `gpt-5.1` to `gpt-5.4` (including `-mini` and
|
|
171
|
+
* `-nano`) do only while reasoning is off, which is their default; `gpt-5`,
|
|
172
|
+
* `gpt-5.5`, `gpt-5.6*`, `gpt-6*` and the o-series never do.
|
|
136
173
|
*/
|
|
137
|
-
function
|
|
138
|
-
if (
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
174
|
+
function takesSamplingFields(model: string, effort: ChatCompletionParams['effort']): boolean {
|
|
175
|
+
if (isClassicChatModel(model)) return true
|
|
176
|
+
const id = model.toLowerCase()
|
|
177
|
+
return (
|
|
178
|
+
/^(?:ft:)?gpt-5\.[1-4](?![a-z0-9.])(?!-(?:codex|pro|chat))/.test(id) &&
|
|
179
|
+
(effort === undefined || effort === 'none')
|
|
143
180
|
)
|
|
144
181
|
}
|
|
145
182
|
|
|
183
|
+
/** Models that refuse `reasoning_effort` outright. */
|
|
184
|
+
function refusesReasoningEffort(model: string): boolean {
|
|
185
|
+
return isClassicChatModel(model)
|
|
186
|
+
}
|
|
187
|
+
|
|
146
188
|
/** Whether a base URL names a host other than OpenAI's own API. */
|
|
147
189
|
function isCompatibleHost(baseURL: string | undefined): boolean {
|
|
148
190
|
return !isFirstPartyOpenAIEndpoint(baseURL)
|
|
@@ -346,6 +388,7 @@ function parseUsage(
|
|
|
346
388
|
totalTokens: raw.total_tokens ?? promptTokens + completionTokens,
|
|
347
389
|
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? 0,
|
|
348
390
|
cacheWriteTokens: 0,
|
|
391
|
+
billingRoute: 'api',
|
|
349
392
|
...servedSpeed(servedTier, requestedSpeed),
|
|
350
393
|
}
|
|
351
394
|
}
|
|
@@ -538,6 +581,8 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
538
581
|
private thinkingOffFields: OpenAIConfig['thinkingOffFields']
|
|
539
582
|
/** The base URL requests go to, kept to name the host when fast mode is refused there. */
|
|
540
583
|
private readonly effectiveBaseURL: string | undefined
|
|
584
|
+
private readonly config: OpenAIConfig
|
|
585
|
+
private responses?: CodexProvider
|
|
541
586
|
|
|
542
587
|
constructor(config: OpenAIConfig) {
|
|
543
588
|
if (!config.apiKey) {
|
|
@@ -561,6 +606,7 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
561
606
|
}
|
|
562
607
|
|
|
563
608
|
this.client = new OpenAI(clientOptions)
|
|
609
|
+
this.config = config
|
|
564
610
|
this.defaultModel = config.model
|
|
565
611
|
this.thinkingOffFields = config.thinkingOffFields
|
|
566
612
|
// The client reads the standard base-URL variable when none is given, so that is where requests go.
|
|
@@ -607,6 +653,25 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
607
653
|
return this.declaredWindows.get(model)
|
|
608
654
|
}
|
|
609
655
|
|
|
656
|
+
/**
|
|
657
|
+
* The Responses transport for this key, built on the subscription driver's
|
|
658
|
+
* request and stream handling. Only used on OpenAI's own endpoint.
|
|
659
|
+
*/
|
|
660
|
+
private responsesRoute(): CodexProvider {
|
|
661
|
+
this.responses ??= new CodexProvider({
|
|
662
|
+
responsesApi: true,
|
|
663
|
+
apiKey: this.config.apiKey,
|
|
664
|
+
model: this.defaultModel,
|
|
665
|
+
...(this.effectiveBaseURL ? { baseURL: this.effectiveBaseURL } : {}),
|
|
666
|
+
organization: this.config.organization,
|
|
667
|
+
project: this.config.project,
|
|
668
|
+
timeout: this.config.timeout,
|
|
669
|
+
maxRetries: this.config.maxRetries,
|
|
670
|
+
defaultHeaders: { ...attributionHeaders(), ...(this.config.defaultHeaders ?? {}) },
|
|
671
|
+
})
|
|
672
|
+
return this.responses
|
|
673
|
+
}
|
|
674
|
+
|
|
610
675
|
private resolveModel(params: ChatCompletionParams): string {
|
|
611
676
|
const model = params.model || this.defaultModel
|
|
612
677
|
if (!model) {
|
|
@@ -627,10 +692,16 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
627
692
|
assertOpenAIReasoningEffort(model, params.effort)
|
|
628
693
|
// The model's own rules apply on OpenAI's own host only; a compatible
|
|
629
694
|
// endpoint reached through a custom base URL keeps the classic fields.
|
|
630
|
-
const
|
|
631
|
-
if (
|
|
632
|
-
|
|
633
|
-
|
|
695
|
+
const firstParty = !this.compatibleHost
|
|
696
|
+
if (firstParty && openAIModelNeedsResponses(model, params)) {
|
|
697
|
+
yield* this.responsesRoute().chatStream({ ...params, model })
|
|
698
|
+
return
|
|
699
|
+
}
|
|
700
|
+
// First-party Chat Completions always takes `max_completion_tokens`; the
|
|
701
|
+
// sampling fields go only where the model accepts them, and only when the
|
|
702
|
+
// caller set them; elsewhere they are dropped with no error.
|
|
703
|
+
const dropsSampling = firstParty && !takesSamplingFields(model, params.effort)
|
|
704
|
+
const effort = firstParty && refusesReasoningEffort(model) ? undefined : params.effort
|
|
634
705
|
|
|
635
706
|
// A call that asked for no effort (or for thinking to be off) means no
|
|
636
707
|
// reasoning at all. `reasoning_effort` alone is ignored by some compatible
|
|
@@ -679,7 +750,7 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
679
750
|
frequency_penalty: params.frequencyPenalty,
|
|
680
751
|
presence_penalty: params.presencePenalty,
|
|
681
752
|
}),
|
|
682
|
-
...(
|
|
753
|
+
...(firstParty
|
|
683
754
|
? { max_completion_tokens: params.maxTokens }
|
|
684
755
|
: { max_tokens: params.maxTokens }),
|
|
685
756
|
stop: params.stop,
|
|
@@ -687,7 +758,7 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
687
758
|
...(serviceTier ? { service_tier: serviceTier } : {}),
|
|
688
759
|
...(offFields ?? {}),
|
|
689
760
|
},
|
|
690
|
-
|
|
761
|
+
effort,
|
|
691
762
|
),
|
|
692
763
|
// Per-request abort: a Stop tears the in-flight SSE request down.
|
|
693
764
|
{ signal: params.signal },
|
|
@@ -700,6 +771,14 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
700
771
|
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
701
772
|
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
702
773
|
if (isProviderRequestError(err)) throw err
|
|
774
|
+
// The model answered before any output that its tools cannot go with
|
|
775
|
+
// reasoning on this endpoint: remember that for the process and send the
|
|
776
|
+
// request once through Responses, which takes the pair.
|
|
777
|
+
if (firstParty && isResponsesOnlyRefusal(err)) {
|
|
778
|
+
learnedResponsesModels.add(model.toLowerCase().replace(/^ft:/, ''))
|
|
779
|
+
yield* this.responsesRoute().chatStream({ ...params, model })
|
|
780
|
+
return
|
|
781
|
+
}
|
|
703
782
|
throw providerVendorError({ providerId: 'openai', error: err })
|
|
704
783
|
}
|
|
705
784
|
|
|
@@ -817,7 +896,9 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
817
896
|
signal?.throwIfAborted()
|
|
818
897
|
const page = await this.client.models.list(signal ? { signal } : undefined)
|
|
819
898
|
signal?.throwIfAborted()
|
|
820
|
-
|
|
899
|
+
// OpenAI's own listing mixes in speech, image and embedding models; a compatible host's does not.
|
|
900
|
+
const rows = this.compatibleHost ? page.data : chatModelsOnly(page.data)
|
|
901
|
+
return rows.map((m) => ({
|
|
821
902
|
id: m.id,
|
|
822
903
|
name: m.id,
|
|
823
904
|
supportsToolUse: true,
|
package/src/codex.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type {
|
|
|
7
7
|
ProviderCapabilities,
|
|
8
8
|
ProviderRoute,
|
|
9
9
|
ReasoningEffort,
|
|
10
|
+
RequestWireShape,
|
|
10
11
|
StreamChunk,
|
|
11
12
|
TokenUsage,
|
|
12
13
|
} from '@namzu/sdk'
|
|
@@ -264,6 +265,8 @@ export function toCodexInput(
|
|
|
264
265
|
messages: ChatCompletionParams['messages'],
|
|
265
266
|
targetRoute: ProviderRoute,
|
|
266
267
|
openingSystemRun = messages.findIndex((message) => message.role !== 'system'),
|
|
268
|
+
/** The role a system message after the opening run is sent as. */
|
|
269
|
+
laterSystemRole: 'developer' | 'user' = 'developer',
|
|
267
270
|
): ResponseInputItem[] {
|
|
268
271
|
const input: ResponseInputItem[] = []
|
|
269
272
|
const opening = openingSystemRun < 0 ? messages.length : openingSystemRun
|
|
@@ -271,7 +274,7 @@ export function toCodexInput(
|
|
|
271
274
|
if (message.role === 'system') {
|
|
272
275
|
// The opening run is `instructions`; a later one keeps its place.
|
|
273
276
|
if (at >= opening && message.content) {
|
|
274
|
-
input.push({ type: 'message', role:
|
|
277
|
+
input.push({ type: 'message', role: laterSystemRole, content: message.content })
|
|
275
278
|
}
|
|
276
279
|
continue
|
|
277
280
|
}
|
|
@@ -315,7 +318,7 @@ export function toCodexInput(
|
|
|
315
318
|
return input
|
|
316
319
|
}
|
|
317
320
|
|
|
318
|
-
export function toCodexTools(params: ChatCompletionParams): Tool[] | undefined {
|
|
321
|
+
export function toCodexTools(params: ChatCompletionParams, apiKey = false): Tool[] | undefined {
|
|
319
322
|
const tools: Tool[] = (params.tools ?? []).map((tool) => ({
|
|
320
323
|
type: 'function',
|
|
321
324
|
name: tool.function.name,
|
|
@@ -338,9 +341,10 @@ export function toCodexTools(params: ChatCompletionParams): Tool[] | undefined {
|
|
|
338
341
|
if (params.webSearch.mode !== 'live' && params.webSearch.mode !== 'cached')
|
|
339
342
|
throw new Error('Invalid web search mode.')
|
|
340
343
|
// The subscription wire supports this field; the installed API SDK's Tool type predates it.
|
|
341
|
-
const hosted: Tool & { external_web_access
|
|
344
|
+
const hosted: Tool & { external_web_access?: boolean } = {
|
|
342
345
|
type: 'web_search',
|
|
343
|
-
|
|
346
|
+
// The public API takes the plain tool; the access switch is a subscription-wire field.
|
|
347
|
+
...(apiKey ? {} : { external_web_access: params.webSearch.mode === 'live' }),
|
|
344
348
|
}
|
|
345
349
|
tools.push(hosted)
|
|
346
350
|
}
|
|
@@ -356,6 +360,8 @@ function responseUsage(
|
|
|
356
360
|
},
|
|
357
361
|
servedTier?: unknown,
|
|
358
362
|
requestedSpeed?: InferenceSpeed,
|
|
363
|
+
requestShape?: RequestWireShape,
|
|
364
|
+
apiKey = false,
|
|
359
365
|
): TokenUsage {
|
|
360
366
|
const promptTokens = usage.input_tokens ?? 0
|
|
361
367
|
const completionTokens = usage.output_tokens ?? 0
|
|
@@ -365,7 +371,9 @@ function responseUsage(
|
|
|
365
371
|
totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
|
|
366
372
|
cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
|
|
367
373
|
cacheWriteTokens: 0,
|
|
374
|
+
billingRoute: apiKey ? 'api' : 'subscription',
|
|
368
375
|
...servedSpeed(servedTier, requestedSpeed),
|
|
376
|
+
...(requestShape ? { requestShape } : {}),
|
|
369
377
|
}
|
|
370
378
|
}
|
|
371
379
|
|
|
@@ -397,6 +405,7 @@ function buildRequest(
|
|
|
397
405
|
targetRoute: ProviderRoute,
|
|
398
406
|
supportedEffort: readonly ReasoningEffort[] | undefined,
|
|
399
407
|
downgrade: SubscriptionDowngrade = NO_DOWNGRADE,
|
|
408
|
+
apiKey = false,
|
|
400
409
|
): ResponseCreateParamsStreaming {
|
|
401
410
|
if (
|
|
402
411
|
params.effort !== undefined &&
|
|
@@ -425,14 +434,13 @@ function buildRequest(
|
|
|
425
434
|
// where they were, as developer messages in the input.
|
|
426
435
|
let openingRun = 0
|
|
427
436
|
while (params.messages[openingRun]?.role === 'system') openingRun++
|
|
428
|
-
//
|
|
429
|
-
//
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
)
|
|
437
|
+
// What the backend refused of the newer shape changes only the field it
|
|
438
|
+
// named; it never moves text into `instructions`. A changing preamble
|
|
439
|
+
// joined into `instructions` sits in front of the whole input, so the
|
|
440
|
+
// next request shared nothing with it past the tools. A refused
|
|
441
|
+
// `developer` item is sent as a `user` item in the same place instead.
|
|
442
|
+
const instructions = params.messages
|
|
443
|
+
.slice(0, openingRun)
|
|
436
444
|
.map((message) => message.content)
|
|
437
445
|
.join('\n\n')
|
|
438
446
|
const request = {
|
|
@@ -440,10 +448,18 @@ function buildRequest(
|
|
|
440
448
|
stream: true,
|
|
441
449
|
store: false,
|
|
442
450
|
instructions: instructions || undefined,
|
|
443
|
-
input: toCodexInput(
|
|
451
|
+
input: toCodexInput(
|
|
452
|
+
params.messages,
|
|
453
|
+
targetRoute,
|
|
454
|
+
openingRun,
|
|
455
|
+
downgrade.noDeveloper ? 'user' : 'developer',
|
|
456
|
+
),
|
|
444
457
|
// One key for the whole conversation routes every request to the same
|
|
445
458
|
// cache; without it the backend keys on the request alone.
|
|
446
459
|
...(params.cacheKey && !downgrade.noCacheKey ? { prompt_cache_key: params.cacheKey } : {}),
|
|
460
|
+
// An API key reaches the public Responses endpoint, which has the member and
|
|
461
|
+
// is told the budget the caller set.
|
|
462
|
+
...(apiKey && params.maxTokens !== undefined ? { max_output_tokens: params.maxTokens } : {}),
|
|
447
463
|
// The Codex subscription request schema deliberately has no
|
|
448
464
|
// `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
|
|
449
465
|
// API control, but projecting it onto this route makes the whole request
|
|
@@ -452,7 +468,7 @@ function buildRequest(
|
|
|
452
468
|
// turn that exposes no tools. The ordinary public Responses endpoint admits
|
|
453
469
|
// their omission, which is why the generated client types all make them
|
|
454
470
|
// optional; the Codex wire does not have the same defaulting contract.
|
|
455
|
-
tools: toCodexTools(params) ?? [],
|
|
471
|
+
tools: toCodexTools(params, apiKey) ?? [],
|
|
456
472
|
tool_choice: (params.toolChoice ?? 'auto') as ResponseCreateParamsStreaming['tool_choice'],
|
|
457
473
|
parallel_tool_calls: params.parallelToolCalls ?? true,
|
|
458
474
|
include: ['reasoning.encrypted_content'],
|
|
@@ -481,38 +497,49 @@ function buildRequest(
|
|
|
481
497
|
/**
|
|
482
498
|
* What the subscription backend has refused of the newer request shape: the
|
|
483
499
|
* `developer` input item, the `session_id` header, the `prompt_cache_key` body
|
|
484
|
-
* field.
|
|
485
|
-
* refusal triggers; later requests go
|
|
500
|
+
* field. Each is recorded only when the refusal named it, for the life of the
|
|
501
|
+
* process, by the one resend that the refusal triggers; later requests go
|
|
502
|
+
* straight to the older shape. A refusal that names none of them is not one.
|
|
486
503
|
*/
|
|
487
504
|
interface SubscriptionDowngrade {
|
|
488
|
-
/**
|
|
489
|
-
|
|
490
|
-
/** The
|
|
505
|
+
/** Later system messages go as `user` items, in the same place. */
|
|
506
|
+
noDeveloper: boolean
|
|
507
|
+
/** The `session_id` header is left off. */
|
|
508
|
+
noSessionHeader: boolean
|
|
509
|
+
/** The `prompt_cache_key` body field is left off. */
|
|
491
510
|
noCacheKey: boolean
|
|
492
511
|
}
|
|
493
512
|
|
|
494
|
-
const NO_DOWNGRADE: SubscriptionDowngrade = {
|
|
495
|
-
|
|
513
|
+
const NO_DOWNGRADE: SubscriptionDowngrade = {
|
|
514
|
+
noDeveloper: false,
|
|
515
|
+
noSessionHeader: false,
|
|
516
|
+
noCacheKey: false,
|
|
517
|
+
}
|
|
518
|
+
const subscriptionDowngrade: SubscriptionDowngrade = { ...NO_DOWNGRADE }
|
|
496
519
|
|
|
497
520
|
/** Test seam: forget a downgrade recorded earlier in this process. */
|
|
498
521
|
export function resetSubscriptionDowngrade(): void {
|
|
499
|
-
subscriptionDowngrade
|
|
500
|
-
subscriptionDowngrade.noCacheKey = false
|
|
522
|
+
Object.assign(subscriptionDowngrade, NO_DOWNGRADE)
|
|
501
523
|
}
|
|
502
524
|
|
|
503
|
-
const REFUSED_SHAPE = /\bdeveloper\b|\brole\b|\binput\[\d*\]|session_id|prompt_cache_key/i
|
|
504
|
-
|
|
505
525
|
/**
|
|
506
|
-
* A bad-request answer that names what the newer shape added
|
|
507
|
-
* (a different 400,
|
|
526
|
+
* A bad-request answer that names what the newer shape added, by the name of
|
|
527
|
+
* the field or the role. Anything else (a different 400, a bad image at
|
|
528
|
+
* `input[3].content`, any other status, a network failure) is not one: taking
|
|
529
|
+
* it for one drops the cache key or moves the changing guidance for every
|
|
530
|
+
* later request of the process, and the cache is lost with it.
|
|
508
531
|
*/
|
|
509
|
-
function refusedNewShape(error: unknown):
|
|
532
|
+
function refusedNewShape(error: unknown): Partial<SubscriptionDowngrade> | undefined {
|
|
510
533
|
if (typeof error !== 'object' || error === null) return undefined
|
|
511
534
|
const status = (error as { status?: unknown }).status
|
|
512
535
|
if (!(error instanceof OpenAI.BadRequestError) && status !== 400) return undefined
|
|
513
536
|
const message = (error as { message?: unknown }).message
|
|
514
|
-
if (typeof message !== 'string'
|
|
515
|
-
|
|
537
|
+
if (typeof message !== 'string') return undefined
|
|
538
|
+
const refused: Partial<SubscriptionDowngrade> = {}
|
|
539
|
+
if (/\bdeveloper\b|input\[\d*\]\.role/i.test(message)) refused.noDeveloper = true
|
|
540
|
+
if (/session_id/i.test(message)) refused.noSessionHeader = true
|
|
541
|
+
if (/prompt_cache_key/i.test(message)) refused.noCacheKey = true
|
|
542
|
+
return Object.keys(refused).length > 0 ? refused : undefined
|
|
516
543
|
}
|
|
517
544
|
|
|
518
545
|
/**
|
|
@@ -542,10 +569,30 @@ const WINDOW_LISTING_TIMEOUT_MS = 3_000
|
|
|
542
569
|
/** How long a failed listing is remembered, so a turn does not ask again every time. */
|
|
543
570
|
const WINDOW_LISTING_RETRY_MS = 5 * 60_000
|
|
544
571
|
|
|
572
|
+
/**
|
|
573
|
+
* An API key for OpenAI's own Responses endpoint. The same request building,
|
|
574
|
+
* streaming, tool-call and reasoning-item handling as the subscription
|
|
575
|
+
* transport; only the address, the bearer and the account routing differ.
|
|
576
|
+
*/
|
|
577
|
+
export interface ResponsesApiConfig {
|
|
578
|
+
apiKey: string
|
|
579
|
+
model?: string
|
|
580
|
+
baseURL?: string
|
|
581
|
+
organization?: string
|
|
582
|
+
project?: string
|
|
583
|
+
timeout?: number
|
|
584
|
+
defaultHeaders?: Record<string, string>
|
|
585
|
+
maxRetries?: number
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
export const RESPONSES_API_BASE_URL = 'https://api.openai.com/v1'
|
|
589
|
+
|
|
545
590
|
export class CodexProvider implements LLMProvider {
|
|
546
|
-
readonly id
|
|
547
|
-
readonly name
|
|
591
|
+
readonly id: string
|
|
592
|
+
readonly name: string
|
|
548
593
|
readonly capabilities = CODEX_CAPABILITIES
|
|
594
|
+
/** True when an API key (not a subscription) is the credential. */
|
|
595
|
+
private readonly apiKeyRoute: boolean
|
|
549
596
|
|
|
550
597
|
private client: OpenAI
|
|
551
598
|
private defaultModel?: string
|
|
@@ -561,7 +608,28 @@ export class CodexProvider implements LLMProvider {
|
|
|
561
608
|
private windowListing?: Promise<boolean>
|
|
562
609
|
private readonly listingKey: string
|
|
563
610
|
|
|
564
|
-
constructor(config: CodexConfig) {
|
|
611
|
+
constructor(config: CodexConfig | ({ responsesApi: true } & ResponsesApiConfig)) {
|
|
612
|
+
if ('responsesApi' in config) {
|
|
613
|
+
if (!config.apiKey) throw new Error('OpenAI API key is required.')
|
|
614
|
+
this.id = 'openai'
|
|
615
|
+
this.name = 'OpenAI'
|
|
616
|
+
this.apiKeyRoute = true
|
|
617
|
+
this.client = new OpenAI({
|
|
618
|
+
apiKey: config.apiKey,
|
|
619
|
+
baseURL: config.baseURL ?? RESPONSES_API_BASE_URL,
|
|
620
|
+
...(config.organization ? { organization: config.organization } : {}),
|
|
621
|
+
...(config.project ? { project: config.project } : {}),
|
|
622
|
+
...(config.timeout !== undefined ? { timeout: config.timeout } : {}),
|
|
623
|
+
...(config.maxRetries !== undefined ? { maxRetries: config.maxRetries } : {}),
|
|
624
|
+
defaultHeaders: config.defaultHeaders ?? {},
|
|
625
|
+
})
|
|
626
|
+
this.defaultModel = config.model
|
|
627
|
+
this.listingKey = ''
|
|
628
|
+
return
|
|
629
|
+
}
|
|
630
|
+
this.id = 'codex'
|
|
631
|
+
this.name = 'OpenAI Codex'
|
|
632
|
+
this.apiKeyRoute = false
|
|
565
633
|
if (!config.accessToken) throw new Error('Codex access token is required.')
|
|
566
634
|
if (!config.accountId) throw new Error('Codex ChatGPT account id is required.')
|
|
567
635
|
this.client = new OpenAI({
|
|
@@ -668,17 +736,21 @@ export class CodexProvider implements LLMProvider {
|
|
|
668
736
|
chainIndex: 0,
|
|
669
737
|
}
|
|
670
738
|
const effortLevels = this.reasoningEffortLevelsFor(model)
|
|
671
|
-
const
|
|
739
|
+
const apiKey = this.apiKeyRoute
|
|
740
|
+
// An API key has no older shape to fall back to; the shared downgrade
|
|
741
|
+
// record belongs to the subscription backend.
|
|
742
|
+
const downgradeState = apiKey ? NO_DOWNGRADE : subscriptionDowngrade
|
|
743
|
+
const built = buildRequest(params, model, targetRoute, effortLevels, downgradeState, apiKey)
|
|
672
744
|
// A tier the account's listing does not offer is refused here, before
|
|
673
745
|
// transport: the backend would drop it and serve standard speed while
|
|
674
746
|
// the caller believes the request was honoured.
|
|
675
747
|
const fast =
|
|
676
748
|
params.speed === 'fast' || params.speed === 'ultrafast'
|
|
677
749
|
? assertFastModeAccepted({
|
|
678
|
-
route: 'subscription',
|
|
750
|
+
route: apiKey ? 'api' : 'subscription',
|
|
679
751
|
model,
|
|
680
752
|
tier: params.speed,
|
|
681
|
-
advertised: this.speedTiersFor(model),
|
|
753
|
+
advertised: apiKey ? undefined : this.speedTiersFor(model),
|
|
682
754
|
firstPartyEndpoint: true,
|
|
683
755
|
})
|
|
684
756
|
: undefined
|
|
@@ -686,8 +758,18 @@ export class CodexProvider implements LLMProvider {
|
|
|
686
758
|
(fast ? { ...body, service_tier: fast.wire } : body) as ResponseCreateParamsStreaming
|
|
687
759
|
const requestedSpeed =
|
|
688
760
|
params.speed === 'fast' || params.speed === 'ultrafast' ? params.speed : undefined
|
|
689
|
-
|
|
690
|
-
|
|
761
|
+
// What the last request put on the wire, after any field the backend refused
|
|
762
|
+
// was dropped: reported with the usage, so a record can say what was sent.
|
|
763
|
+
let wire: RequestWireShape = { cacheKey: false, sessionHeader: false }
|
|
764
|
+
const send = (body: ResponseCreateParamsStreaming, sessionHeader: boolean) => {
|
|
765
|
+
wire = {
|
|
766
|
+
cacheKey: Boolean((body as { prompt_cache_key?: unknown }).prompt_cache_key),
|
|
767
|
+
sessionHeader: Boolean(sessionHeader && params.cacheKey),
|
|
768
|
+
// Recorded from the downgrade state, not from the items built: a request
|
|
769
|
+
// with no guidance to send is not a refusal.
|
|
770
|
+
...(downgradeState.noDeveloper ? { developerRefused: true } : {}),
|
|
771
|
+
}
|
|
772
|
+
return this.client.responses.create(withTier(body), {
|
|
691
773
|
signal: params.signal,
|
|
692
774
|
...(fast?.header || (sessionHeader && params.cacheKey)
|
|
693
775
|
? {
|
|
@@ -698,27 +780,38 @@ export class CodexProvider implements LLMProvider {
|
|
|
698
780
|
}
|
|
699
781
|
: {}),
|
|
700
782
|
}) as Promise<AsyncIterable<ResponseStreamEvent>>
|
|
783
|
+
}
|
|
701
784
|
let stream: AsyncIterable<ResponseStreamEvent>
|
|
702
785
|
try {
|
|
703
786
|
try {
|
|
704
|
-
stream = await send(built, !subscriptionDowngrade.
|
|
787
|
+
stream = await send(built, !apiKey && !subscriptionDowngrade.noSessionHeader)
|
|
705
788
|
} catch (error) {
|
|
706
789
|
// The backend refusing the newer shape is answered before any
|
|
707
790
|
// output exists, so one resend in the older shape is safe. It is
|
|
708
791
|
// remembered, so no later request sends the newer shape and nothing
|
|
709
792
|
// is resent twice.
|
|
710
|
-
const refused =
|
|
793
|
+
const refused = refusedNewShape(error)
|
|
711
794
|
const newShapeSent =
|
|
712
795
|
built.input !== undefined &&
|
|
713
796
|
(Boolean(params.cacheKey) ||
|
|
714
797
|
(Array.isArray(built.input) &&
|
|
715
798
|
built.input.some((item) => 'role' in item && item.role === 'developer')))
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
799
|
+
// Only what is still being sent can be what was refused.
|
|
800
|
+
const fresh =
|
|
801
|
+
refused &&
|
|
802
|
+
(
|
|
803
|
+
[
|
|
804
|
+
'noDeveloper',
|
|
805
|
+
'noSessionHeader',
|
|
806
|
+
'noCacheKey',
|
|
807
|
+
] as const satisfies readonly (keyof SubscriptionDowngrade)[]
|
|
808
|
+
).filter((key) => refused[key] && !subscriptionDowngrade[key])
|
|
809
|
+
if (apiKey || !fresh || fresh.length === 0 || !newShapeSent || params.signal?.aborted)
|
|
810
|
+
throw error
|
|
811
|
+
for (const key of fresh) subscriptionDowngrade[key] = true
|
|
719
812
|
stream = await send(
|
|
720
|
-
buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade),
|
|
721
|
-
|
|
813
|
+
buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade, apiKey),
|
|
814
|
+
!subscriptionDowngrade.noSessionHeader,
|
|
722
815
|
)
|
|
723
816
|
}
|
|
724
817
|
} catch (error) {
|
|
@@ -949,6 +1042,8 @@ export class CodexProvider implements LLMProvider {
|
|
|
949
1042
|
event.response.usage ?? {},
|
|
950
1043
|
(event.response as { service_tier?: unknown }).service_tier,
|
|
951
1044
|
requestedSpeed,
|
|
1045
|
+
wire,
|
|
1046
|
+
Boolean(apiKey),
|
|
952
1047
|
),
|
|
953
1048
|
replayState,
|
|
954
1049
|
}
|
|
@@ -973,6 +1068,8 @@ export class CodexProvider implements LLMProvider {
|
|
|
973
1068
|
event.response.usage ?? {},
|
|
974
1069
|
(event.response as { service_tier?: unknown }).service_tier,
|
|
975
1070
|
requestedSpeed,
|
|
1071
|
+
wire,
|
|
1072
|
+
Boolean(apiKey),
|
|
976
1073
|
),
|
|
977
1074
|
}
|
|
978
1075
|
break
|
|
@@ -982,7 +1079,7 @@ export class CodexProvider implements LLMProvider {
|
|
|
982
1079
|
throw new ProviderRequestError({
|
|
983
1080
|
kind: 'server',
|
|
984
1081
|
providerId: this.id,
|
|
985
|
-
detail: 'the Codex Responses stream failed',
|
|
1082
|
+
detail: apiKey ? 'the Responses stream failed' : 'the Codex Responses stream failed',
|
|
986
1083
|
})
|
|
987
1084
|
}
|
|
988
1085
|
}
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which ids of OpenAI's `/v1/models` listing can serve a chat turn.
|
|
3
|
+
*
|
|
4
|
+
* The listing carries `id`, `object`, `created`, `owned_by` and `shutdown_date`
|
|
5
|
+
* and nothing that says what a model is for, so the rule is on the id. A model
|
|
6
|
+
* is offered when its id is in a chat family AND names none of the kinds that
|
|
7
|
+
* Chat Completions refuses: speech in or out, realtime and live sessions,
|
|
8
|
+
* images, embeddings, moderation, search-only models and legacy completions.
|
|
9
|
+
*
|
|
10
|
+
* `-pro` and `-codex` ids stay in the list: OpenAI answers them on the
|
|
11
|
+
* Responses endpoint only, and the driver sends them there. `gpt-live-*` is
|
|
12
|
+
* hidden because it is a voice model: its model page
|
|
13
|
+
* (developers.openai.com/api/docs/models/gpt-live-1.1) lists audio in and out
|
|
14
|
+
* and supports only the Live endpoint (`v1/live/sessions`), not Chat
|
|
15
|
+
* Completions, Responses or Realtime.
|
|
16
|
+
*
|
|
17
|
+
* This only shapes the list a person picks from. A model typed by id is never
|
|
18
|
+
* refused here.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Families that hold chat models: `gpt-*`, the o-series, `chatgpt-*` and `chat-latest`. */
|
|
22
|
+
const CHAT_FAMILY = /^(?:gpt-|o\d|chatgpt-|chat-latest)/
|
|
23
|
+
|
|
24
|
+
/** Kinds that are not chat, matched anywhere in the id. */
|
|
25
|
+
const NOT_CHAT =
|
|
26
|
+
/(?:audio|realtime|gpt-live|transcribe|diarize|whisper|tts|image|sora|dall-e|embed|moderation|search-api|search-preview|computer-use|instruct|babbage|davinci)/
|
|
27
|
+
|
|
28
|
+
/** `tts-1`, `whisper-1`, `text-embedding-*` and the like never start with a chat family; this keeps the reason explicit. */
|
|
29
|
+
export function isOpenAIChatModelId(id: string): boolean {
|
|
30
|
+
const normalized = id.toLowerCase().replace(/^ft:/, '')
|
|
31
|
+
return CHAT_FAMILY.test(normalized) && !NOT_CHAT.test(normalized)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The rows of a listing that can serve a chat turn, in their order. */
|
|
35
|
+
export function chatModelsOnly<T extends { readonly id: string }>(rows: readonly T[]): T[] {
|
|
36
|
+
return rows.filter((row) => isOpenAIChatModelId(row.id))
|
|
37
|
+
}
|