@namzu/openai 4.8.1 → 4.8.3
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 +124 -7
- 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 +116 -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 +132 -7
- package/src/codex.ts +139 -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
|
|
|
@@ -110,6 +112,79 @@ export function openAIReasoningEffortLevels(model: string): readonly ReasoningEf
|
|
|
110
112
|
return undefined
|
|
111
113
|
}
|
|
112
114
|
|
|
115
|
+
/**
|
|
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.
|
|
122
|
+
*/
|
|
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
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
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())
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
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.
|
|
173
|
+
*/
|
|
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')
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Models that refuse `reasoning_effort` outright. */
|
|
184
|
+
function refusesReasoningEffort(model: string): boolean {
|
|
185
|
+
return isClassicChatModel(model)
|
|
186
|
+
}
|
|
187
|
+
|
|
113
188
|
/** Whether a base URL names a host other than OpenAI's own API. */
|
|
114
189
|
function isCompatibleHost(baseURL: string | undefined): boolean {
|
|
115
190
|
return !isFirstPartyOpenAIEndpoint(baseURL)
|
|
@@ -505,6 +580,8 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
505
580
|
private thinkingOffFields: OpenAIConfig['thinkingOffFields']
|
|
506
581
|
/** The base URL requests go to, kept to name the host when fast mode is refused there. */
|
|
507
582
|
private readonly effectiveBaseURL: string | undefined
|
|
583
|
+
private readonly config: OpenAIConfig
|
|
584
|
+
private responses?: CodexProvider
|
|
508
585
|
|
|
509
586
|
constructor(config: OpenAIConfig) {
|
|
510
587
|
if (!config.apiKey) {
|
|
@@ -528,6 +605,7 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
528
605
|
}
|
|
529
606
|
|
|
530
607
|
this.client = new OpenAI(clientOptions)
|
|
608
|
+
this.config = config
|
|
531
609
|
this.defaultModel = config.model
|
|
532
610
|
this.thinkingOffFields = config.thinkingOffFields
|
|
533
611
|
// The client reads the standard base-URL variable when none is given, so that is where requests go.
|
|
@@ -574,6 +652,25 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
574
652
|
return this.declaredWindows.get(model)
|
|
575
653
|
}
|
|
576
654
|
|
|
655
|
+
/**
|
|
656
|
+
* The Responses transport for this key, built on the subscription driver's
|
|
657
|
+
* request and stream handling. Only used on OpenAI's own endpoint.
|
|
658
|
+
*/
|
|
659
|
+
private responsesRoute(): CodexProvider {
|
|
660
|
+
this.responses ??= new CodexProvider({
|
|
661
|
+
responsesApi: true,
|
|
662
|
+
apiKey: this.config.apiKey,
|
|
663
|
+
model: this.defaultModel,
|
|
664
|
+
...(this.effectiveBaseURL ? { baseURL: this.effectiveBaseURL } : {}),
|
|
665
|
+
organization: this.config.organization,
|
|
666
|
+
project: this.config.project,
|
|
667
|
+
timeout: this.config.timeout,
|
|
668
|
+
maxRetries: this.config.maxRetries,
|
|
669
|
+
defaultHeaders: { ...attributionHeaders(), ...(this.config.defaultHeaders ?? {}) },
|
|
670
|
+
})
|
|
671
|
+
return this.responses
|
|
672
|
+
}
|
|
673
|
+
|
|
577
674
|
private resolveModel(params: ChatCompletionParams): string {
|
|
578
675
|
const model = params.model || this.defaultModel
|
|
579
676
|
if (!model) {
|
|
@@ -592,6 +689,18 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
592
689
|
const model = this.resolveModel(params)
|
|
593
690
|
assertThinkingSupported(params)
|
|
594
691
|
assertOpenAIReasoningEffort(model, params.effort)
|
|
692
|
+
// The model's own rules apply on OpenAI's own host only; a compatible
|
|
693
|
+
// endpoint reached through a custom base URL keeps the classic fields.
|
|
694
|
+
const firstParty = !this.compatibleHost
|
|
695
|
+
if (firstParty && openAIModelNeedsResponses(model, params)) {
|
|
696
|
+
yield* this.responsesRoute().chatStream({ ...params, model })
|
|
697
|
+
return
|
|
698
|
+
}
|
|
699
|
+
// First-party Chat Completions always takes `max_completion_tokens`; the
|
|
700
|
+
// sampling fields go only where the model accepts them, and only when the
|
|
701
|
+
// caller set them; elsewhere they are dropped with no error.
|
|
702
|
+
const dropsSampling = firstParty && !takesSamplingFields(model, params.effort)
|
|
703
|
+
const effort = firstParty && refusesReasoningEffort(model) ? undefined : params.effort
|
|
595
704
|
|
|
596
705
|
// A call that asked for no effort (or for thinking to be off) means no
|
|
597
706
|
// reasoning at all. `reasoning_effort` alone is ignored by some compatible
|
|
@@ -632,17 +741,23 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
632
741
|
tools: toOpenAITools(params),
|
|
633
742
|
tool_choice: formatToolChoice(params.toolChoice),
|
|
634
743
|
parallel_tool_calls: params.parallelToolCalls,
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
744
|
+
...(dropsSampling
|
|
745
|
+
? {}
|
|
746
|
+
: {
|
|
747
|
+
temperature: params.temperature,
|
|
748
|
+
top_p: params.topP,
|
|
749
|
+
frequency_penalty: params.frequencyPenalty,
|
|
750
|
+
presence_penalty: params.presencePenalty,
|
|
751
|
+
}),
|
|
752
|
+
...(firstParty
|
|
753
|
+
? { max_completion_tokens: params.maxTokens }
|
|
754
|
+
: { max_tokens: params.maxTokens }),
|
|
640
755
|
stop: params.stop,
|
|
641
756
|
response_format: params.responseFormat,
|
|
642
757
|
...(serviceTier ? { service_tier: serviceTier } : {}),
|
|
643
758
|
...(offFields ?? {}),
|
|
644
759
|
},
|
|
645
|
-
|
|
760
|
+
effort,
|
|
646
761
|
),
|
|
647
762
|
// Per-request abort: a Stop tears the in-flight SSE request down.
|
|
648
763
|
{ signal: params.signal },
|
|
@@ -655,6 +770,14 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
655
770
|
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
656
771
|
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
657
772
|
if (isProviderRequestError(err)) throw err
|
|
773
|
+
// The model answered before any output that its tools cannot go with
|
|
774
|
+
// reasoning on this endpoint: remember that for the process and send the
|
|
775
|
+
// request once through Responses, which takes the pair.
|
|
776
|
+
if (firstParty && isResponsesOnlyRefusal(err)) {
|
|
777
|
+
learnedResponsesModels.add(model.toLowerCase().replace(/^ft:/, ''))
|
|
778
|
+
yield* this.responsesRoute().chatStream({ ...params, model })
|
|
779
|
+
return
|
|
780
|
+
}
|
|
658
781
|
throw providerVendorError({ providerId: 'openai', error: err })
|
|
659
782
|
}
|
|
660
783
|
|
|
@@ -772,7 +895,9 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
772
895
|
signal?.throwIfAborted()
|
|
773
896
|
const page = await this.client.models.list(signal ? { signal } : undefined)
|
|
774
897
|
signal?.throwIfAborted()
|
|
775
|
-
|
|
898
|
+
// OpenAI's own listing mixes in speech, image and embedding models; a compatible host's does not.
|
|
899
|
+
const rows = this.compatibleHost ? page.data : chatModelsOnly(page.data)
|
|
900
|
+
return rows.map((m) => ({
|
|
776
901
|
id: m.id,
|
|
777
902
|
name: m.id,
|
|
778
903
|
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,7 @@ function responseUsage(
|
|
|
356
360
|
},
|
|
357
361
|
servedTier?: unknown,
|
|
358
362
|
requestedSpeed?: InferenceSpeed,
|
|
363
|
+
requestShape?: RequestWireShape,
|
|
359
364
|
): TokenUsage {
|
|
360
365
|
const promptTokens = usage.input_tokens ?? 0
|
|
361
366
|
const completionTokens = usage.output_tokens ?? 0
|
|
@@ -366,6 +371,7 @@ function responseUsage(
|
|
|
366
371
|
cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
|
|
367
372
|
cacheWriteTokens: 0,
|
|
368
373
|
...servedSpeed(servedTier, requestedSpeed),
|
|
374
|
+
...(requestShape ? { requestShape } : {}),
|
|
369
375
|
}
|
|
370
376
|
}
|
|
371
377
|
|
|
@@ -397,6 +403,7 @@ function buildRequest(
|
|
|
397
403
|
targetRoute: ProviderRoute,
|
|
398
404
|
supportedEffort: readonly ReasoningEffort[] | undefined,
|
|
399
405
|
downgrade: SubscriptionDowngrade = NO_DOWNGRADE,
|
|
406
|
+
apiKey = false,
|
|
400
407
|
): ResponseCreateParamsStreaming {
|
|
401
408
|
if (
|
|
402
409
|
params.effort !== undefined &&
|
|
@@ -425,14 +432,13 @@ function buildRequest(
|
|
|
425
432
|
// where they were, as developer messages in the input.
|
|
426
433
|
let openingRun = 0
|
|
427
434
|
while (params.messages[openingRun]?.role === 'system') openingRun++
|
|
428
|
-
//
|
|
429
|
-
//
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
)
|
|
435
|
+
// What the backend refused of the newer shape changes only the field it
|
|
436
|
+
// named; it never moves text into `instructions`. A changing preamble
|
|
437
|
+
// joined into `instructions` sits in front of the whole input, so the
|
|
438
|
+
// next request shared nothing with it past the tools. A refused
|
|
439
|
+
// `developer` item is sent as a `user` item in the same place instead.
|
|
440
|
+
const instructions = params.messages
|
|
441
|
+
.slice(0, openingRun)
|
|
436
442
|
.map((message) => message.content)
|
|
437
443
|
.join('\n\n')
|
|
438
444
|
const request = {
|
|
@@ -440,10 +446,18 @@ function buildRequest(
|
|
|
440
446
|
stream: true,
|
|
441
447
|
store: false,
|
|
442
448
|
instructions: instructions || undefined,
|
|
443
|
-
input: toCodexInput(
|
|
449
|
+
input: toCodexInput(
|
|
450
|
+
params.messages,
|
|
451
|
+
targetRoute,
|
|
452
|
+
openingRun,
|
|
453
|
+
downgrade.noDeveloper ? 'user' : 'developer',
|
|
454
|
+
),
|
|
444
455
|
// One key for the whole conversation routes every request to the same
|
|
445
456
|
// cache; without it the backend keys on the request alone.
|
|
446
457
|
...(params.cacheKey && !downgrade.noCacheKey ? { prompt_cache_key: params.cacheKey } : {}),
|
|
458
|
+
// An API key reaches the public Responses endpoint, which has the member and
|
|
459
|
+
// is told the budget the caller set.
|
|
460
|
+
...(apiKey && params.maxTokens !== undefined ? { max_output_tokens: params.maxTokens } : {}),
|
|
447
461
|
// The Codex subscription request schema deliberately has no
|
|
448
462
|
// `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
|
|
449
463
|
// API control, but projecting it onto this route makes the whole request
|
|
@@ -452,7 +466,7 @@ function buildRequest(
|
|
|
452
466
|
// turn that exposes no tools. The ordinary public Responses endpoint admits
|
|
453
467
|
// their omission, which is why the generated client types all make them
|
|
454
468
|
// optional; the Codex wire does not have the same defaulting contract.
|
|
455
|
-
tools: toCodexTools(params) ?? [],
|
|
469
|
+
tools: toCodexTools(params, apiKey) ?? [],
|
|
456
470
|
tool_choice: (params.toolChoice ?? 'auto') as ResponseCreateParamsStreaming['tool_choice'],
|
|
457
471
|
parallel_tool_calls: params.parallelToolCalls ?? true,
|
|
458
472
|
include: ['reasoning.encrypted_content'],
|
|
@@ -481,38 +495,49 @@ function buildRequest(
|
|
|
481
495
|
/**
|
|
482
496
|
* What the subscription backend has refused of the newer request shape: the
|
|
483
497
|
* `developer` input item, the `session_id` header, the `prompt_cache_key` body
|
|
484
|
-
* field.
|
|
485
|
-
* refusal triggers; later requests go
|
|
498
|
+
* field. Each is recorded only when the refusal named it, for the life of the
|
|
499
|
+
* process, by the one resend that the refusal triggers; later requests go
|
|
500
|
+
* straight to the older shape. A refusal that names none of them is not one.
|
|
486
501
|
*/
|
|
487
502
|
interface SubscriptionDowngrade {
|
|
488
|
-
/**
|
|
489
|
-
|
|
490
|
-
/** The
|
|
503
|
+
/** Later system messages go as `user` items, in the same place. */
|
|
504
|
+
noDeveloper: boolean
|
|
505
|
+
/** The `session_id` header is left off. */
|
|
506
|
+
noSessionHeader: boolean
|
|
507
|
+
/** The `prompt_cache_key` body field is left off. */
|
|
491
508
|
noCacheKey: boolean
|
|
492
509
|
}
|
|
493
510
|
|
|
494
|
-
const NO_DOWNGRADE: SubscriptionDowngrade = {
|
|
495
|
-
|
|
511
|
+
const NO_DOWNGRADE: SubscriptionDowngrade = {
|
|
512
|
+
noDeveloper: false,
|
|
513
|
+
noSessionHeader: false,
|
|
514
|
+
noCacheKey: false,
|
|
515
|
+
}
|
|
516
|
+
const subscriptionDowngrade: SubscriptionDowngrade = { ...NO_DOWNGRADE }
|
|
496
517
|
|
|
497
518
|
/** Test seam: forget a downgrade recorded earlier in this process. */
|
|
498
519
|
export function resetSubscriptionDowngrade(): void {
|
|
499
|
-
subscriptionDowngrade
|
|
500
|
-
subscriptionDowngrade.noCacheKey = false
|
|
520
|
+
Object.assign(subscriptionDowngrade, NO_DOWNGRADE)
|
|
501
521
|
}
|
|
502
522
|
|
|
503
|
-
const REFUSED_SHAPE = /\bdeveloper\b|\brole\b|\binput\[\d*\]|session_id|prompt_cache_key/i
|
|
504
|
-
|
|
505
523
|
/**
|
|
506
|
-
* A bad-request answer that names what the newer shape added
|
|
507
|
-
* (a different 400,
|
|
524
|
+
* A bad-request answer that names what the newer shape added, by the name of
|
|
525
|
+
* the field or the role. Anything else (a different 400, a bad image at
|
|
526
|
+
* `input[3].content`, any other status, a network failure) is not one: taking
|
|
527
|
+
* it for one drops the cache key or moves the changing guidance for every
|
|
528
|
+
* later request of the process, and the cache is lost with it.
|
|
508
529
|
*/
|
|
509
|
-
function refusedNewShape(error: unknown):
|
|
530
|
+
function refusedNewShape(error: unknown): Partial<SubscriptionDowngrade> | undefined {
|
|
510
531
|
if (typeof error !== 'object' || error === null) return undefined
|
|
511
532
|
const status = (error as { status?: unknown }).status
|
|
512
533
|
if (!(error instanceof OpenAI.BadRequestError) && status !== 400) return undefined
|
|
513
534
|
const message = (error as { message?: unknown }).message
|
|
514
|
-
if (typeof message !== 'string'
|
|
515
|
-
|
|
535
|
+
if (typeof message !== 'string') return undefined
|
|
536
|
+
const refused: Partial<SubscriptionDowngrade> = {}
|
|
537
|
+
if (/\bdeveloper\b|input\[\d*\]\.role/i.test(message)) refused.noDeveloper = true
|
|
538
|
+
if (/session_id/i.test(message)) refused.noSessionHeader = true
|
|
539
|
+
if (/prompt_cache_key/i.test(message)) refused.noCacheKey = true
|
|
540
|
+
return Object.keys(refused).length > 0 ? refused : undefined
|
|
516
541
|
}
|
|
517
542
|
|
|
518
543
|
/**
|
|
@@ -542,10 +567,30 @@ const WINDOW_LISTING_TIMEOUT_MS = 3_000
|
|
|
542
567
|
/** How long a failed listing is remembered, so a turn does not ask again every time. */
|
|
543
568
|
const WINDOW_LISTING_RETRY_MS = 5 * 60_000
|
|
544
569
|
|
|
570
|
+
/**
|
|
571
|
+
* An API key for OpenAI's own Responses endpoint. The same request building,
|
|
572
|
+
* streaming, tool-call and reasoning-item handling as the subscription
|
|
573
|
+
* transport; only the address, the bearer and the account routing differ.
|
|
574
|
+
*/
|
|
575
|
+
export interface ResponsesApiConfig {
|
|
576
|
+
apiKey: string
|
|
577
|
+
model?: string
|
|
578
|
+
baseURL?: string
|
|
579
|
+
organization?: string
|
|
580
|
+
project?: string
|
|
581
|
+
timeout?: number
|
|
582
|
+
defaultHeaders?: Record<string, string>
|
|
583
|
+
maxRetries?: number
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
export const RESPONSES_API_BASE_URL = 'https://api.openai.com/v1'
|
|
587
|
+
|
|
545
588
|
export class CodexProvider implements LLMProvider {
|
|
546
|
-
readonly id
|
|
547
|
-
readonly name
|
|
589
|
+
readonly id: string
|
|
590
|
+
readonly name: string
|
|
548
591
|
readonly capabilities = CODEX_CAPABILITIES
|
|
592
|
+
/** True when an API key (not a subscription) is the credential. */
|
|
593
|
+
private readonly apiKeyRoute: boolean
|
|
549
594
|
|
|
550
595
|
private client: OpenAI
|
|
551
596
|
private defaultModel?: string
|
|
@@ -561,7 +606,28 @@ export class CodexProvider implements LLMProvider {
|
|
|
561
606
|
private windowListing?: Promise<boolean>
|
|
562
607
|
private readonly listingKey: string
|
|
563
608
|
|
|
564
|
-
constructor(config: CodexConfig) {
|
|
609
|
+
constructor(config: CodexConfig | ({ responsesApi: true } & ResponsesApiConfig)) {
|
|
610
|
+
if ('responsesApi' in config) {
|
|
611
|
+
if (!config.apiKey) throw new Error('OpenAI API key is required.')
|
|
612
|
+
this.id = 'openai'
|
|
613
|
+
this.name = 'OpenAI'
|
|
614
|
+
this.apiKeyRoute = true
|
|
615
|
+
this.client = new OpenAI({
|
|
616
|
+
apiKey: config.apiKey,
|
|
617
|
+
baseURL: config.baseURL ?? RESPONSES_API_BASE_URL,
|
|
618
|
+
...(config.organization ? { organization: config.organization } : {}),
|
|
619
|
+
...(config.project ? { project: config.project } : {}),
|
|
620
|
+
...(config.timeout !== undefined ? { timeout: config.timeout } : {}),
|
|
621
|
+
...(config.maxRetries !== undefined ? { maxRetries: config.maxRetries } : {}),
|
|
622
|
+
defaultHeaders: config.defaultHeaders ?? {},
|
|
623
|
+
})
|
|
624
|
+
this.defaultModel = config.model
|
|
625
|
+
this.listingKey = ''
|
|
626
|
+
return
|
|
627
|
+
}
|
|
628
|
+
this.id = 'codex'
|
|
629
|
+
this.name = 'OpenAI Codex'
|
|
630
|
+
this.apiKeyRoute = false
|
|
565
631
|
if (!config.accessToken) throw new Error('Codex access token is required.')
|
|
566
632
|
if (!config.accountId) throw new Error('Codex ChatGPT account id is required.')
|
|
567
633
|
this.client = new OpenAI({
|
|
@@ -668,17 +734,21 @@ export class CodexProvider implements LLMProvider {
|
|
|
668
734
|
chainIndex: 0,
|
|
669
735
|
}
|
|
670
736
|
const effortLevels = this.reasoningEffortLevelsFor(model)
|
|
671
|
-
const
|
|
737
|
+
const apiKey = this.apiKeyRoute
|
|
738
|
+
// An API key has no older shape to fall back to; the shared downgrade
|
|
739
|
+
// record belongs to the subscription backend.
|
|
740
|
+
const downgradeState = apiKey ? NO_DOWNGRADE : subscriptionDowngrade
|
|
741
|
+
const built = buildRequest(params, model, targetRoute, effortLevels, downgradeState, apiKey)
|
|
672
742
|
// A tier the account's listing does not offer is refused here, before
|
|
673
743
|
// transport: the backend would drop it and serve standard speed while
|
|
674
744
|
// the caller believes the request was honoured.
|
|
675
745
|
const fast =
|
|
676
746
|
params.speed === 'fast' || params.speed === 'ultrafast'
|
|
677
747
|
? assertFastModeAccepted({
|
|
678
|
-
route: 'subscription',
|
|
748
|
+
route: apiKey ? 'api' : 'subscription',
|
|
679
749
|
model,
|
|
680
750
|
tier: params.speed,
|
|
681
|
-
advertised: this.speedTiersFor(model),
|
|
751
|
+
advertised: apiKey ? undefined : this.speedTiersFor(model),
|
|
682
752
|
firstPartyEndpoint: true,
|
|
683
753
|
})
|
|
684
754
|
: undefined
|
|
@@ -686,8 +756,18 @@ export class CodexProvider implements LLMProvider {
|
|
|
686
756
|
(fast ? { ...body, service_tier: fast.wire } : body) as ResponseCreateParamsStreaming
|
|
687
757
|
const requestedSpeed =
|
|
688
758
|
params.speed === 'fast' || params.speed === 'ultrafast' ? params.speed : undefined
|
|
689
|
-
|
|
690
|
-
|
|
759
|
+
// What the last request put on the wire, after any field the backend refused
|
|
760
|
+
// was dropped: reported with the usage, so a record can say what was sent.
|
|
761
|
+
let wire: RequestWireShape = { cacheKey: false, sessionHeader: false }
|
|
762
|
+
const send = (body: ResponseCreateParamsStreaming, sessionHeader: boolean) => {
|
|
763
|
+
wire = {
|
|
764
|
+
cacheKey: Boolean((body as { prompt_cache_key?: unknown }).prompt_cache_key),
|
|
765
|
+
sessionHeader: Boolean(sessionHeader && params.cacheKey),
|
|
766
|
+
// Recorded from the downgrade state, not from the items built: a request
|
|
767
|
+
// with no guidance to send is not a refusal.
|
|
768
|
+
...(downgradeState.noDeveloper ? { developerRefused: true } : {}),
|
|
769
|
+
}
|
|
770
|
+
return this.client.responses.create(withTier(body), {
|
|
691
771
|
signal: params.signal,
|
|
692
772
|
...(fast?.header || (sessionHeader && params.cacheKey)
|
|
693
773
|
? {
|
|
@@ -698,27 +778,38 @@ export class CodexProvider implements LLMProvider {
|
|
|
698
778
|
}
|
|
699
779
|
: {}),
|
|
700
780
|
}) as Promise<AsyncIterable<ResponseStreamEvent>>
|
|
781
|
+
}
|
|
701
782
|
let stream: AsyncIterable<ResponseStreamEvent>
|
|
702
783
|
try {
|
|
703
784
|
try {
|
|
704
|
-
stream = await send(built, !subscriptionDowngrade.
|
|
785
|
+
stream = await send(built, !apiKey && !subscriptionDowngrade.noSessionHeader)
|
|
705
786
|
} catch (error) {
|
|
706
787
|
// The backend refusing the newer shape is answered before any
|
|
707
788
|
// output exists, so one resend in the older shape is safe. It is
|
|
708
789
|
// remembered, so no later request sends the newer shape and nothing
|
|
709
790
|
// is resent twice.
|
|
710
|
-
const refused =
|
|
791
|
+
const refused = refusedNewShape(error)
|
|
711
792
|
const newShapeSent =
|
|
712
793
|
built.input !== undefined &&
|
|
713
794
|
(Boolean(params.cacheKey) ||
|
|
714
795
|
(Array.isArray(built.input) &&
|
|
715
796
|
built.input.some((item) => 'role' in item && item.role === 'developer')))
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
797
|
+
// Only what is still being sent can be what was refused.
|
|
798
|
+
const fresh =
|
|
799
|
+
refused &&
|
|
800
|
+
(
|
|
801
|
+
[
|
|
802
|
+
'noDeveloper',
|
|
803
|
+
'noSessionHeader',
|
|
804
|
+
'noCacheKey',
|
|
805
|
+
] as const satisfies readonly (keyof SubscriptionDowngrade)[]
|
|
806
|
+
).filter((key) => refused[key] && !subscriptionDowngrade[key])
|
|
807
|
+
if (apiKey || !fresh || fresh.length === 0 || !newShapeSent || params.signal?.aborted)
|
|
808
|
+
throw error
|
|
809
|
+
for (const key of fresh) subscriptionDowngrade[key] = true
|
|
719
810
|
stream = await send(
|
|
720
|
-
buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade),
|
|
721
|
-
|
|
811
|
+
buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade, apiKey),
|
|
812
|
+
!subscriptionDowngrade.noSessionHeader,
|
|
722
813
|
)
|
|
723
814
|
}
|
|
724
815
|
} catch (error) {
|
|
@@ -949,6 +1040,7 @@ export class CodexProvider implements LLMProvider {
|
|
|
949
1040
|
event.response.usage ?? {},
|
|
950
1041
|
(event.response as { service_tier?: unknown }).service_tier,
|
|
951
1042
|
requestedSpeed,
|
|
1043
|
+
wire,
|
|
952
1044
|
),
|
|
953
1045
|
replayState,
|
|
954
1046
|
}
|
|
@@ -973,6 +1065,7 @@ export class CodexProvider implements LLMProvider {
|
|
|
973
1065
|
event.response.usage ?? {},
|
|
974
1066
|
(event.response as { service_tier?: unknown }).service_tier,
|
|
975
1067
|
requestedSpeed,
|
|
1068
|
+
wire,
|
|
976
1069
|
),
|
|
977
1070
|
}
|
|
978
1071
|
break
|
|
@@ -982,7 +1075,7 @@ export class CodexProvider implements LLMProvider {
|
|
|
982
1075
|
throw new ProviderRequestError({
|
|
983
1076
|
kind: 'server',
|
|
984
1077
|
providerId: this.id,
|
|
985
|
-
detail: 'the Codex Responses stream failed',
|
|
1078
|
+
detail: apiKey ? 'the Responses stream failed' : 'the Codex Responses stream failed',
|
|
986
1079
|
})
|
|
987
1080
|
}
|
|
988
1081
|
}
|
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
|
+
}
|