@namzu/openrouter 3.2.0 → 3.2.2
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 +13 -0
- package/dist/client.d.ts +31 -8
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +317 -64
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/client.ts +357 -73
- package/src/types.ts +2 -0
package/src/client.ts
CHANGED
|
@@ -19,6 +19,8 @@ import {
|
|
|
19
19
|
providerVendorError,
|
|
20
20
|
} from '@namzu/sdk'
|
|
21
21
|
import { attributionHeaders } from '@namzu/sdk'
|
|
22
|
+
import type { Logger } from '@namzu/sdk'
|
|
23
|
+
import { NOOP_LOGGER } from '@namzu/sdk'
|
|
22
24
|
import type { OpenRouterConfig } from './types.js'
|
|
23
25
|
|
|
24
26
|
/**
|
|
@@ -208,6 +210,8 @@ interface RawUsage {
|
|
|
208
210
|
total_tokens: number
|
|
209
211
|
prompt_tokens_details?: {
|
|
210
212
|
cached_tokens?: number
|
|
213
|
+
/** Tokens written to an explicit cache; OpenRouter documents it for models with explicit caching. */
|
|
214
|
+
cache_write_tokens?: number
|
|
211
215
|
}
|
|
212
216
|
completion_tokens_details?: {
|
|
213
217
|
reasoning_tokens?: number
|
|
@@ -270,7 +274,8 @@ function parseUsage(raw?: RawUsage): TokenUsage {
|
|
|
270
274
|
completionTokens: raw.completion_tokens,
|
|
271
275
|
totalTokens: raw.total_tokens,
|
|
272
276
|
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
|
|
273
|
-
cacheWriteTokens:
|
|
277
|
+
cacheWriteTokens:
|
|
278
|
+
raw.cache_creation_input_tokens ?? raw.prompt_tokens_details?.cache_write_tokens ?? 0,
|
|
274
279
|
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
|
|
275
280
|
...(cost !== undefined ? { reportedCostUsd: cost } : {}),
|
|
276
281
|
}
|
|
@@ -512,15 +517,45 @@ function refusesForcedChoiceWhileReasoning(model: string): boolean {
|
|
|
512
517
|
return /^deepseek-(v([4-9]|\d{2,})(\.|-|$)|r\d+(-|$)|reasoner(-|$)|(flash|pro)(-|$))/.test(bare)
|
|
513
518
|
}
|
|
514
519
|
|
|
520
|
+
/** Highest first. What a request for `max` or `ultra` falls down through. */
|
|
521
|
+
const EFFORT_DESCENDING = ['max', 'xhigh', 'high', 'medium', 'low', 'minimal'] as const
|
|
522
|
+
|
|
515
523
|
/**
|
|
516
|
-
* The effort
|
|
524
|
+
* The level that stands in for an SDK effort the wire may not carry.
|
|
517
525
|
*
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
*
|
|
526
|
+
* `max` and `ultra` are legal SDK values, so refusing them stopped a run for a
|
|
527
|
+
* setting nobody did wrong. Each asks for the deepest reasoning the model
|
|
528
|
+
* offers, so each resolves to the highest level in the model's own list
|
|
529
|
+
* (`supported_efforts` in the `/models` listing), never `none`. When the
|
|
530
|
+
* listing could not be read or does not carry a list for the model, the
|
|
531
|
+
* highest level the unified `reasoning.effort` documents for every model, `xhigh`, is sent: a level the
|
|
532
|
+
* vendor accepts, one step short of what was asked for rather than a failure.
|
|
533
|
+
* Every other level is sent as given.
|
|
522
534
|
*/
|
|
523
|
-
|
|
535
|
+
function carriedEffort(
|
|
536
|
+
effort: NonNullable<ChatCompletionParams['effort']>,
|
|
537
|
+
supported: readonly string[] | undefined,
|
|
538
|
+
): string {
|
|
539
|
+
if (effort !== 'max' && effort !== 'ultra') return effort
|
|
540
|
+
if (!supported) return 'xhigh'
|
|
541
|
+
return EFFORT_DESCENDING.find((level) => supported.includes(level)) ?? 'xhigh'
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** The least thinking budget a budgeted model accepts. */
|
|
545
|
+
const MIN_THINKING_BUDGET = 1024
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* A thinking budget has to leave room for the answer: a budget at or above the
|
|
549
|
+
* request's output limit is refused by the host. With both numbers present and
|
|
550
|
+
* a limit above 1024, the budget is brought under the limit (and up to 1024 if
|
|
551
|
+
* it was lower); in every other case it is sent as given.
|
|
552
|
+
*/
|
|
553
|
+
function fitBudget(budget: number | undefined, maxTokens: number | undefined): number | undefined {
|
|
554
|
+
if (budget === undefined || maxTokens === undefined || maxTokens <= MIN_THINKING_BUDGET) {
|
|
555
|
+
return budget
|
|
556
|
+
}
|
|
557
|
+
return Math.max(MIN_THINKING_BUDGET, Math.min(budget, maxTokens - 1))
|
|
558
|
+
}
|
|
524
559
|
|
|
525
560
|
/**
|
|
526
561
|
* Map the SDK's thinking controls onto OpenRouter's unified `reasoning` object.
|
|
@@ -530,29 +565,110 @@ const OPENROUTER_REASONING_EFFORT = ['none', 'minimal', 'low', 'medium', 'high',
|
|
|
530
565
|
*/
|
|
531
566
|
function formatReasoning(
|
|
532
567
|
thinking: ChatCompletionParams['thinking'],
|
|
533
|
-
effort:
|
|
568
|
+
effort: string | undefined,
|
|
569
|
+
maxTokens?: number,
|
|
534
570
|
): Record<string, unknown> | undefined {
|
|
535
|
-
if (effort !== undefined) {
|
|
536
|
-
const carried = (OPENROUTER_REASONING_EFFORT as readonly string[]).includes(effort)
|
|
537
|
-
if (!carried) {
|
|
538
|
-
throw new Error(
|
|
539
|
-
`OpenRouterProvider cannot carry effort "${effort}". Its reasoning.effort accepts ${OPENROUTER_REASONING_EFFORT.join(', ')}. Sending a different level would return a perfectly ordinary completion that no caller could tell apart from the one that was asked for.`,
|
|
540
|
-
)
|
|
541
|
-
}
|
|
542
|
-
return { effort }
|
|
543
|
-
}
|
|
571
|
+
if (effort !== undefined) return { effort }
|
|
544
572
|
if (!thinking || thinking.type === undefined) return undefined
|
|
545
573
|
if (thinking.type === 'disabled') return { enabled: false }
|
|
546
574
|
// 'adaptive' has no separate spelling on this wire: the model decides its
|
|
547
575
|
// own depth, which is what `enabled: true` without a budget expresses.
|
|
548
576
|
// 'enabled' fixes the depth with budgetTokens, so it carries the cap.
|
|
549
|
-
const budgetTokens =
|
|
577
|
+
const budgetTokens = fitBudget(
|
|
578
|
+
thinking.type === 'enabled' ? thinking.budgetTokens : undefined,
|
|
579
|
+
maxTokens,
|
|
580
|
+
)
|
|
550
581
|
return {
|
|
551
582
|
enabled: true,
|
|
552
583
|
...(budgetTokens !== undefined ? { max_tokens: budgetTokens } : {}),
|
|
553
584
|
}
|
|
554
585
|
}
|
|
555
586
|
|
|
587
|
+
/** Longest host name or code worth naming in an error. */
|
|
588
|
+
const UPSTREAM_FIELD_MAX = 64
|
|
589
|
+
|
|
590
|
+
function upstreamField(value: unknown): string | undefined {
|
|
591
|
+
if (typeof value !== 'string' && typeof value !== 'number') return undefined
|
|
592
|
+
const text = String(value)
|
|
593
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control characters is the point
|
|
594
|
+
.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ')
|
|
595
|
+
.trim()
|
|
596
|
+
return text === '' ? undefined : text.slice(0, UPSTREAM_FIELD_MAX)
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* The refusing host and its code, read from an error object's `metadata`
|
|
601
|
+
* (`provider_name`, and `provider_code` on an HTTP error or `error_type` on a
|
|
602
|
+
* mid-stream one). `metadata.raw` is never read: it can echo prompt text.
|
|
603
|
+
*/
|
|
604
|
+
function upstreamNote(error: Record<string, unknown>, codeKey: string): string | undefined {
|
|
605
|
+
const meta = error.metadata
|
|
606
|
+
if (typeof meta !== 'object' || meta === null) return undefined
|
|
607
|
+
const m = meta as Record<string, unknown>
|
|
608
|
+
const host = upstreamField(m.provider_name)
|
|
609
|
+
const code = upstreamField(m[codeKey])
|
|
610
|
+
if (host === undefined && code === undefined) return undefined
|
|
611
|
+
return [host !== undefined ? `host ${host}` : '', code !== undefined ? `code ${code}` : '']
|
|
612
|
+
.filter(Boolean)
|
|
613
|
+
.join(', ')
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* A failed body with the refusing host named in its message. `metadata` stays
|
|
618
|
+
* in the body: the classifier reads the whole text (the upstream's own
|
|
619
|
+
* sentence about a full context window lives in `metadata.raw`), and the error
|
|
620
|
+
* the SDK builds carries only the message, type, code and param, never `raw`.
|
|
621
|
+
* Anything that is not a JSON object with an `error` object, or that
|
|
622
|
+
* names no host or code, comes back unchanged.
|
|
623
|
+
*/
|
|
624
|
+
function nameUpstream(body: string, parsed: unknown, codeKey: string): string {
|
|
625
|
+
if (typeof parsed !== 'object' || parsed === null) return body
|
|
626
|
+
const error = (parsed as { error?: unknown }).error
|
|
627
|
+
if (typeof error !== 'object' || error === null) return body
|
|
628
|
+
const note = upstreamNote(error as Record<string, unknown>, codeKey)
|
|
629
|
+
if (note === undefined) return body
|
|
630
|
+
const rest = error as Record<string, unknown>
|
|
631
|
+
const message = typeof rest.message === 'string' ? rest.message : ''
|
|
632
|
+
return JSON.stringify({
|
|
633
|
+
...(parsed as object),
|
|
634
|
+
error: { ...rest, message: message ? `${message} (${note})` : note },
|
|
635
|
+
})
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function parseJson(text: string): unknown {
|
|
639
|
+
try {
|
|
640
|
+
return JSON.parse(text)
|
|
641
|
+
} catch {
|
|
642
|
+
return undefined
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** A choice that makes the model call a tool: `required` or a named function. */
|
|
647
|
+
function isForcedToolChoice(tc: ToolChoice): boolean {
|
|
648
|
+
return tc !== 'auto' && tc !== 'none'
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Whether a 400 body is the vendor refusing the tool choice. The router passes
|
|
653
|
+
* the upstream sentence through ("Thinking mode does not support this
|
|
654
|
+
* tool_choice"). Only the error's message is read (the whole body when it is
|
|
655
|
+
* not JSON), and it must both name the field and say it is refused, so a 400
|
|
656
|
+
* that merely mentions `tool_choice` (an echo of the request, a schema error
|
|
657
|
+
* about another field) is not retried.
|
|
658
|
+
*/
|
|
659
|
+
function refusesToolChoice(errorBody: string, parsedBody: unknown): boolean {
|
|
660
|
+
let text = errorBody
|
|
661
|
+
const e = (parsedBody as { error?: { message?: unknown } | string } | null | undefined)?.error
|
|
662
|
+
const message = typeof e === 'string' ? e : e?.message
|
|
663
|
+
if (typeof message === 'string') text = message
|
|
664
|
+
return (
|
|
665
|
+
/tool_choice/i.test(text) &&
|
|
666
|
+
/(not\s+support|unsupported|not\s+supported|not\s+allowed|cannot|can't|only\s+support|invalid)/i.test(
|
|
667
|
+
text,
|
|
668
|
+
)
|
|
669
|
+
)
|
|
670
|
+
}
|
|
671
|
+
|
|
556
672
|
function formatToolChoice(tc: ToolChoice): unknown {
|
|
557
673
|
if (typeof tc === 'string') return tc
|
|
558
674
|
return tc
|
|
@@ -578,6 +694,59 @@ export const OPENROUTER_CAPABILITIES: ProviderCapabilities = {
|
|
|
578
694
|
reportsRequestCost: true,
|
|
579
695
|
}
|
|
580
696
|
|
|
697
|
+
/**
|
|
698
|
+
* How long a read of the `/models` listing may take. The listing is several
|
|
699
|
+
* hundred entries and normally answers well inside a second; 5 s is long
|
|
700
|
+
* enough for a slow link and short enough that the first `max` request, which
|
|
701
|
+
* waits on this read, does not feel stuck. It is a bound on waiting, not a
|
|
702
|
+
* retry: past it the listing counts as absent and each reader's documented
|
|
703
|
+
* fallback applies.
|
|
704
|
+
*/
|
|
705
|
+
export const MODEL_LISTING_TIMEOUT_MS = 5000
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Run `read` with a signal that fires at the listing bound or when the
|
|
709
|
+
* caller's signal does. The bound is an ordinary timer, cleared when the read
|
|
710
|
+
* settles, so a test can advance it with a fake clock.
|
|
711
|
+
*/
|
|
712
|
+
async function withListingBound<T>(
|
|
713
|
+
signal: AbortSignal | undefined,
|
|
714
|
+
read: (bounded: AbortSignal) => Promise<T>,
|
|
715
|
+
): Promise<T> {
|
|
716
|
+
const bound = new AbortController()
|
|
717
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
718
|
+
// Rejects at the bound even when the transport ignores its signal.
|
|
719
|
+
const expired = new Promise<never>((_, reject) => {
|
|
720
|
+
timer = setTimeout(() => {
|
|
721
|
+
const reason = new DOMException('the models listing did not answer in time', 'TimeoutError')
|
|
722
|
+
bound.abort(reason)
|
|
723
|
+
reject(reason)
|
|
724
|
+
}, MODEL_LISTING_TIMEOUT_MS)
|
|
725
|
+
})
|
|
726
|
+
let onAbort: (() => void) | undefined
|
|
727
|
+
// The caller's abort also ends the wait, whether or not the transport honours it.
|
|
728
|
+
const cancelled = new Promise<never>((_, reject) => {
|
|
729
|
+
if (!signal) return
|
|
730
|
+
onAbort = () => reject(signal.reason ?? new DOMException('aborted', 'AbortError'))
|
|
731
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
732
|
+
})
|
|
733
|
+
try {
|
|
734
|
+
return await Promise.race([
|
|
735
|
+
read(signal ? AbortSignal.any([bound.signal, signal]) : bound.signal),
|
|
736
|
+
expired,
|
|
737
|
+
cancelled,
|
|
738
|
+
])
|
|
739
|
+
} finally {
|
|
740
|
+
if (onAbort) signal?.removeEventListener('abort', onAbort)
|
|
741
|
+
clearTimeout(timer)
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** Did the listing read run past its bound (as opposed to failing some other way)? */
|
|
746
|
+
function isListingTimeout(err: unknown): boolean {
|
|
747
|
+
return err instanceof Error && err.name === 'TimeoutError'
|
|
748
|
+
}
|
|
749
|
+
|
|
581
750
|
export class OpenRouterProvider implements LLMProvider {
|
|
582
751
|
readonly id = 'openrouter'
|
|
583
752
|
readonly name = 'OpenRouter'
|
|
@@ -585,6 +754,7 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
585
754
|
|
|
586
755
|
private config: OpenRouterConfig
|
|
587
756
|
private baseUrl: string
|
|
757
|
+
private logger: Logger
|
|
588
758
|
|
|
589
759
|
constructor(config: OpenRouterConfig) {
|
|
590
760
|
if (!config.apiKey) {
|
|
@@ -592,6 +762,7 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
592
762
|
}
|
|
593
763
|
this.config = config
|
|
594
764
|
this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL
|
|
765
|
+
this.logger = config.logger ?? NOOP_LOGGER
|
|
595
766
|
}
|
|
596
767
|
|
|
597
768
|
/**
|
|
@@ -600,14 +771,19 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
600
771
|
* the DeepSeek models whose own API refuses it while they reason, and
|
|
601
772
|
* reasoning is on for them unless thinking is disabled or effort is `none`
|
|
602
773
|
* (the same rule the DeepSeek driver applies). The kernel asks first and,
|
|
603
|
-
* on `false`, keeps the step at low effort and asks in words.
|
|
604
|
-
*
|
|
605
|
-
*
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
774
|
+
* on `false`, keeps the step at low effort and asks in words.
|
|
775
|
+
*
|
|
776
|
+
* The vendor's refusal is not what every route returns. On the live route a
|
|
777
|
+
* forced choice with reasoning on was served (HTTP 200) by five different
|
|
778
|
+
* upstream hosts, and when the request was pinned to the vendor's own host
|
|
779
|
+
* the router answered its own 404 "no endpoints" (its tool-compatibility
|
|
780
|
+
* filter drops that host for a forced choice). Yet a real session got the
|
|
781
|
+
* vendor's own 400 "Thinking mode does not support this tool_choice" from
|
|
782
|
+
* some host. So this driver acts on both facts: where this answer is
|
|
783
|
+
* `false` the forced choice is not put on the wire, and a request that did
|
|
784
|
+
* carry one and drew a 400 naming `tool_choice` is sent once more without
|
|
785
|
+
* it. A host that accepts the choice keeps getting it; only a host that
|
|
786
|
+
* rejects it costs a second request.
|
|
611
787
|
*/
|
|
612
788
|
acceptsForcedToolChoiceFor(
|
|
613
789
|
model: string,
|
|
@@ -681,7 +857,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
681
857
|
})
|
|
682
858
|
}
|
|
683
859
|
|
|
684
|
-
private buildRequestBody(
|
|
860
|
+
private buildRequestBody(
|
|
861
|
+
params: ChatCompletionParams,
|
|
862
|
+
stream: boolean,
|
|
863
|
+
supportedEfforts?: readonly string[],
|
|
864
|
+
): Record<string, unknown> {
|
|
685
865
|
const body: Record<string, unknown> = {
|
|
686
866
|
model: params.model,
|
|
687
867
|
messages: this.formatMessages(params.messages, routeOf(params)),
|
|
@@ -692,7 +872,19 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
692
872
|
body.tools = params.tools
|
|
693
873
|
}
|
|
694
874
|
if (params.toolChoice !== undefined) {
|
|
695
|
-
|
|
875
|
+
if (
|
|
876
|
+
isForcedToolChoice(params.toolChoice) &&
|
|
877
|
+
!this.acceptsForcedToolChoiceFor(params.model, params.thinking, params.effort)
|
|
878
|
+
) {
|
|
879
|
+
// The model's vendor refuses a forced choice while it reasons. Not
|
|
880
|
+
// sending it costs the caller nothing it could have had: the step
|
|
881
|
+
// goes out with the choice left to the model.
|
|
882
|
+
this.logger.debug('openrouter: forced tool_choice not sent, the model refuses it here', {
|
|
883
|
+
'namzu.model': params.model,
|
|
884
|
+
})
|
|
885
|
+
} else {
|
|
886
|
+
body.tool_choice = formatToolChoice(params.toolChoice)
|
|
887
|
+
}
|
|
696
888
|
}
|
|
697
889
|
if (params.parallelToolCalls !== undefined) {
|
|
698
890
|
body.parallel_tool_calls = params.parallelToolCalls
|
|
@@ -711,9 +903,13 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
711
903
|
applyCacheBreakpoints(params.messages, body.messages as { content?: unknown }[])
|
|
712
904
|
}
|
|
713
905
|
|
|
714
|
-
//
|
|
715
|
-
//
|
|
716
|
-
const reasoning = formatReasoning(
|
|
906
|
+
// `max` and `ultra` resolve against the model's own list — see
|
|
907
|
+
// `carriedEffort`.
|
|
908
|
+
const reasoning = formatReasoning(
|
|
909
|
+
params.thinking,
|
|
910
|
+
params.effort !== undefined ? carriedEffort(params.effort, supportedEfforts) : undefined,
|
|
911
|
+
params.maxTokens,
|
|
912
|
+
)
|
|
717
913
|
if (reasoning !== undefined) {
|
|
718
914
|
body.reasoning = reasoning
|
|
719
915
|
}
|
|
@@ -726,7 +922,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
726
922
|
}
|
|
727
923
|
|
|
728
924
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
729
|
-
const
|
|
925
|
+
const supportedEfforts =
|
|
926
|
+
params.effort === 'max' || params.effort === 'ultra'
|
|
927
|
+
? await this.resolveSupportedEfforts(params.model, params.signal)
|
|
928
|
+
: undefined
|
|
929
|
+
const body = this.buildRequestBody(params, true, supportedEfforts)
|
|
730
930
|
|
|
731
931
|
const timeout = AbortSignal.timeout(this.config.timeout ?? 120_000)
|
|
732
932
|
// Compose the caller abort with the request timeout so a Stop cancels the
|
|
@@ -734,33 +934,55 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
734
934
|
// prior `AbortSignal.timeout(...)` expression (byte-identical).
|
|
735
935
|
const signal = params.signal ? AbortSignal.any([timeout, params.signal]) : timeout
|
|
736
936
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
937
|
+
const send = async (payload: Record<string, unknown>): Promise<Response> => {
|
|
938
|
+
try {
|
|
939
|
+
return await fetch(`${this.baseUrl}/chat/completions`, {
|
|
940
|
+
method: 'POST',
|
|
941
|
+
headers: this.getHeaders(),
|
|
942
|
+
body: JSON.stringify(payload),
|
|
943
|
+
signal,
|
|
944
|
+
})
|
|
945
|
+
} catch (err) {
|
|
946
|
+
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
947
|
+
throw providerVendorError({ providerId: 'openrouter', error: err })
|
|
948
|
+
}
|
|
748
949
|
}
|
|
749
950
|
|
|
951
|
+
let response = await send(body)
|
|
952
|
+
|
|
750
953
|
if (!response.ok) {
|
|
751
954
|
// The body is read to CLASSIFY (a 400 saying "prompt is too long" is a
|
|
752
955
|
// context overflow, any other 400 is a bad request) and then dropped. It
|
|
753
956
|
// used to be interpolated straight into the message, which is how a
|
|
754
957
|
// credential the upstream echoed back reached every log that recorded
|
|
755
958
|
// the failure — proven with a planted fake token.
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
959
|
+
let errorBody = await response.text().catch(() => '')
|
|
960
|
+
const sentForced =
|
|
961
|
+
body.tool_choice !== undefined && isForcedToolChoice(body.tool_choice as ToolChoice)
|
|
962
|
+
if (
|
|
963
|
+
response.status === 400 &&
|
|
964
|
+
sentForced &&
|
|
965
|
+
refusesToolChoice(errorBody, parseJson(errorBody))
|
|
966
|
+
) {
|
|
967
|
+
// This host refuses a forced choice. Ask once more without it; the
|
|
968
|
+
// model decides whether to call a tool. Anything the second attempt
|
|
969
|
+
// answers is final.
|
|
970
|
+
this.logger.debug('openrouter: a 400 named tool_choice, sending once more without it', {
|
|
971
|
+
'namzu.model': params.model,
|
|
972
|
+
})
|
|
973
|
+
const { tool_choice: _dropped, ...withoutChoice } = body
|
|
974
|
+
response = await send(withoutChoice)
|
|
975
|
+
if (!response.ok) errorBody = await response.text().catch(() => '')
|
|
976
|
+
}
|
|
977
|
+
if (!response.ok) {
|
|
978
|
+
throw providerHttpError({
|
|
979
|
+
providerId: 'openrouter',
|
|
980
|
+
status: response.status,
|
|
981
|
+
body: nameUpstream(errorBody, parseJson(errorBody), 'provider_code'),
|
|
982
|
+
retryAfter: response.headers.get('retry-after'),
|
|
983
|
+
shouldRetry: response.headers.get('x-should-retry'),
|
|
984
|
+
})
|
|
985
|
+
}
|
|
764
986
|
}
|
|
765
987
|
|
|
766
988
|
if (!response.body) {
|
|
@@ -839,7 +1061,7 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
839
1061
|
if (parsed.error !== undefined) {
|
|
840
1062
|
throw providerVendorError({
|
|
841
1063
|
providerId: 'openrouter',
|
|
842
|
-
error: new Error(data),
|
|
1064
|
+
error: new Error(nameUpstream(data, parsed, 'error_type')),
|
|
843
1065
|
})
|
|
844
1066
|
}
|
|
845
1067
|
|
|
@@ -987,7 +1209,16 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
987
1209
|
if (signal?.aborted) return undefined
|
|
988
1210
|
let windows = this.contextWindows
|
|
989
1211
|
if (!windows) {
|
|
990
|
-
|
|
1212
|
+
let models: ModelInfo[]
|
|
1213
|
+
try {
|
|
1214
|
+
models = await this.listModels(signal)
|
|
1215
|
+
} catch (err) {
|
|
1216
|
+
// A listing that outlasts its bound is "no listing": the
|
|
1217
|
+
// caller's static table answers. A caller abort stays an abort.
|
|
1218
|
+
if (signal?.aborted) return undefined
|
|
1219
|
+
if (isListingTimeout(err)) return undefined
|
|
1220
|
+
throw err
|
|
1221
|
+
}
|
|
991
1222
|
if (signal?.aborted) return undefined
|
|
992
1223
|
windows = new Map<string, number>(
|
|
993
1224
|
models
|
|
@@ -1011,29 +1242,80 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1011
1242
|
return typeof reported === 'number' && reported > 0 ? reported : undefined
|
|
1012
1243
|
}
|
|
1013
1244
|
|
|
1245
|
+
/**
|
|
1246
|
+
* The reasoning levels the listing names for `model` (`reasoning.supported_efforts`),
|
|
1247
|
+
* or `undefined` when the listing cannot be read or names none. Read only
|
|
1248
|
+
* for a `max` or `ultra` request, and kept for this driver once fulfilled; a
|
|
1249
|
+
* failure is not kept. A caller abort still propagates.
|
|
1250
|
+
*/
|
|
1251
|
+
private async resolveSupportedEfforts(
|
|
1252
|
+
model: string,
|
|
1253
|
+
signal?: AbortSignal,
|
|
1254
|
+
): Promise<readonly string[] | undefined> {
|
|
1255
|
+
let table = this.supportedEfforts
|
|
1256
|
+
if (!table) {
|
|
1257
|
+
try {
|
|
1258
|
+
signal?.throwIfAborted()
|
|
1259
|
+
// Bounded on its own: this read sits in front of the first max or
|
|
1260
|
+
// ultra request, so a stalled listing must not stall that request.
|
|
1261
|
+
const data = await withListingBound(signal, async (bounded) => {
|
|
1262
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1263
|
+
headers: this.getHeaders(),
|
|
1264
|
+
signal: bounded,
|
|
1265
|
+
})
|
|
1266
|
+
if (!response.ok) return undefined
|
|
1267
|
+
return (await response.json()) as {
|
|
1268
|
+
data?: Array<{ id: string; reasoning?: { supported_efforts?: unknown } }>
|
|
1269
|
+
}
|
|
1270
|
+
})
|
|
1271
|
+
if (!data) return undefined
|
|
1272
|
+
table = new Map()
|
|
1273
|
+
for (const m of data.data ?? []) {
|
|
1274
|
+
const levels = m.reasoning?.supported_efforts
|
|
1275
|
+
if (Array.isArray(levels)) {
|
|
1276
|
+
table.set(
|
|
1277
|
+
m.id,
|
|
1278
|
+
levels.filter((l): l is string => typeof l === 'string'),
|
|
1279
|
+
)
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
this.supportedEfforts = table
|
|
1283
|
+
} catch (err) {
|
|
1284
|
+
if (signal?.aborted) throw signal.reason ?? err
|
|
1285
|
+
return undefined
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
const tag = model.indexOf(':')
|
|
1289
|
+
return table.get(model) ?? (tag > 0 ? table.get(model.slice(0, tag)) : undefined)
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
private supportedEfforts?: Map<string, string[]>
|
|
1293
|
+
|
|
1014
1294
|
/** First fulfilled listing; see the note on `resolveContextWindow`. */
|
|
1015
1295
|
private contextWindows?: Map<string, number>
|
|
1016
1296
|
|
|
1017
1297
|
async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
|
|
1018
1298
|
signal?.throwIfAborted()
|
|
1019
|
-
const
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1299
|
+
const data = await withListingBound(signal, async (bounded) => {
|
|
1300
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1301
|
+
headers: this.getHeaders(),
|
|
1302
|
+
signal: bounded,
|
|
1303
|
+
})
|
|
1023
1304
|
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1305
|
+
if (!response.ok) {
|
|
1306
|
+
throw new Error(`Failed to list models: ${response.status}`)
|
|
1307
|
+
}
|
|
1027
1308
|
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1309
|
+
return (await response.json()) as {
|
|
1310
|
+
data: Array<{
|
|
1311
|
+
id: string
|
|
1312
|
+
name: string
|
|
1313
|
+
context_length: number
|
|
1314
|
+
top_provider?: { max_completion_tokens?: number }
|
|
1315
|
+
pricing?: { prompt: string; completion: string }
|
|
1316
|
+
}>
|
|
1317
|
+
}
|
|
1318
|
+
})
|
|
1037
1319
|
signal?.throwIfAborted()
|
|
1038
1320
|
|
|
1039
1321
|
return data.data.map((m) => {
|
|
@@ -1054,11 +1336,13 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1054
1336
|
|
|
1055
1337
|
async healthCheck(): Promise<boolean> {
|
|
1056
1338
|
try {
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1339
|
+
return await withListingBound(undefined, async (bounded) => {
|
|
1340
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1341
|
+
headers: this.getHeaders(),
|
|
1342
|
+
signal: bounded,
|
|
1343
|
+
})
|
|
1344
|
+
return response.ok
|
|
1060
1345
|
})
|
|
1061
|
-
return response.ok
|
|
1062
1346
|
} catch {
|
|
1063
1347
|
return false
|
|
1064
1348
|
}
|
package/src/types.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface OpenRouterConfig {
|
|
|
14
14
|
siteUrl?: string
|
|
15
15
|
siteName?: string
|
|
16
16
|
timeout?: number
|
|
17
|
+
/** Receives the driver's debug lines. Absent, they are discarded. */
|
|
18
|
+
logger?: import('@namzu/sdk').Logger
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export interface OpenRouterProviderConfig extends OpenRouterConfig {
|