@namzu/openrouter 3.1.2 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +17 -0
- package/dist/client.d.ts +31 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +464 -50
- 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 +542 -52
- package/src/types.ts +2 -0
package/src/client.ts
CHANGED
|
@@ -3,7 +3,11 @@ import type {
|
|
|
3
3
|
LLMProvider,
|
|
4
4
|
ModelInfo,
|
|
5
5
|
ProviderCapabilities,
|
|
6
|
+
ProviderRoute,
|
|
7
|
+
ReasoningBlock,
|
|
8
|
+
ReasoningEffort,
|
|
6
9
|
StreamChunk,
|
|
10
|
+
ThinkingConfig,
|
|
7
11
|
TokenUsage,
|
|
8
12
|
ToolChoice,
|
|
9
13
|
} from '@namzu/sdk'
|
|
@@ -15,6 +19,8 @@ import {
|
|
|
15
19
|
providerVendorError,
|
|
16
20
|
} from '@namzu/sdk'
|
|
17
21
|
import { attributionHeaders } from '@namzu/sdk'
|
|
22
|
+
import type { Logger } from '@namzu/sdk'
|
|
23
|
+
import { NOOP_LOGGER } from '@namzu/sdk'
|
|
18
24
|
import type { OpenRouterConfig } from './types.js'
|
|
19
25
|
|
|
20
26
|
/**
|
|
@@ -172,6 +178,10 @@ function applyCacheBreakpoints(
|
|
|
172
178
|
}
|
|
173
179
|
}
|
|
174
180
|
|
|
181
|
+
function routeOf(params: ChatCompletionParams): ProviderRoute {
|
|
182
|
+
return params.providerRoute ?? { providerId: 'openrouter', model: params.model, chainIndex: 0 }
|
|
183
|
+
}
|
|
184
|
+
|
|
175
185
|
const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? 'https://openrouter.ai/api/v1'
|
|
176
186
|
|
|
177
187
|
/**
|
|
@@ -200,6 +210,8 @@ interface RawUsage {
|
|
|
200
210
|
total_tokens: number
|
|
201
211
|
prompt_tokens_details?: {
|
|
202
212
|
cached_tokens?: number
|
|
213
|
+
/** Tokens written to an explicit cache; OpenRouter documents it for models with explicit caching. */
|
|
214
|
+
cache_write_tokens?: number
|
|
203
215
|
}
|
|
204
216
|
completion_tokens_details?: {
|
|
205
217
|
reasoning_tokens?: number
|
|
@@ -207,6 +219,32 @@ interface RawUsage {
|
|
|
207
219
|
cache_discount?: number
|
|
208
220
|
cache_read_input_tokens?: number
|
|
209
221
|
cache_creation_input_tokens?: number
|
|
222
|
+
/** USD charged to the account for this request. Present on every response. */
|
|
223
|
+
cost?: number | null
|
|
224
|
+
/** Bring-your-own-key: the upstream bills the caller directly, `cost` is only OpenRouter's part. */
|
|
225
|
+
is_byok?: boolean
|
|
226
|
+
cost_details?: { upstream_inference_cost?: number | null }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* What the request cost, as OpenRouter reports it, or `undefined`.
|
|
231
|
+
*
|
|
232
|
+
* `usage.cost` is "the total charged to your account", on every response
|
|
233
|
+
* without being asked (the documented `usage: { include: true }` is now a
|
|
234
|
+
* no-op, so this driver does not send it). A request on the caller's own
|
|
235
|
+
* upstream key (BYOK) is billed twice over: the upstream bills the caller
|
|
236
|
+
* directly and `cost` is only OpenRouter's share, so the upstream figure the
|
|
237
|
+
* response also carries is added, or the report would understate what the
|
|
238
|
+
* person spent. A missing, null or non-numeric `cost` is "not reported", never
|
|
239
|
+
* zero; a reported `0` (a free model) is a real zero.
|
|
240
|
+
*/
|
|
241
|
+
function reportedCost(raw: RawUsage): number | undefined {
|
|
242
|
+
const charged = raw.cost
|
|
243
|
+
if (typeof charged !== 'number' || !Number.isFinite(charged) || charged < 0) return undefined
|
|
244
|
+
const upstream = raw.cost_details?.upstream_inference_cost
|
|
245
|
+
return raw.is_byok === true && typeof upstream === 'number' && Number.isFinite(upstream)
|
|
246
|
+
? charged + Math.max(0, upstream)
|
|
247
|
+
: charged
|
|
210
248
|
}
|
|
211
249
|
|
|
212
250
|
/**
|
|
@@ -230,13 +268,16 @@ function parseUsage(raw?: RawUsage): TokenUsage {
|
|
|
230
268
|
}
|
|
231
269
|
}
|
|
232
270
|
const reasoningTokens = raw.completion_tokens_details?.reasoning_tokens
|
|
271
|
+
const cost = reportedCost(raw)
|
|
233
272
|
return {
|
|
234
273
|
promptTokens: raw.prompt_tokens,
|
|
235
274
|
completionTokens: raw.completion_tokens,
|
|
236
275
|
totalTokens: raw.total_tokens,
|
|
237
276
|
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
|
|
238
|
-
cacheWriteTokens:
|
|
277
|
+
cacheWriteTokens:
|
|
278
|
+
raw.cache_creation_input_tokens ?? raw.prompt_tokens_details?.cache_write_tokens ?? 0,
|
|
239
279
|
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
|
|
280
|
+
...(cost !== undefined ? { reportedCostUsd: cost } : {}),
|
|
240
281
|
}
|
|
241
282
|
}
|
|
242
283
|
|
|
@@ -297,14 +338,224 @@ function parseReasoning(
|
|
|
297
338
|
}
|
|
298
339
|
|
|
299
340
|
/**
|
|
300
|
-
*
|
|
341
|
+
* Adapter-private state for one completed reasoning response.
|
|
342
|
+
*
|
|
343
|
+
* OpenRouter's guide for reasoning across tool calls says to send the
|
|
344
|
+
* assistant message back with its `reasoning_details` unmodified: the whole
|
|
345
|
+
* sequence of blocks, in the order the model produced it. The kernel's own
|
|
346
|
+
* reasoning blocks keep the text, signature and encrypted payload but not the
|
|
347
|
+
* rest of each entry (its `format`, `id`, summary form), so the entries as the
|
|
348
|
+
* wire sent them are kept here, in the message's source, and the route is
|
|
349
|
+
* repeated inside so the state is used only by the member that produced it.
|
|
350
|
+
*
|
|
351
|
+
* `reasoning` is the flat string of a route that sent no `reasoning_details`.
|
|
352
|
+
*/
|
|
353
|
+
interface OpenRouterReplayState {
|
|
354
|
+
readonly kind: 'namzu-openrouter-reasoning'
|
|
355
|
+
readonly version: 1
|
|
356
|
+
readonly route: ProviderRoute
|
|
357
|
+
readonly details?: readonly Record<string, unknown>[]
|
|
358
|
+
readonly reasoning?: string
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function sameRoute(left: ProviderRoute, right: ProviderRoute): boolean {
|
|
362
|
+
return (
|
|
363
|
+
left.providerId === right.providerId &&
|
|
364
|
+
left.model === right.model &&
|
|
365
|
+
left.chainIndex === right.chainIndex
|
|
366
|
+
)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function isReplayState(value: unknown): value is OpenRouterReplayState {
|
|
370
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
371
|
+
const state = value as Record<string, unknown>
|
|
372
|
+
const route = state.route as Record<string, unknown> | null | undefined
|
|
373
|
+
if (
|
|
374
|
+
state.kind !== 'namzu-openrouter-reasoning' ||
|
|
375
|
+
state.version !== 1 ||
|
|
376
|
+
typeof route !== 'object' ||
|
|
377
|
+
route === null ||
|
|
378
|
+
typeof route.providerId !== 'string' ||
|
|
379
|
+
typeof route.model !== 'string' ||
|
|
380
|
+
!Number.isSafeInteger(route.chainIndex)
|
|
381
|
+
) {
|
|
382
|
+
return false
|
|
383
|
+
}
|
|
384
|
+
const hasDetails =
|
|
385
|
+
Array.isArray(state.details) &&
|
|
386
|
+
state.details.length > 0 &&
|
|
387
|
+
state.details.every((d) => typeof d === 'object' && d !== null && !Array.isArray(d))
|
|
388
|
+
const hasFlat = typeof state.reasoning === 'string' && state.reasoning.length > 0
|
|
389
|
+
return hasDetails !== hasFlat
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Fold the `reasoning_details` fragments of a stream into the entries the
|
|
394
|
+
* complete response held: fragments of one `index` are one entry, its text
|
|
395
|
+
* (or summary, or encrypted data) concatenated in arrival order, every other
|
|
396
|
+
* field kept as first sent and a signature kept when one arrives.
|
|
397
|
+
*/
|
|
398
|
+
class ReasoningDetailsAccumulator {
|
|
399
|
+
private readonly entries = new Map<number, Record<string, unknown>>()
|
|
400
|
+
private flat = ''
|
|
401
|
+
|
|
402
|
+
addFlat(text: string | null | undefined): void {
|
|
403
|
+
if (typeof text === 'string') this.flat += text
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
add(fragments: readonly RawReasoningDetail[] | undefined): void {
|
|
407
|
+
for (const [position, fragment] of (fragments ?? []).entries()) {
|
|
408
|
+
if (typeof fragment !== 'object' || fragment === null) continue
|
|
409
|
+
const raw = fragment as Record<string, unknown>
|
|
410
|
+
const index = typeof raw.index === 'number' ? raw.index : position
|
|
411
|
+
const entry = this.entries.get(index)
|
|
412
|
+
if (!entry) {
|
|
413
|
+
this.entries.set(index, { ...raw })
|
|
414
|
+
continue
|
|
415
|
+
}
|
|
416
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
417
|
+
if (key === 'text' || key === 'summary' || key === 'data') {
|
|
418
|
+
if (typeof value === 'string') {
|
|
419
|
+
entry[key] = (typeof entry[key] === 'string' ? entry[key] : '') + value
|
|
420
|
+
}
|
|
421
|
+
} else if (key === 'signature') {
|
|
422
|
+
if (typeof value === 'string' && value.length > 0) entry[key] = value
|
|
423
|
+
} else if (entry[key] === undefined) {
|
|
424
|
+
entry[key] = value
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
get hasAny(): boolean {
|
|
431
|
+
return this.entries.size > 0 || this.flat.length > 0
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
state(route: ProviderRoute): OpenRouterReplayState | undefined {
|
|
435
|
+
if (this.entries.size > 0) {
|
|
436
|
+
const details = [...this.entries.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => v)
|
|
437
|
+
return { kind: 'namzu-openrouter-reasoning', version: 1, route, details }
|
|
438
|
+
}
|
|
439
|
+
return this.flat.length > 0
|
|
440
|
+
? { kind: 'namzu-openrouter-reasoning', version: 1, route, reasoning: this.flat }
|
|
441
|
+
: undefined
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** The text and the opaque payloads the kernel's own blocks would hold for a state. */
|
|
446
|
+
function durableFingerprint(state: OpenRouterReplayState): string {
|
|
447
|
+
if (state.details === undefined) return JSON.stringify([state.reasoning, ''])
|
|
448
|
+
let text = ''
|
|
449
|
+
let encrypted = ''
|
|
450
|
+
for (const d of state.details) {
|
|
451
|
+
if (d.type === 'reasoning.encrypted') {
|
|
452
|
+
if (typeof d.data === 'string') encrypted += d.data
|
|
453
|
+
} else if (typeof d.text === 'string') {
|
|
454
|
+
text += d.text
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return JSON.stringify([text, encrypted])
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function blocksFingerprint(blocks: readonly ReasoningBlock[] | undefined): string {
|
|
461
|
+
let text = ''
|
|
462
|
+
let encrypted = ''
|
|
463
|
+
for (const b of blocks ?? []) {
|
|
464
|
+
if (b.type === 'redacted_thinking') encrypted += b.encrypted ?? ''
|
|
465
|
+
else text += b.text ?? ''
|
|
466
|
+
}
|
|
467
|
+
return JSON.stringify([text, encrypted])
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The reasoning to send back with an assistant message, or nothing.
|
|
472
|
+
*
|
|
473
|
+
* Only from a validated envelope of the same route whose content still matches
|
|
474
|
+
* the stored reasoning (request repair or compaction that rewrote the blocks
|
|
475
|
+
* leaves the envelope behind, and a mismatch means history-neutral). Names
|
|
476
|
+
* alone never prove it.
|
|
477
|
+
*/
|
|
478
|
+
function replayFor(
|
|
479
|
+
message: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
|
|
480
|
+
target: ProviderRoute,
|
|
481
|
+
): { reasoning_details: readonly Record<string, unknown>[] } | { reasoning: string } | undefined {
|
|
482
|
+
const source = message.source
|
|
483
|
+
if (!source || source.type !== 'model' || !sameRoute(source, target)) return undefined
|
|
484
|
+
const state = source.replayState
|
|
485
|
+
if (!isReplayState(state) || !sameRoute(state.route, target)) return undefined
|
|
486
|
+
if (durableFingerprint(state) !== blocksFingerprint(message.reasoning)) return undefined
|
|
487
|
+
return state.details !== undefined
|
|
488
|
+
? { reasoning_details: state.details }
|
|
489
|
+
: { reasoning: state.reasoning as string }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Index of the first message of the current turn: the last user message that
|
|
494
|
+
* is not host-generated context. Reasoning is sent back for the assistant
|
|
495
|
+
* messages from there on, which is what the guide asks for between a tool
|
|
496
|
+
* call and the model's next step; an earlier turn is history and is not
|
|
497
|
+
* resent. Answers 0 when the conversation holds no such user message.
|
|
498
|
+
*/
|
|
499
|
+
function currentTurnStart(messages: ChatCompletionParams['messages']): number {
|
|
500
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
501
|
+
const msg = messages[i]
|
|
502
|
+
if (msg?.role === 'user' && msg.source?.type !== 'runtime-context') return i
|
|
503
|
+
}
|
|
504
|
+
return 0
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Whether a model is one whose vendor refuses a forced tool choice while it
|
|
509
|
+
* reasons: the DeepSeek V4 generation and its reasoner line. Its own API
|
|
510
|
+
* answers 400 "Thinking mode does not support this tool_choice". Matched on
|
|
511
|
+
* the id's bare name (a `deepseek/` prefix, an OpenRouter `~` alias marker and a
|
|
512
|
+
* `:tag` removed), never by substring, so a derivative is not swept in.
|
|
513
|
+
*/
|
|
514
|
+
function refusesForcedChoiceWhileReasoning(model: string): boolean {
|
|
515
|
+
const afterSlash = model.replace(/^~/, '').toLowerCase()
|
|
516
|
+
const bare = afterSlash.slice(afterSlash.lastIndexOf('/') + 1).split(':')[0] ?? ''
|
|
517
|
+
return /^deepseek-(v([4-9]|\d{2,})(\.|-|$)|r\d+(-|$)|reasoner(-|$)|(flash|pro)(-|$))/.test(bare)
|
|
518
|
+
}
|
|
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
|
+
|
|
523
|
+
/**
|
|
524
|
+
* The level that stands in for an SDK effort the wire may not carry.
|
|
301
525
|
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
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.
|
|
534
|
+
*/
|
|
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.
|
|
306
552
|
*/
|
|
307
|
-
|
|
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
|
+
}
|
|
308
559
|
|
|
309
560
|
/**
|
|
310
561
|
* Map the SDK's thinking controls onto OpenRouter's unified `reasoning` object.
|
|
@@ -314,29 +565,110 @@ const OPENROUTER_REASONING_EFFORT = ['none', 'minimal', 'low', 'medium', 'high',
|
|
|
314
565
|
*/
|
|
315
566
|
function formatReasoning(
|
|
316
567
|
thinking: ChatCompletionParams['thinking'],
|
|
317
|
-
effort:
|
|
568
|
+
effort: string | undefined,
|
|
569
|
+
maxTokens?: number,
|
|
318
570
|
): Record<string, unknown> | undefined {
|
|
319
|
-
if (effort !== undefined) {
|
|
320
|
-
const carried = (OPENROUTER_REASONING_EFFORT as readonly string[]).includes(effort)
|
|
321
|
-
if (!carried) {
|
|
322
|
-
throw new Error(
|
|
323
|
-
`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.`,
|
|
324
|
-
)
|
|
325
|
-
}
|
|
326
|
-
return { effort }
|
|
327
|
-
}
|
|
571
|
+
if (effort !== undefined) return { effort }
|
|
328
572
|
if (!thinking || thinking.type === undefined) return undefined
|
|
329
573
|
if (thinking.type === 'disabled') return { enabled: false }
|
|
330
574
|
// 'adaptive' has no separate spelling on this wire: the model decides its
|
|
331
575
|
// own depth, which is what `enabled: true` without a budget expresses.
|
|
332
576
|
// 'enabled' fixes the depth with budgetTokens, so it carries the cap.
|
|
333
|
-
const budgetTokens =
|
|
577
|
+
const budgetTokens = fitBudget(
|
|
578
|
+
thinking.type === 'enabled' ? thinking.budgetTokens : undefined,
|
|
579
|
+
maxTokens,
|
|
580
|
+
)
|
|
334
581
|
return {
|
|
335
582
|
enabled: true,
|
|
336
583
|
...(budgetTokens !== undefined ? { max_tokens: budgetTokens } : {}),
|
|
337
584
|
}
|
|
338
585
|
}
|
|
339
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
|
+
|
|
340
672
|
function formatToolChoice(tc: ToolChoice): unknown {
|
|
341
673
|
if (typeof tc === 'string') return tc
|
|
342
674
|
return tc
|
|
@@ -358,6 +690,8 @@ export const OPENROUTER_CAPABILITIES: ProviderCapabilities = {
|
|
|
358
690
|
supportsDocuments: false,
|
|
359
691
|
supportsToolResultImages: false,
|
|
360
692
|
supportsToolResultDocuments: false,
|
|
693
|
+
// OpenRouter states the charge on every response (`usage.cost`).
|
|
694
|
+
reportsRequestCost: true,
|
|
361
695
|
}
|
|
362
696
|
|
|
363
697
|
export class OpenRouterProvider implements LLMProvider {
|
|
@@ -367,6 +701,7 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
367
701
|
|
|
368
702
|
private config: OpenRouterConfig
|
|
369
703
|
private baseUrl: string
|
|
704
|
+
private logger: Logger
|
|
370
705
|
|
|
371
706
|
constructor(config: OpenRouterConfig) {
|
|
372
707
|
if (!config.apiKey) {
|
|
@@ -374,6 +709,36 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
374
709
|
}
|
|
375
710
|
this.config = config
|
|
376
711
|
this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL
|
|
712
|
+
this.logger = config.logger ?? NOOP_LOGGER
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Whether a forced tool choice (`required` or a named function) is taken
|
|
717
|
+
* under the thinking configuration the request will carry. `false` only for
|
|
718
|
+
* the DeepSeek models whose own API refuses it while they reason, and
|
|
719
|
+
* reasoning is on for them unless thinking is disabled or effort is `none`
|
|
720
|
+
* (the same rule the DeepSeek driver applies). The kernel asks first and,
|
|
721
|
+
* on `false`, keeps the step at low effort and asks in words.
|
|
722
|
+
*
|
|
723
|
+
* The vendor's refusal is not what every route returns. On the live route a
|
|
724
|
+
* forced choice with reasoning on was served (HTTP 200) by five different
|
|
725
|
+
* upstream hosts, and when the request was pinned to the vendor's own host
|
|
726
|
+
* the router answered its own 404 "no endpoints" (its tool-compatibility
|
|
727
|
+
* filter drops that host for a forced choice). Yet a real session got the
|
|
728
|
+
* vendor's own 400 "Thinking mode does not support this tool_choice" from
|
|
729
|
+
* some host. So this driver acts on both facts: where this answer is
|
|
730
|
+
* `false` the forced choice is not put on the wire, and a request that did
|
|
731
|
+
* carry one and drew a 400 naming `tool_choice` is sent once more without
|
|
732
|
+
* it. A host that accepts the choice keeps getting it; only a host that
|
|
733
|
+
* rejects it costs a second request.
|
|
734
|
+
*/
|
|
735
|
+
acceptsForcedToolChoiceFor(
|
|
736
|
+
model: string,
|
|
737
|
+
thinking?: ThinkingConfig,
|
|
738
|
+
effort?: ReasoningEffort,
|
|
739
|
+
): boolean {
|
|
740
|
+
if (!refusesForcedChoiceWhileReasoning(model)) return true
|
|
741
|
+
return thinking?.type === 'disabled' || effort === 'none'
|
|
377
742
|
}
|
|
378
743
|
|
|
379
744
|
private getHeaders(): Record<string, string> {
|
|
@@ -394,16 +759,23 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
394
759
|
return headers
|
|
395
760
|
}
|
|
396
761
|
|
|
397
|
-
private formatMessages(
|
|
762
|
+
private formatMessages(
|
|
763
|
+
messages: ChatCompletionParams['messages'],
|
|
764
|
+
route: ProviderRoute,
|
|
765
|
+
): unknown[] {
|
|
766
|
+
const turnStart = currentTurnStart(messages)
|
|
398
767
|
// An assistant entry with neither text nor a tool call (the model produced
|
|
399
768
|
// only reasoning, or was cut off) is rejected upstream with "content or
|
|
400
769
|
// tool_calls must be set". Leave it out; no filler is invented. An entry
|
|
401
770
|
// with tool calls is never dropped, so every tool result still follows the
|
|
402
771
|
// call it answers, and the stored history is untouched.
|
|
403
|
-
const sendable = messages
|
|
404
|
-
(msg) =>
|
|
405
|
-
|
|
406
|
-
|
|
772
|
+
const sendable = messages
|
|
773
|
+
.map((msg, index) => ({ msg, index }))
|
|
774
|
+
.filter(
|
|
775
|
+
({ msg }) =>
|
|
776
|
+
msg.role !== 'assistant' || Boolean(msg.content) || (msg.toolCalls?.length ?? 0) > 0,
|
|
777
|
+
)
|
|
778
|
+
return sendable.map(({ msg, index }) => {
|
|
407
779
|
if (msg.role === 'tool') {
|
|
408
780
|
return {
|
|
409
781
|
role: 'tool',
|
|
@@ -411,6 +783,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
411
783
|
tool_call_id: (msg as { toolCallId?: string }).toolCallId,
|
|
412
784
|
}
|
|
413
785
|
}
|
|
786
|
+
// The model's own reasoning for the steps of THIS turn goes back with the
|
|
787
|
+
// message that produced it, so it can continue from where it left off
|
|
788
|
+
// after a tool result. An earlier turn's reasoning is not resent.
|
|
789
|
+
const replay =
|
|
790
|
+
msg.role === 'assistant' && index >= turnStart ? replayFor(msg, route) : undefined
|
|
414
791
|
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls?.length) {
|
|
415
792
|
return {
|
|
416
793
|
role: 'assistant',
|
|
@@ -420,16 +797,21 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
420
797
|
type: tc.type,
|
|
421
798
|
function: tc.function,
|
|
422
799
|
})),
|
|
800
|
+
...replay,
|
|
423
801
|
}
|
|
424
802
|
}
|
|
425
|
-
return { role: msg.role, content: msg.content }
|
|
803
|
+
return { role: msg.role, content: msg.content, ...replay }
|
|
426
804
|
})
|
|
427
805
|
}
|
|
428
806
|
|
|
429
|
-
private buildRequestBody(
|
|
807
|
+
private buildRequestBody(
|
|
808
|
+
params: ChatCompletionParams,
|
|
809
|
+
stream: boolean,
|
|
810
|
+
supportedEfforts?: readonly string[],
|
|
811
|
+
): Record<string, unknown> {
|
|
430
812
|
const body: Record<string, unknown> = {
|
|
431
813
|
model: params.model,
|
|
432
|
-
messages: this.formatMessages(params.messages),
|
|
814
|
+
messages: this.formatMessages(params.messages, routeOf(params)),
|
|
433
815
|
stream,
|
|
434
816
|
}
|
|
435
817
|
|
|
@@ -437,7 +819,19 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
437
819
|
body.tools = params.tools
|
|
438
820
|
}
|
|
439
821
|
if (params.toolChoice !== undefined) {
|
|
440
|
-
|
|
822
|
+
if (
|
|
823
|
+
isForcedToolChoice(params.toolChoice) &&
|
|
824
|
+
!this.acceptsForcedToolChoiceFor(params.model, params.thinking, params.effort)
|
|
825
|
+
) {
|
|
826
|
+
// The model's vendor refuses a forced choice while it reasons. Not
|
|
827
|
+
// sending it costs the caller nothing it could have had: the step
|
|
828
|
+
// goes out with the choice left to the model.
|
|
829
|
+
this.logger.debug('openrouter: forced tool_choice not sent, the model refuses it here', {
|
|
830
|
+
'namzu.model': params.model,
|
|
831
|
+
})
|
|
832
|
+
} else {
|
|
833
|
+
body.tool_choice = formatToolChoice(params.toolChoice)
|
|
834
|
+
}
|
|
441
835
|
}
|
|
442
836
|
if (params.parallelToolCalls !== undefined) {
|
|
443
837
|
body.parallel_tool_calls = params.parallelToolCalls
|
|
@@ -456,9 +850,13 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
456
850
|
applyCacheBreakpoints(params.messages, body.messages as { content?: unknown }[])
|
|
457
851
|
}
|
|
458
852
|
|
|
459
|
-
//
|
|
460
|
-
//
|
|
461
|
-
const reasoning = formatReasoning(
|
|
853
|
+
// `max` and `ultra` resolve against the model's own list — see
|
|
854
|
+
// `carriedEffort`.
|
|
855
|
+
const reasoning = formatReasoning(
|
|
856
|
+
params.thinking,
|
|
857
|
+
params.effort !== undefined ? carriedEffort(params.effort, supportedEfforts) : undefined,
|
|
858
|
+
params.maxTokens,
|
|
859
|
+
)
|
|
462
860
|
if (reasoning !== undefined) {
|
|
463
861
|
body.reasoning = reasoning
|
|
464
862
|
}
|
|
@@ -471,7 +869,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
471
869
|
}
|
|
472
870
|
|
|
473
871
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
474
|
-
const
|
|
872
|
+
const supportedEfforts =
|
|
873
|
+
params.effort === 'max' || params.effort === 'ultra'
|
|
874
|
+
? await this.resolveSupportedEfforts(params.model, params.signal)
|
|
875
|
+
: undefined
|
|
876
|
+
const body = this.buildRequestBody(params, true, supportedEfforts)
|
|
475
877
|
|
|
476
878
|
const timeout = AbortSignal.timeout(this.config.timeout ?? 120_000)
|
|
477
879
|
// Compose the caller abort with the request timeout so a Stop cancels the
|
|
@@ -479,33 +881,55 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
479
881
|
// prior `AbortSignal.timeout(...)` expression (byte-identical).
|
|
480
882
|
const signal = params.signal ? AbortSignal.any([timeout, params.signal]) : timeout
|
|
481
883
|
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
884
|
+
const send = async (payload: Record<string, unknown>): Promise<Response> => {
|
|
885
|
+
try {
|
|
886
|
+
return await fetch(`${this.baseUrl}/chat/completions`, {
|
|
887
|
+
method: 'POST',
|
|
888
|
+
headers: this.getHeaders(),
|
|
889
|
+
body: JSON.stringify(payload),
|
|
890
|
+
signal,
|
|
891
|
+
})
|
|
892
|
+
} catch (err) {
|
|
893
|
+
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
894
|
+
throw providerVendorError({ providerId: 'openrouter', error: err })
|
|
895
|
+
}
|
|
493
896
|
}
|
|
494
897
|
|
|
898
|
+
let response = await send(body)
|
|
899
|
+
|
|
495
900
|
if (!response.ok) {
|
|
496
901
|
// The body is read to CLASSIFY (a 400 saying "prompt is too long" is a
|
|
497
902
|
// context overflow, any other 400 is a bad request) and then dropped. It
|
|
498
903
|
// used to be interpolated straight into the message, which is how a
|
|
499
904
|
// credential the upstream echoed back reached every log that recorded
|
|
500
905
|
// the failure — proven with a planted fake token.
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
906
|
+
let errorBody = await response.text().catch(() => '')
|
|
907
|
+
const sentForced =
|
|
908
|
+
body.tool_choice !== undefined && isForcedToolChoice(body.tool_choice as ToolChoice)
|
|
909
|
+
if (
|
|
910
|
+
response.status === 400 &&
|
|
911
|
+
sentForced &&
|
|
912
|
+
refusesToolChoice(errorBody, parseJson(errorBody))
|
|
913
|
+
) {
|
|
914
|
+
// This host refuses a forced choice. Ask once more without it; the
|
|
915
|
+
// model decides whether to call a tool. Anything the second attempt
|
|
916
|
+
// answers is final.
|
|
917
|
+
this.logger.debug('openrouter: a 400 named tool_choice, sending once more without it', {
|
|
918
|
+
'namzu.model': params.model,
|
|
919
|
+
})
|
|
920
|
+
const { tool_choice: _dropped, ...withoutChoice } = body
|
|
921
|
+
response = await send(withoutChoice)
|
|
922
|
+
if (!response.ok) errorBody = await response.text().catch(() => '')
|
|
923
|
+
}
|
|
924
|
+
if (!response.ok) {
|
|
925
|
+
throw providerHttpError({
|
|
926
|
+
providerId: 'openrouter',
|
|
927
|
+
status: response.status,
|
|
928
|
+
body: nameUpstream(errorBody, parseJson(errorBody), 'provider_code'),
|
|
929
|
+
retryAfter: response.headers.get('retry-after'),
|
|
930
|
+
shouldRetry: response.headers.get('x-should-retry'),
|
|
931
|
+
})
|
|
932
|
+
}
|
|
509
933
|
}
|
|
510
934
|
|
|
511
935
|
if (!response.body) {
|
|
@@ -523,6 +947,10 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
523
947
|
// Reasoning blocks this stream has opened and not yet closed, in the
|
|
524
948
|
// order the wire reported them.
|
|
525
949
|
const openReasoning = new Set<number>()
|
|
950
|
+
// The reasoning entries as the wire sent them, kept for replay.
|
|
951
|
+
const replay = new ReasoningDetailsAccumulator()
|
|
952
|
+
const route = routeOf(params)
|
|
953
|
+
let replayStateEmitted = false
|
|
526
954
|
// A choice reported why it stopped. A stream that ends without one, with or
|
|
527
955
|
// without `[DONE]`, was cut by the connection.
|
|
528
956
|
let finished = false
|
|
@@ -580,7 +1008,7 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
580
1008
|
if (parsed.error !== undefined) {
|
|
581
1009
|
throw providerVendorError({
|
|
582
1010
|
providerId: 'openrouter',
|
|
583
|
-
error: new Error(data),
|
|
1011
|
+
error: new Error(nameUpstream(data, parsed, 'error_type')),
|
|
584
1012
|
})
|
|
585
1013
|
}
|
|
586
1014
|
|
|
@@ -589,6 +1017,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
589
1017
|
if (choice.finish_reason) finished = true
|
|
590
1018
|
|
|
591
1019
|
const fragments = parseReasoning(choice.delta.reasoning_details, choice.delta.reasoning)
|
|
1020
|
+
if (choice.delta.reasoning_details && choice.delta.reasoning_details.length > 0) {
|
|
1021
|
+
replay.add(choice.delta.reasoning_details)
|
|
1022
|
+
} else {
|
|
1023
|
+
replay.addFlat(choice.delta.reasoning)
|
|
1024
|
+
}
|
|
592
1025
|
const content = choice.delta.content
|
|
593
1026
|
const toolCalls = choice.delta.tool_calls?.map((tc) => ({
|
|
594
1027
|
index: tc.index,
|
|
@@ -620,8 +1053,14 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
620
1053
|
choice.finish_reason !== undefined ||
|
|
621
1054
|
parsed.usage !== undefined
|
|
622
1055
|
) {
|
|
1056
|
+
const replayState =
|
|
1057
|
+
!replayStateEmitted && choice.finish_reason && replay.hasAny
|
|
1058
|
+
? replay.state(route)
|
|
1059
|
+
: undefined
|
|
1060
|
+
if (replayState !== undefined) replayStateEmitted = true
|
|
623
1061
|
yield {
|
|
624
1062
|
id: parsed.id,
|
|
1063
|
+
...(replayState !== undefined ? { replayState } : {}),
|
|
625
1064
|
delta: {
|
|
626
1065
|
...(firstFragment ? { reasoning: firstFragment } : {}),
|
|
627
1066
|
content,
|
|
@@ -734,10 +1173,61 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
734
1173
|
this.contextWindows ??= windows
|
|
735
1174
|
windows = this.contextWindows
|
|
736
1175
|
}
|
|
737
|
-
|
|
1176
|
+
// A variant tag (`:batch`, `:nitro`) names the same model at the same
|
|
1177
|
+
// window; when the listing has only the untagged id, that is the answer.
|
|
1178
|
+
const tag = model.indexOf(':')
|
|
1179
|
+
const reported = windows.get(model) ?? (tag > 0 ? windows.get(model.slice(0, tag)) : undefined)
|
|
738
1180
|
return typeof reported === 'number' && reported > 0 ? reported : undefined
|
|
739
1181
|
}
|
|
740
1182
|
|
|
1183
|
+
/**
|
|
1184
|
+
* The reasoning levels the listing names for `model` (`reasoning.supported_efforts`),
|
|
1185
|
+
* or `undefined` when the listing cannot be read or names none. Read only
|
|
1186
|
+
* for a `max` or `ultra` request, and kept for this driver once fulfilled; a
|
|
1187
|
+
* failure is not kept. A caller abort still propagates.
|
|
1188
|
+
*/
|
|
1189
|
+
private async resolveSupportedEfforts(
|
|
1190
|
+
model: string,
|
|
1191
|
+
signal?: AbortSignal,
|
|
1192
|
+
): Promise<readonly string[] | undefined> {
|
|
1193
|
+
let table = this.supportedEfforts
|
|
1194
|
+
if (!table) {
|
|
1195
|
+
try {
|
|
1196
|
+
signal?.throwIfAborted()
|
|
1197
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1198
|
+
headers: this.getHeaders(),
|
|
1199
|
+
// Bounded on its own: this read sits in front of the first max or
|
|
1200
|
+
// ultra request, so a stalled listing must not stall that request.
|
|
1201
|
+
signal: signal
|
|
1202
|
+
? AbortSignal.any([AbortSignal.timeout(5000), signal])
|
|
1203
|
+
: AbortSignal.timeout(5000),
|
|
1204
|
+
})
|
|
1205
|
+
if (!response.ok) return undefined
|
|
1206
|
+
const data = (await response.json()) as {
|
|
1207
|
+
data?: Array<{ id: string; reasoning?: { supported_efforts?: unknown } }>
|
|
1208
|
+
}
|
|
1209
|
+
table = new Map()
|
|
1210
|
+
for (const m of data.data ?? []) {
|
|
1211
|
+
const levels = m.reasoning?.supported_efforts
|
|
1212
|
+
if (Array.isArray(levels)) {
|
|
1213
|
+
table.set(
|
|
1214
|
+
m.id,
|
|
1215
|
+
levels.filter((l): l is string => typeof l === 'string'),
|
|
1216
|
+
)
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
this.supportedEfforts = table
|
|
1220
|
+
} catch (err) {
|
|
1221
|
+
if (signal?.aborted) throw signal.reason ?? err
|
|
1222
|
+
return undefined
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
const tag = model.indexOf(':')
|
|
1226
|
+
return table.get(model) ?? (tag > 0 ? table.get(model.slice(0, tag)) : undefined)
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
private supportedEfforts?: Map<string, string[]>
|
|
1230
|
+
|
|
741
1231
|
/** First fulfilled listing; see the note on `resolveContextWindow`. */
|
|
742
1232
|
private contextWindows?: Map<string, number>
|
|
743
1233
|
|