@namzu/openrouter 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +7 -5
- package/dist/client.d.ts +33 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +266 -63
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/limits.d.ts +9 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/limits.js +44 -0
- package/dist/limits.js.map +1 -0
- package/package.json +2 -2
- package/src/client.ts +298 -80
- package/src/index.ts +1 -0
- package/src/limits.ts +48 -0
package/src/client.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type {
|
|
|
3
3
|
LLMProvider,
|
|
4
4
|
ModelInfo,
|
|
5
5
|
ProviderCapabilities,
|
|
6
|
+
ProviderLimits,
|
|
6
7
|
ProviderRoute,
|
|
7
8
|
ReasoningBlock,
|
|
8
9
|
ReasoningEffort,
|
|
@@ -14,13 +15,16 @@ import type {
|
|
|
14
15
|
import {
|
|
15
16
|
ProviderRequestError,
|
|
16
17
|
isCallerAbortError,
|
|
18
|
+
isModelContentOmission,
|
|
17
19
|
isProviderRequestError,
|
|
18
20
|
providerHttpError,
|
|
19
21
|
providerVendorError,
|
|
22
|
+
toToolResultBlocks,
|
|
20
23
|
} from '@namzu/sdk'
|
|
21
24
|
import { attributionHeaders } from '@namzu/sdk'
|
|
22
25
|
import type { Logger } from '@namzu/sdk'
|
|
23
26
|
import { NOOP_LOGGER } from '@namzu/sdk'
|
|
27
|
+
import { parseKeyLimits } from './limits.js'
|
|
24
28
|
import type { OpenRouterConfig } from './types.js'
|
|
25
29
|
|
|
26
30
|
/**
|
|
@@ -162,22 +166,32 @@ function markLastPart(message: { content?: unknown }): boolean {
|
|
|
162
166
|
function applyCacheBreakpoints(
|
|
163
167
|
source: ChatCompletionParams['messages'],
|
|
164
168
|
formatted: { content?: unknown }[],
|
|
169
|
+
origin: readonly number[],
|
|
165
170
|
): void {
|
|
171
|
+
// `origin[w]` is the source index of wire entry `w`, or -1 for an entry the
|
|
172
|
+
// driver added (the user message that carries a tool's images).
|
|
173
|
+
const wireOf = (sourceIndex: number): { content?: unknown } | undefined => {
|
|
174
|
+
const at = origin.indexOf(sourceIndex)
|
|
175
|
+
return at >= 0 ? formatted[at] : undefined
|
|
176
|
+
}
|
|
166
177
|
let lastStatic = -1
|
|
167
178
|
let historyEnd = source.length
|
|
168
179
|
for (const [i, msg] of source.entries()) {
|
|
169
180
|
if (msg.role === 'system' && msg.cacheHint === 'cache') lastStatic = i
|
|
170
181
|
if (historyEnd === source.length && isRequestOnlyContext(msg)) historyEnd = i
|
|
171
182
|
}
|
|
172
|
-
const staticMessage = lastStatic >= 0 ?
|
|
183
|
+
const staticMessage = lastStatic >= 0 ? wireOf(lastStatic) : undefined
|
|
173
184
|
if (staticMessage) markLastPart(staticMessage)
|
|
174
185
|
for (let i = historyEnd - 1; i > lastStatic; i--) {
|
|
175
186
|
if (source[i]?.role === 'system') continue
|
|
176
|
-
const message =
|
|
187
|
+
const message = wireOf(i)
|
|
177
188
|
if (message && markLastPart(message)) return
|
|
178
189
|
}
|
|
179
190
|
}
|
|
180
191
|
|
|
192
|
+
/** An inline image a tool returned. */
|
|
193
|
+
type ToolImage = { readonly data: string; readonly mediaType: string }
|
|
194
|
+
|
|
181
195
|
function routeOf(params: ChatCompletionParams): ProviderRoute {
|
|
182
196
|
return params.providerRoute ?? { providerId: 'openrouter', model: params.model, chainIndex: 0 }
|
|
183
197
|
}
|
|
@@ -201,7 +215,9 @@ const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? 'https://openrout
|
|
|
201
215
|
function pricePerMillion(raw: string | undefined): number | undefined {
|
|
202
216
|
if (raw === undefined) return undefined
|
|
203
217
|
const parsed = Number.parseFloat(raw)
|
|
204
|
-
|
|
218
|
+
// `"-1"` is how the listing marks a router with no fixed rate (`openrouter/auto`):
|
|
219
|
+
// a rate nobody stated, not a negative one.
|
|
220
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed * 1_000_000 : undefined
|
|
205
221
|
}
|
|
206
222
|
|
|
207
223
|
interface RawUsage {
|
|
@@ -489,21 +505,6 @@ function replayFor(
|
|
|
489
505
|
: { reasoning: state.reasoning as string }
|
|
490
506
|
}
|
|
491
507
|
|
|
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
|
/**
|
|
508
509
|
* Whether a model is one whose vendor refuses a forced tool choice while it
|
|
509
510
|
* reasons: the DeepSeek V4 generation and its reasoner line. Its own API
|
|
@@ -676,24 +677,81 @@ function formatToolChoice(tc: ToolChoice): unknown {
|
|
|
676
677
|
|
|
677
678
|
/**
|
|
678
679
|
* What this DRIVER does, not what OpenRouter could do: tools pass
|
|
679
|
-
* through to the request body,
|
|
680
|
-
*
|
|
681
|
-
*
|
|
680
|
+
* through to the request body, and user-message image `attachments` are
|
|
681
|
+
* mapped into `image_url` content parts; an image a tool returns rides in a user
|
|
682
|
+
* message right after that turn's tool messages. Whether a given MODEL reads them is
|
|
683
|
+
* answered per model by `supportsImageInputFor`, from the listing's input
|
|
684
|
+
* modalities; the runtime keeps images away from a model known to be text-only.
|
|
682
685
|
*/
|
|
683
686
|
export const OPENROUTER_CAPABILITIES: ProviderCapabilities = {
|
|
684
687
|
supportsTools: true,
|
|
685
688
|
supportsStreaming: true,
|
|
686
689
|
supportsFunctionCalling: true,
|
|
687
690
|
supportsNativeStructuredOutput: true,
|
|
688
|
-
supportsVision:
|
|
691
|
+
supportsVision: true,
|
|
689
692
|
// Images only. A document degrades to a named placeholder.
|
|
690
693
|
supportsDocuments: false,
|
|
691
|
-
|
|
694
|
+
// An image a tool returns follows its tool messages in one user message
|
|
695
|
+
// (a chat-completions tool message carries text only).
|
|
696
|
+
supportsToolResultImages: true,
|
|
692
697
|
supportsToolResultDocuments: false,
|
|
693
698
|
// OpenRouter states the charge on every response (`usage.cost`).
|
|
694
699
|
reportsRequestCost: true,
|
|
695
700
|
}
|
|
696
701
|
|
|
702
|
+
/**
|
|
703
|
+
* How long a read of the `/models` listing may take. The listing is several
|
|
704
|
+
* hundred entries and normally answers well inside a second; 5 s is long
|
|
705
|
+
* enough for a slow link and short enough that the first `max` request, which
|
|
706
|
+
* waits on this read, does not feel stuck. It is a bound on waiting, not a
|
|
707
|
+
* retry: past it the listing counts as absent and each reader's documented
|
|
708
|
+
* fallback applies.
|
|
709
|
+
*/
|
|
710
|
+
export const MODEL_LISTING_TIMEOUT_MS = 5000
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* Run `read` with a signal that fires at the listing bound or when the
|
|
714
|
+
* caller's signal does. The bound is an ordinary timer, cleared when the read
|
|
715
|
+
* settles, so a test can advance it with a fake clock.
|
|
716
|
+
*/
|
|
717
|
+
async function withListingBound<T>(
|
|
718
|
+
signal: AbortSignal | undefined,
|
|
719
|
+
read: (bounded: AbortSignal) => Promise<T>,
|
|
720
|
+
): Promise<T> {
|
|
721
|
+
const bound = new AbortController()
|
|
722
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
723
|
+
// Rejects at the bound even when the transport ignores its signal.
|
|
724
|
+
const expired = new Promise<never>((_, reject) => {
|
|
725
|
+
timer = setTimeout(() => {
|
|
726
|
+
const reason = new DOMException('the models listing did not answer in time', 'TimeoutError')
|
|
727
|
+
bound.abort(reason)
|
|
728
|
+
reject(reason)
|
|
729
|
+
}, MODEL_LISTING_TIMEOUT_MS)
|
|
730
|
+
})
|
|
731
|
+
let onAbort: (() => void) | undefined
|
|
732
|
+
// The caller's abort also ends the wait, whether or not the transport honours it.
|
|
733
|
+
const cancelled = new Promise<never>((_, reject) => {
|
|
734
|
+
if (!signal) return
|
|
735
|
+
onAbort = () => reject(signal.reason ?? new DOMException('aborted', 'AbortError'))
|
|
736
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
737
|
+
})
|
|
738
|
+
try {
|
|
739
|
+
return await Promise.race([
|
|
740
|
+
read(signal ? AbortSignal.any([bound.signal, signal]) : bound.signal),
|
|
741
|
+
expired,
|
|
742
|
+
cancelled,
|
|
743
|
+
])
|
|
744
|
+
} finally {
|
|
745
|
+
if (onAbort) signal?.removeEventListener('abort', onAbort)
|
|
746
|
+
clearTimeout(timer)
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** Did the listing read run past its bound (as opposed to failing some other way)? */
|
|
751
|
+
function isListingTimeout(err: unknown): boolean {
|
|
752
|
+
return err instanceof Error && err.name === 'TimeoutError'
|
|
753
|
+
}
|
|
754
|
+
|
|
697
755
|
export class OpenRouterProvider implements LLMProvider {
|
|
698
756
|
readonly id = 'openrouter'
|
|
699
757
|
readonly name = 'OpenRouter'
|
|
@@ -762,8 +820,8 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
762
820
|
private formatMessages(
|
|
763
821
|
messages: ChatCompletionParams['messages'],
|
|
764
822
|
route: ProviderRoute,
|
|
765
|
-
): unknown[] {
|
|
766
|
-
const
|
|
823
|
+
): { wire: unknown[]; origin: number[] } {
|
|
824
|
+
const readsImages = this.supportsImageInputFor(route.model)
|
|
767
825
|
// An assistant entry with neither text nor a tool call (the model produced
|
|
768
826
|
// only reasoning, or was cut off) is rejected upstream with "content or
|
|
769
827
|
// tool_calls must be set". Leave it out; no filler is invented. An entry
|
|
@@ -775,33 +833,119 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
775
833
|
({ msg }) =>
|
|
776
834
|
msg.role !== 'assistant' || Boolean(msg.content) || (msg.toolCalls?.length ?? 0) > 0,
|
|
777
835
|
)
|
|
778
|
-
|
|
836
|
+
const wire: unknown[] = []
|
|
837
|
+
const origin: number[] = []
|
|
838
|
+
const callNames = new Map<string, string>()
|
|
839
|
+
// A tool message carries text only on this wire. The images a turn's tools
|
|
840
|
+
// returned wait here and go out as ONE user message after the last of that
|
|
841
|
+
// turn's tool messages, because every tool message has to follow the
|
|
842
|
+
// assistant message that made the calls directly.
|
|
843
|
+
let pendingImages: Array<{ callId: string; image: ToolImage }> = []
|
|
844
|
+
const flushToolImages = (): void => {
|
|
845
|
+
if (pendingImages.length === 0) return
|
|
846
|
+
const parts: Array<
|
|
847
|
+
{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }
|
|
848
|
+
> = []
|
|
849
|
+
for (const { callId, image } of pendingImages) {
|
|
850
|
+
const name = callNames.get(callId)
|
|
851
|
+
parts.push({
|
|
852
|
+
type: 'text',
|
|
853
|
+
text: `Image returned by the ${name ? `\`${name}\` ` : ''}tool call ${callId}:`,
|
|
854
|
+
})
|
|
855
|
+
parts.push({
|
|
856
|
+
type: 'image_url',
|
|
857
|
+
image_url: { url: `data:${image.mediaType};base64,${image.data}` },
|
|
858
|
+
})
|
|
859
|
+
}
|
|
860
|
+
wire.push({ role: 'user', content: parts })
|
|
861
|
+
origin.push(-1)
|
|
862
|
+
pendingImages = []
|
|
863
|
+
}
|
|
864
|
+
const push = (entry: unknown, index: number): void => {
|
|
865
|
+
wire.push(entry)
|
|
866
|
+
origin.push(index)
|
|
867
|
+
}
|
|
868
|
+
for (const { msg, index } of sendable) {
|
|
869
|
+
if (msg.role !== 'tool') flushToolImages()
|
|
779
870
|
if (msg.role === 'tool') {
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
content: msg.content,
|
|
783
|
-
|
|
871
|
+
const callId = (msg as { toolCallId?: string }).toolCallId
|
|
872
|
+
if (typeof msg.content === 'string') {
|
|
873
|
+
push({ role: 'tool', content: msg.content, tool_call_id: callId }, index)
|
|
874
|
+
continue
|
|
784
875
|
}
|
|
876
|
+
const text: string[] = []
|
|
877
|
+
for (const block of toToolResultBlocks(msg.content)) {
|
|
878
|
+
if (block.type === 'text') text.push(block.text)
|
|
879
|
+
else if (block.type === 'image') {
|
|
880
|
+
if (readsImages && !isModelContentOmission(block.modelOmission) && callId) {
|
|
881
|
+
pendingImages.push({ callId, image: block })
|
|
882
|
+
text.push('[image attached in the next message]')
|
|
883
|
+
} else {
|
|
884
|
+
text.push(
|
|
885
|
+
`[image omitted: this model cannot read it (${block.mediaType}, ${block.data.length} B)]`,
|
|
886
|
+
)
|
|
887
|
+
}
|
|
888
|
+
} else text.push(`[document omitted: ${block.mediaType} cannot be sent here]`)
|
|
889
|
+
}
|
|
890
|
+
push({ role: 'tool', content: text.join('\n'), tool_call_id: callId }, index)
|
|
891
|
+
continue
|
|
785
892
|
}
|
|
786
|
-
// The model's own reasoning
|
|
787
|
-
//
|
|
788
|
-
//
|
|
789
|
-
|
|
790
|
-
|
|
893
|
+
// The model's own reasoning goes back with the message that produced it,
|
|
894
|
+
// for every assistant message of the conversation, not only the current
|
|
895
|
+
// turn's. A message's bytes must not change from one request to the next:
|
|
896
|
+
// the upstream caches by prefix, and an earlier message re-sent without
|
|
897
|
+
// the reasoning it was sent with before moves the prefix and bills the
|
|
898
|
+
// whole history again at the first new user message. Reasoning leaves
|
|
899
|
+
// the history only when a compaction rewrites it (the stored reasoning
|
|
900
|
+
// then no longer matches the envelope and `replayFor` answers nothing).
|
|
901
|
+
const replay = msg.role === 'assistant' ? replayFor(msg, route) : undefined
|
|
791
902
|
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls?.length) {
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
903
|
+
for (const tc of msg.toolCalls) callNames.set(tc.id, tc.function.name)
|
|
904
|
+
push(
|
|
905
|
+
{
|
|
906
|
+
role: 'assistant',
|
|
907
|
+
content: msg.content,
|
|
908
|
+
tool_calls: msg.toolCalls.map((tc) => ({
|
|
909
|
+
id: tc.id,
|
|
910
|
+
type: tc.type,
|
|
911
|
+
function: tc.function,
|
|
912
|
+
})),
|
|
913
|
+
...replay,
|
|
914
|
+
},
|
|
915
|
+
index,
|
|
916
|
+
)
|
|
917
|
+
continue
|
|
918
|
+
}
|
|
919
|
+
if (msg.role === 'user' && msg.attachments && msg.attachments.length > 0) {
|
|
920
|
+
const parts: Array<
|
|
921
|
+
{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }
|
|
922
|
+
> = []
|
|
923
|
+
if (msg.content.length > 0) parts.push({ type: 'text', text: msg.content })
|
|
924
|
+
for (const attachment of msg.attachments) {
|
|
925
|
+
// Only inline images have a wire form here. A document is turned
|
|
926
|
+
// into a placeholder and a stored reference is resolved by the
|
|
927
|
+
// runtime before this point; an image the runtime already withheld
|
|
928
|
+
// from the model stays withheld.
|
|
929
|
+
if (attachment.type === 'stored' || attachment.type === 'document') continue
|
|
930
|
+
if (isModelContentOmission(attachment.modelOmission)) continue
|
|
931
|
+
parts.push({
|
|
932
|
+
type: 'image_url',
|
|
933
|
+
image_url: { url: `data:${attachment.mediaType};base64,${attachment.data}` },
|
|
934
|
+
})
|
|
801
935
|
}
|
|
936
|
+
push(
|
|
937
|
+
{
|
|
938
|
+
role: 'user',
|
|
939
|
+
content: parts.some((part) => part.type === 'image_url') ? parts : msg.content,
|
|
940
|
+
},
|
|
941
|
+
index,
|
|
942
|
+
)
|
|
943
|
+
continue
|
|
802
944
|
}
|
|
803
|
-
|
|
804
|
-
}
|
|
945
|
+
push({ role: msg.role, content: msg.content, ...replay }, index)
|
|
946
|
+
}
|
|
947
|
+
flushToolImages()
|
|
948
|
+
return { wire, origin }
|
|
805
949
|
}
|
|
806
950
|
|
|
807
951
|
private buildRequestBody(
|
|
@@ -809,9 +953,10 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
809
953
|
stream: boolean,
|
|
810
954
|
supportedEfforts?: readonly string[],
|
|
811
955
|
): Record<string, unknown> {
|
|
956
|
+
const formatted = this.formatMessages(params.messages, routeOf(params))
|
|
812
957
|
const body: Record<string, unknown> = {
|
|
813
958
|
model: params.model,
|
|
814
|
-
messages:
|
|
959
|
+
messages: formatted.wire,
|
|
815
960
|
stream,
|
|
816
961
|
}
|
|
817
962
|
|
|
@@ -847,7 +992,11 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
847
992
|
if (params.stop) body.stop = params.stop
|
|
848
993
|
|
|
849
994
|
if (params.cacheControl && takesExplicitBreakpoints(params.model)) {
|
|
850
|
-
applyCacheBreakpoints(
|
|
995
|
+
applyCacheBreakpoints(
|
|
996
|
+
params.messages,
|
|
997
|
+
body.messages as { content?: unknown }[],
|
|
998
|
+
formatted.origin,
|
|
999
|
+
)
|
|
851
1000
|
}
|
|
852
1001
|
|
|
853
1002
|
// `max` and `ultra` resolve against the model's own list — see
|
|
@@ -1113,6 +1262,23 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1113
1262
|
* requires the credential and returns its metadata, so a 401 here means the
|
|
1114
1263
|
* key is genuinely refused.
|
|
1115
1264
|
*/
|
|
1265
|
+
/**
|
|
1266
|
+
* The key's limit and use, from one GET of `/key`. Any failure or unexpected body is "not
|
|
1267
|
+
* reported", never a zero.
|
|
1268
|
+
*/
|
|
1269
|
+
async readLimits(signal?: AbortSignal): Promise<ProviderLimits | undefined> {
|
|
1270
|
+
try {
|
|
1271
|
+
const response = await fetch(`${this.baseUrl}/key`, {
|
|
1272
|
+
headers: this.getHeaders(),
|
|
1273
|
+
...(signal ? { signal } : {}),
|
|
1274
|
+
})
|
|
1275
|
+
if (!response.ok) return undefined
|
|
1276
|
+
return parseKeyLimits(await response.json(), Date.now())
|
|
1277
|
+
} catch {
|
|
1278
|
+
return undefined
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1116
1282
|
async probeCredential(signal?: AbortSignal): Promise<void> {
|
|
1117
1283
|
signal?.throwIfAborted()
|
|
1118
1284
|
const response = await fetch(`${this.baseUrl}/key`, {
|
|
@@ -1156,7 +1322,16 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1156
1322
|
if (signal?.aborted) return undefined
|
|
1157
1323
|
let windows = this.contextWindows
|
|
1158
1324
|
if (!windows) {
|
|
1159
|
-
|
|
1325
|
+
let models: ModelInfo[]
|
|
1326
|
+
try {
|
|
1327
|
+
models = await this.listModels(signal)
|
|
1328
|
+
} catch (err) {
|
|
1329
|
+
// A listing that outlasts its bound is "no listing": the
|
|
1330
|
+
// caller's static table answers. A caller abort stays an abort.
|
|
1331
|
+
if (signal?.aborted) return undefined
|
|
1332
|
+
if (isListingTimeout(err)) return undefined
|
|
1333
|
+
throw err
|
|
1334
|
+
}
|
|
1160
1335
|
if (signal?.aborted) return undefined
|
|
1161
1336
|
windows = new Map<string, number>(
|
|
1162
1337
|
models
|
|
@@ -1194,18 +1369,19 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1194
1369
|
if (!table) {
|
|
1195
1370
|
try {
|
|
1196
1371
|
signal?.throwIfAborted()
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1372
|
+
// Bounded on its own: this read sits in front of the first max or
|
|
1373
|
+
// ultra request, so a stalled listing must not stall that request.
|
|
1374
|
+
const data = await withListingBound(signal, async (bounded) => {
|
|
1375
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1376
|
+
headers: this.getHeaders(),
|
|
1377
|
+
signal: bounded,
|
|
1378
|
+
})
|
|
1379
|
+
if (!response.ok) return undefined
|
|
1380
|
+
return (await response.json()) as {
|
|
1381
|
+
data?: Array<{ id: string; reasoning?: { supported_efforts?: unknown } }>
|
|
1382
|
+
}
|
|
1204
1383
|
})
|
|
1205
|
-
if (!
|
|
1206
|
-
const data = (await response.json()) as {
|
|
1207
|
-
data?: Array<{ id: string; reasoning?: { supported_efforts?: unknown } }>
|
|
1208
|
-
}
|
|
1384
|
+
if (!data) return undefined
|
|
1209
1385
|
table = new Map()
|
|
1210
1386
|
for (const m of data.data ?? []) {
|
|
1211
1387
|
const levels = m.reasoning?.supported_efforts
|
|
@@ -1228,31 +1404,63 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1228
1404
|
|
|
1229
1405
|
private supportedEfforts?: Map<string, string[]>
|
|
1230
1406
|
|
|
1407
|
+
/**
|
|
1408
|
+
* Whether the model reads images, as the listing last said (`architecture.input_modalities`).
|
|
1409
|
+
* Filled by `listModels`, which the context-window lookup runs once per driver, so
|
|
1410
|
+
* answering costs no request of its own. Empty until a listing was read.
|
|
1411
|
+
*/
|
|
1412
|
+
private imageInput = new Map<string, boolean>()
|
|
1413
|
+
|
|
1414
|
+
/**
|
|
1415
|
+
* Whether `model` reads images. `false` only when the listing named the model's input
|
|
1416
|
+
* kinds and `image` was not among them. A model the listing does not name, or a
|
|
1417
|
+
* listing not read yet, answers `true`: a wrong "no" blinds a vision model, while a
|
|
1418
|
+
* wrong "yes" is recovered from when the router refuses the request.
|
|
1419
|
+
*/
|
|
1420
|
+
supportsImageInputFor(model: string): boolean {
|
|
1421
|
+
const tag = model.indexOf(':')
|
|
1422
|
+
return (
|
|
1423
|
+
this.imageInput.get(model) ??
|
|
1424
|
+
(tag > 0 ? this.imageInput.get(model.slice(0, tag)) : undefined) ??
|
|
1425
|
+
true
|
|
1426
|
+
)
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1231
1429
|
/** First fulfilled listing; see the note on `resolveContextWindow`. */
|
|
1232
1430
|
private contextWindows?: Map<string, number>
|
|
1233
1431
|
|
|
1234
1432
|
async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
|
|
1235
1433
|
signal?.throwIfAborted()
|
|
1236
|
-
const
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1434
|
+
const data = await withListingBound(signal, async (bounded) => {
|
|
1435
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1436
|
+
headers: this.getHeaders(),
|
|
1437
|
+
signal: bounded,
|
|
1438
|
+
})
|
|
1240
1439
|
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1440
|
+
if (!response.ok) {
|
|
1441
|
+
throw new Error(`Failed to list models: ${response.status}`)
|
|
1442
|
+
}
|
|
1244
1443
|
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1444
|
+
return (await response.json()) as {
|
|
1445
|
+
data: Array<{
|
|
1446
|
+
id: string
|
|
1447
|
+
name: string
|
|
1448
|
+
context_length: number
|
|
1449
|
+
top_provider?: { max_completion_tokens?: number }
|
|
1450
|
+
pricing?: { prompt: string; completion: string }
|
|
1451
|
+
architecture?: { input_modalities?: unknown }
|
|
1452
|
+
}>
|
|
1453
|
+
}
|
|
1454
|
+
})
|
|
1254
1455
|
signal?.throwIfAborted()
|
|
1255
1456
|
|
|
1457
|
+
const imageInput = new Map<string, boolean>()
|
|
1458
|
+
for (const m of data.data) {
|
|
1459
|
+
const kinds = m.architecture?.input_modalities
|
|
1460
|
+
if (Array.isArray(kinds)) imageInput.set(m.id, kinds.includes('image'))
|
|
1461
|
+
}
|
|
1462
|
+
this.imageInput = imageInput
|
|
1463
|
+
|
|
1256
1464
|
return data.data.map((m) => {
|
|
1257
1465
|
const inputPrice = pricePerMillion(m.pricing?.prompt)
|
|
1258
1466
|
const outputPrice = pricePerMillion(m.pricing?.completion)
|
|
@@ -1263,6 +1471,14 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1263
1471
|
maxOutputTokens: m.top_provider?.max_completion_tokens ?? 4096,
|
|
1264
1472
|
...(inputPrice !== undefined ? { inputPrice } : {}),
|
|
1265
1473
|
...(outputPrice !== undefined ? { outputPrice } : {}),
|
|
1474
|
+
...(Array.isArray(m.architecture?.input_modalities)
|
|
1475
|
+
? {
|
|
1476
|
+
inputModalities: [
|
|
1477
|
+
'text' as const,
|
|
1478
|
+
...(imageInput.get(m.id) ? ['image' as const] : []),
|
|
1479
|
+
],
|
|
1480
|
+
}
|
|
1481
|
+
: {}),
|
|
1266
1482
|
supportsToolUse: true,
|
|
1267
1483
|
supportsStreaming: true,
|
|
1268
1484
|
}
|
|
@@ -1271,11 +1487,13 @@ export class OpenRouterProvider implements LLMProvider {
|
|
|
1271
1487
|
|
|
1272
1488
|
async healthCheck(): Promise<boolean> {
|
|
1273
1489
|
try {
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1490
|
+
return await withListingBound(undefined, async (bounded) => {
|
|
1491
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
1492
|
+
headers: this.getHeaders(),
|
|
1493
|
+
signal: bounded,
|
|
1494
|
+
})
|
|
1495
|
+
return response.ok
|
|
1277
1496
|
})
|
|
1278
|
-
return response.ok
|
|
1279
1497
|
} catch {
|
|
1280
1498
|
return false
|
|
1281
1499
|
}
|
package/src/index.ts
CHANGED
|
@@ -25,3 +25,4 @@ export function registerOpenRouter(options?: RegisterOptions): void {
|
|
|
25
25
|
|
|
26
26
|
export { OPENROUTER_CAPABILITIES, OpenRouterProvider } from './client.js'
|
|
27
27
|
export type { OpenRouterConfig, OpenRouterProviderConfig } from './types.js'
|
|
28
|
+
export { parseKeyLimits } from './limits.js'
|
package/src/limits.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ProviderLimits } from '@namzu/sdk'
|
|
2
|
+
|
|
3
|
+
const number = (value: unknown): number | undefined =>
|
|
4
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The key's limit and use from `GET /key`. The body is `{ data: { limit, limit_remaining, usage, ... } }`
|
|
8
|
+
* with `limit` and `limit_remaining` null for a key without a cap. When the vendor names a budget
|
|
9
|
+
* in dollars (`effective_budget`) that is what is shown; otherwise the key's own numbers, which the
|
|
10
|
+
* vendor counts in credits. A body that does not match is "not reported" (`undefined`), never a zero.
|
|
11
|
+
*/
|
|
12
|
+
export function parseKeyLimits(body: unknown, now: number): ProviderLimits | undefined {
|
|
13
|
+
if (typeof body !== 'object' || body === null) return undefined
|
|
14
|
+
const data = (body as { data?: unknown }).data
|
|
15
|
+
if (typeof data !== 'object' || data === null) return undefined
|
|
16
|
+
const key = data as Record<string, unknown>
|
|
17
|
+
const budget = key.effective_budget
|
|
18
|
+
if (typeof budget === 'object' && budget !== null) {
|
|
19
|
+
const {
|
|
20
|
+
limit_usd: limit,
|
|
21
|
+
spend_usd: used,
|
|
22
|
+
remaining_usd: remaining,
|
|
23
|
+
} = budget as Record<string, unknown>
|
|
24
|
+
if (number(limit) !== undefined && number(used) !== undefined)
|
|
25
|
+
return {
|
|
26
|
+
credit: {
|
|
27
|
+
currency: 'USD',
|
|
28
|
+
limit: number(limit) as number,
|
|
29
|
+
used: number(used) as number,
|
|
30
|
+
...(number(remaining) !== undefined ? { remaining: number(remaining) as number } : {}),
|
|
31
|
+
},
|
|
32
|
+
asOf: now,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const used = number(key.usage)
|
|
36
|
+
if (used === undefined) return undefined
|
|
37
|
+
const limit = number(key.limit)
|
|
38
|
+
const remaining = number(key.limit_remaining)
|
|
39
|
+
return {
|
|
40
|
+
credit: {
|
|
41
|
+
currency: 'credits',
|
|
42
|
+
used,
|
|
43
|
+
...(limit !== undefined ? { limit } : {}),
|
|
44
|
+
...(remaining !== undefined ? { remaining } : {}),
|
|
45
|
+
},
|
|
46
|
+
asOf: now,
|
|
47
|
+
}
|
|
48
|
+
}
|