Open History to see the last commit
1/**
2 * LLM Gateway (llmgateway.io) — OpenAI-compatible router with a public
3 * OpenAPI document and a public model listing.
4 *
5 * Each listed model has `providers[]`: the routes it can be served by, each
6 * with its own price. A bare id (`gpt-oss-120b`) is routed by a live score
7 * (docs.llmgateway.io/features/routing), so its billed price is only known
8 * when every route quotes the same one; otherwise it carries a
9 * `pricingRange` over its routes' cards. `provider/model` pins one route
10 * ("prefix the model name with the provider name followed by a slash"), so
11 * each route is also listed as its own row with that route's price. The
12 * listing's top-level `pricing` is undocumented and is not used.
13 *
14 * Upstream links come from the route's own `providerId` + `externalId`,
15 * never from `family`. A bare id with several routes has no single upstream.
16 */
17import { compileTokenCard } from '@modelschemas/rate-card'
18import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
19
20import type { Activity } from '#/db/schema.ts'
21import { pricingRange } from '#/server/rate-card.ts'
22
23import { bearerConnect } from '../connect.ts'
24import { classifyOpenAiCompat } from '../openai-compat.ts'
25import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
26import type { ChatRequestMap, EffortLevelMap } from '../request-map.ts'
27import { fetchJson, fetchOpenApi, sha256Text } from '../types.ts'
28import type {
29 FactSource,
30 ListModelsResult,
31 ModelInfo,
32 ModelReasoning,
33 ProviderConfig,
34 ProviderSecrets,
35 SpecFetchResult,
36} from '../types.ts'
37
38export const LLMGATEWAY_MODELS_URL = 'https://api.llmgateway.io/v1/models'
39export const LLMGATEWAY_SPEC_URL = 'https://api.llmgateway.io/openapi.json'
40
41/** Route `providerId` of the gateway's own virtual models (auto, custom). */
42const SELF = 'llmgateway'
43
44/** Listing `supported_parameters` names that are catalog flags. */
45const PARAMETER_FLAGS: Record<string, string> = {
46 tools: 'tools',
47 tool_choice: 'tool_choice',
48 max_tokens: 'max_tokens',
49 max_completion_tokens: 'max_tokens',
50 temperature: 'temperature',
51 top_p: 'top_p',
52 stop: 'stop',
53 seed: 'seed',
54 frequency_penalty: 'frequency_penalty',
55 presence_penalty: 'presence_penalty',
56 response_format: 'response_format',
57 reasoning: 'reasoning',
58 reasoning_effort: 'reasoning_effort',
59}
60
61/**
62 * Route price key → the usage lever it prices. Counts are disjoint, as in
63 * the gateway's own cost code (`packages/actions/src/costs.ts`):
64 * `input_cache_read_explicit` replaces the cache read rate when the request
65 * used `cache_control`, `content_filter` is xAI's flat fee per blocked
66 * request. A route quoting any other key (`image`, audio, `per_second`,
67 * `peak`, `discount`) gets no card rather than a guessed one.
68 */
69const LEVERS: Record<string, string> = {
70 prompt: 'input_tokens',
71 completion: 'output_tokens',
72 input_cache_read: 'cache_read_tokens',
73 input_cache_read_explicit: 'explicit_cache_read_tokens',
74 input_cache_write: 'cache_write_tokens',
75 input_cache_write_1h: 'cache_write_1h_tokens',
76 web_search: 'web_searches',
77 content_filter: 'content_filtered_requests',
78 request: 'requests',
79}
80
81/** Levers the gateway counts in the prompt size that picks a tier. */
82const EXTRA_PROMPT_LEVERS = ['explicit_cache_read_tokens']
83
84function isRecord(value: unknown): value is Record<string, unknown> {
85 return typeof value === 'object' && value !== null && !Array.isArray(value)
86}
87
88function positive(value: unknown): number | null {
89 return typeof value === 'number' && Number.isFinite(value) && value > 0
90 ? value
91 : null
92}
93
94function strings(value: unknown): Array<string> | null {
95 if (!Array.isArray(value)) return null
96 return value.every((item) => typeof item === 'string') ? value : null
97}
98
99/** Activity from the listed output modalities; search/rerank/ocr are none. */
100function activityOf(output: Array<string>): Activity | null {
101 if (output.includes('text')) return 'chat'
102 if (output.includes('embedding')) return 'embeddings'
103 if (output.includes('video')) return 'video'
104 if (output.includes('image')) return 'image'
105 if (output.includes('audio') || output.includes('transcription')) {
106 return 'audio'
107 }
108 return null
109}
110
111function endpointFor(
112 activity: Activity | null,
113 output: Array<string>,
114): string | null {
115 switch (activity) {
116 case 'chat':
117 return 'v1/chat/completions'
118 case 'embeddings':
119 return 'v1/embeddings'
120 case 'image':
121 return 'v1/images/generations'
122 case 'video':
123 return 'v1/videos'
124 case 'audio':
125 return output.includes('transcription')
126 ? 'v1/audio/transcriptions'
127 : 'v1/audio/speech'
128 default:
129 return null
130 }
131}
132
133interface RoutePrices {
134 base: Record<string, number>
135 tiers: Array<TokenRateTier>
136}
137
138/**
139 * Lever rates of one price object, or null when it quotes a key this does
140 * not read. `skip` keys are read by the caller. The base drops zeros (an
141 * unpriced lever); a band keeps them, since a band's 0 overrides the base.
142 */
143function leverRates(
144 pricing: Record<string, unknown>,
145 skip: ReadonlySet<string>,
146 dropZeros: boolean,
147): Record<string, number> | null {
148 const out: Record<string, number> = {}
149 for (const [key, value] of Object.entries(pricing)) {
150 if (skip.has(key)) continue
151 const n = typeof value === 'string' ? Number(value) : NaN
152 if (!Number.isFinite(n) || n < 0) return null
153 if (n === 0 && dropZeros) continue
154 const lever = LEVERS[key]
155 if (!lever) return null
156 out[lever] = n
157 }
158 return out
159}
160
161const TIER_META = new Set(['name', 'up_to_tokens'])
162
163/**
164 * The route's token prices, or null when the route quotes nothing or a key
165 * this does not read. `tiers` are context-length bands: the gateway bills
166 * a request at the first band whose `up_to_tokens` is at or above its
167 * prompt tokens (`costs.ts`), so band N applies above band N-1's bound. A
168 * band leaves out a rate it keeps from the base.
169 */
170function routePrices(pricing: unknown): RoutePrices | null {
171 if (!isRecord(pricing)) return null
172 const base = leverRates(pricing, new Set(['tiers']), true)
173 if (!base || !('input_tokens' in base || 'output_tokens' in base)) {
174 return null
175 }
176 const bands = pricing.tiers ?? []
177 if (!Array.isArray(bands)) return null
178 const tiers: Array<TokenRateTier> = []
179 for (const [i, band] of bands.entries()) {
180 if (!isRecord(band)) return null
181 const rates = leverRates(band, TIER_META, false)
182 if (!rates) return null
183 const last = i === bands.length - 1
184 const bound = band.up_to_tokens
185 if (last ? bound !== null : typeof bound !== 'number') return null
186 if (i === 0) continue
187 const below: unknown = (bands[i - 1] as Record<string, unknown>)
188 .up_to_tokens
189 if (typeof below !== 'number') return null
190 tiers.push({ minPromptTokens: below, rates })
191 }
192 return { base, tiers }
193}
194
195function samePrices(a: RoutePrices, b: RoutePrices): boolean {
196 return JSON.stringify(sorted(a)) === JSON.stringify(sorted(b))
197}
198
199function sorted(prices: RoutePrices): unknown {
200 const keys = (rates: Record<string, number>) =>
201 Object.fromEntries(
202 Object.entries(rates).sort(([x], [y]) => x.localeCompare(y)),
203 )
204 return {
205 base: keys(prices.base),
206 tiers: prices.tiers.map((t) => [t.minPromptTokens, keys(t.rates)]),
207 }
208}
209
210/**
211 * The route's own effort list. `none` disables reasoning (openapi.json,
212 * `reasoning_effort`), so a list with it states thinking can be turned
213 * off; a list without it states nothing.
214 */
215function routeReasoning(route: Record<string, unknown>): ModelReasoning | null {
216 if (route.reasoning !== true) return null
217 const efforts = strings(route.reasoning_efforts)
218 if (!efforts || efforts.length === 0) return null
219 return {
220 mode: 'effort',
221 mandatory: efforts.includes('none') ? false : null,
222 efforts,
223 }
224}
225
226function sameReasoning(
227 a: ModelReasoning | null,
228 b: ModelReasoning | null,
229): boolean {
230 return JSON.stringify(a) === JSON.stringify(b)
231}
232
233/** Chat Completions body for the effort values the row lists. */
234function chatRequest(
235 params: Array<string>,
236 reasoning: ModelReasoning | null,
237): ChatRequestMap | null {
238 const maxTokensField = params.includes('max_tokens') ? 'max_tokens' : null
239 const efforts = reasoning?.efforts ?? []
240 const thinking = efforts.includes('high')
241 ? {
242 on: { reasoning_effort: 'high' },
243 off: efforts.includes('none') ? { reasoning_effort: 'none' } : null,
244 levels: Object.fromEntries(
245 SHARED_EFFORT_LEVELS.map((level) => {
246 const value = level === 'off' ? 'none' : level
247 return [level, efforts.includes(value) ? value : null]
248 }),
249 ) as EffortLevelMap,
250 }
251 : null
252 if (maxTokensField === null && thinking === null) return null
253 return {
254 thinking,
255 maxTokensField,
256 developerRole: null,
257 replayReasoningContent: null,
258 store: null,
259 strictTools: null,
260 sessionAffinity: null,
261 cacheControl: null,
262 toolStream: null,
263 reasoningEffort: null,
264 }
265}
266
267function capabilityFlags(params: Array<string>): Array<string> {
268 return [...new Set(params.flatMap((name) => PARAMETER_FLAGS[name] ?? []))]
269}
270
271function deprecated(row: Record<string, unknown>, now: number): boolean {
272 return [row.deprecated_at, row.deactivated_at].some(
273 (at) => typeof at === 'string' && Date.parse(at) <= now,
274 )
275}
276
277function listed(source: RateCard['source'], path: string): FactSource {
278 return {
279 derivation: 'listing',
280 sourceUrl: source.url,
281 sourceHash: source.hash,
282 path,
283 }
284}
285
286interface Route {
287 providerId: string
288 externalId: string
289 row: Record<string, unknown>
290}
291
292function routesOf(row: Record<string, unknown>): Array<Route> {
293 if (!Array.isArray(row.providers)) return []
294 return row.providers.flatMap((route) =>
295 isRecord(route) &&
296 typeof route.providerId === 'string' &&
297 route.providerId.length > 0 &&
298 typeof route.externalId === 'string' &&
299 route.externalId.length > 0
300 ? [
301 {
302 providerId: route.providerId,
303 externalId: route.externalId,
304 row: route,
305 },
306 ]
307 : [],
308 )
309}
310
311export function parseLlmGatewayModels(
312 payload: unknown,
313 source: RateCard['source'],
314 now: number = Date.now(),
315): Array<ModelInfo> {
316 if (!isRecord(payload) || !Array.isArray(payload.data)) {
317 throw new Error('llmgateway: models payload has no data array')
318 }
319 const models: Array<ModelInfo> = []
320 for (const row of payload.data) {
321 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
322 continue
323 }
324 const id = row.id
325 const arch = isRecord(row.architecture) ? row.architecture : {}
326 const input = strings(arch.input_modalities)
327 const output = strings(arch.output_modalities) ?? []
328 const activity = activityOf(output)
329 const routes = routesOf(row)
330 const params = strings(row.supported_parameters) ?? []
331 const flags = capabilityFlags(params)
332 const realtime = routes.some((route) => route.row.realtime === true)
333 const shared: ModelInfo = {
334 rawId: id,
335 activity,
336 modalities:
337 input && input.length > 0 && output.length > 0
338 ? { input, output }
339 : null,
340 releasedAt: positive(row.created),
341 deprecated: deprecated(row, now),
342 // Realtime models are served over a socket, not the listed routes.
343 schemaEndpointId: realtime ? null : endpointFor(activity, output),
344 }
345 const name = typeof row.name === 'string' ? row.name : null
346
347 const routeFacts = routes.map((route) => {
348 const prices = routePrices(route.row.pricing)
349 const card = prices
350 ? compileTokenCard(prices.base, prices.tiers, source, {
351 extraPromptLevers: EXTRA_PROMPT_LEVERS,
352 })
353 : null
354 return { route, prices, card, reasoning: routeReasoning(route.row) }
355 })
356
357 // Bare id: a fact only when every route agrees on it.
358 const [first, ...rest] = routeFacts
359 const prices = first?.prices ?? null
360 const bareCard =
361 first?.card &&
362 prices &&
363 rest.every((r) => r.prices && samePrices(r.prices, prices))
364 ? first.card
365 : null
366 const bareReasoning =
367 first && rest.every((r) => sameReasoning(r.reasoning, first.reasoning))
368 ? first.reasoning
369 : null
370 const single = routes.length === 1 ? routes[0] : undefined
371 // Routes that disagree: no single billed price, so a range over the
372 // pinned rows' cards. The gateway's own route has no pinned row, so
373 // it leaves the range unknown.
374 const range =
375 bareCard || routes.length < 2
376 ? null
377 : pricingRange(
378 routeFacts.map(({ route, card }) => ({
379 model: `${route.providerId}/${id}`,
380 card: route.providerId === SELF ? null : card,
381 })),
382 )
383 models.push(
384 rowInfo({
385 ...shared,
386 displayName: name,
387 contextWindow: positive(row.context_length),
388 maxOutput: activity === 'chat' ? positive(row.max_output) : null,
389 pricing: bareCard,
390 pricingRange: range,
391 // Every route priced and they differ: the listing states there is
392 // no one price. A route this cannot read leaves it a plain omission.
393 ...(routes.length > 1 &&
394 !bareCard &&
395 routeFacts.every((r) => r.card !== null)
396 ? { absent: { pricing: 'cleared' as const } }
397 : {}),
398 reasoning: bareReasoning,
399 aliases: strings(row.aliases),
400 upstream: single ? upstreamOf(single, source) : null,
401 pricePath: 'data[].providers[].pricing',
402 flags,
403 params,
404 source,
405 }),
406 )
407
408 // Pinned `provider/model` rows: one per route, that route's facts.
409 for (const { route, card, reasoning } of routeFacts) {
410 if (route.providerId === SELF) continue
411 const routeFlags =
412 route.row.tools === false
413 ? flags.filter((flag) => flag !== 'tools' && flag !== 'tool_choice')
414 : flags
415 models.push(
416 rowInfo({
417 ...shared,
418 rawId: `${route.providerId}/${id}`,
419 displayName: name ? `${name} (${route.providerId})` : null,
420 // The listed context is the model's largest; a pinned route
421 // may be a smaller deployment.
422 contextWindow: single ? positive(row.context_length) : null,
423 maxOutput:
424 activity === 'chat' ? positive(route.row.max_output) : null,
425 pricing: card,
426 reasoning,
427 upstream: upstreamOf(route, source),
428 pricePath: `data[].providers[providerId=${route.providerId}].pricing`,
429 flags: routeFlags,
430 params,
431 source,
432 }),
433 )
434 }
435 }
436 if (models.length === 0) {
437 throw new Error('llmgateway: models payload listed no ids')
438 }
439 return models
440}
441
442function upstreamOf(
443 route: Route,
444 source: RateCard['source'],
445): ModelInfo['upstream'] {
446 if (route.providerId === SELF) return null
447 return {
448 providerNamespace: route.providerId,
449 rawId: route.externalId,
450 source: listed(source, 'data[].providers[].externalId'),
451 }
452}
453
454function rowInfo(
455 info: ModelInfo & {
456 pricePath: string
457 flags: Array<string>
458 params: Array<string>
459 source: RateCard['source']
460 },
461): ModelInfo {
462 const { pricePath, flags, params, source, ...model } = info
463 const factSources: NonNullable<ModelInfo['factSources']> = {}
464 if (model.pricing) factSources.pricing = listed(source, pricePath)
465 if (model.pricingRange) {
466 factSources.pricingRange = listed(source, 'data[].providers[].pricing')
467 }
468 const requestMap =
469 model.activity === 'chat'
470 ? chatRequest(params, model.reasoning ?? null)
471 : null
472 return {
473 ...model,
474 ...(flags.length > 0
475 ? { capabilities: flags, exactCapabilities: true }
476 : {}),
477 ...(requestMap ? { requestMap } : {}),
478 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
479 }
480}
481
482async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
483 const payload = await fetchJson(LLMGATEWAY_MODELS_URL)
484 return {
485 models: parseLlmGatewayModels(payload, {
486 url: LLMGATEWAY_MODELS_URL,
487 hash: await sha256Text(JSON.stringify(payload)),
488 extractedAt: new Date().toISOString(),
489 }),
490 }
491}
492
493async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
494 const { spec, hash } = await fetchOpenApi(LLMGATEWAY_SPEC_URL)
495 return {
496 specs: [spec],
497 sources: [{ url: LLMGATEWAY_SPEC_URL, hash }],
498 outputStrategy: 'post-200',
499 // Unversioned URL: the document hash is the revision id.
500 specRevision: hash,
501 }
502}
503
504export const provider: ProviderConfig = {
505 id: 'llmgateway',
506 displayName: 'LLM Gateway',
507 specSourceUrl: LLMGATEWAY_SPEC_URL,
508 modelsEndpoint: LLMGATEWAY_MODELS_URL,
509 defaultDerivation: 'upstream-spec',
510 specGrain: 'provider',
511 connect: bearerConnect('https://api.llmgateway.io'),
512 fetchSpec,
513 listModels,
514 classify: classifyOpenAiCompat,
515}