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. `provider/model` pins one route
9 * ("prefix the model name with the provider name followed by a slash"), so
10 * each route is also listed as its own row with that route's price. The
11 * listing's top-level `pricing` is undocumented and is not used.
12 *
13 * Upstream links come from the route's own `providerId` + `externalId`,
14 * never from `family`. A bare id with several routes has no single upstream.
15 */
16import { compileOpenRouterPricing } from '@modelschemas/rate-card'
17import type { RateCard } from '@modelschemas/rate-card'
18
19import type { Activity } from '#/db/schema.ts'
20
21import { bearerConnect } from '../connect.ts'
22import { classifyOpenAiCompat } from '../openai-compat.ts'
23import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
24import type { ChatRequestMap, EffortLevelMap } from '../request-map.ts'
25import { fetchJson, fetchOpenApi, sha256Text } from '../types.ts'
26import type {
27 FactSource,
28 ListModelsResult,
29 ModelInfo,
30 ModelReasoning,
31 ProviderConfig,
32 ProviderSecrets,
33 SpecFetchResult,
34} from '../types.ts'
35
36export const LLMGATEWAY_MODELS_URL = 'https://api.llmgateway.io/v1/models'
37export const LLMGATEWAY_SPEC_URL = 'https://api.llmgateway.io/openapi.json'
38
39/** Route `providerId` of the gateway's own virtual models (auto, custom). */
40const SELF = 'llmgateway'
41
42/** Listing `supported_parameters` names that are catalog flags. */
43const PARAMETER_FLAGS: Record<string, string> = {
44 tools: 'tools',
45 tool_choice: 'tool_choice',
46 max_tokens: 'max_tokens',
47 max_completion_tokens: 'max_tokens',
48 temperature: 'temperature',
49 top_p: 'top_p',
50 stop: 'stop',
51 seed: 'seed',
52 frequency_penalty: 'frequency_penalty',
53 presence_penalty: 'presence_penalty',
54 response_format: 'response_format',
55 reasoning: 'reasoning',
56 reasoning_effort: 'reasoning_effort',
57}
58
59/**
60 * Price keys whose meaning matches the OpenRouter-style token listing.
61 * A route quoting any other key (`image`, audio, `per_second`, `ocr_page`)
62 * gets no card rather than a guessed one.
63 */
64const TOKEN_PRICE_KEYS = new Set([
65 'prompt',
66 'completion',
67 'input_cache_read',
68 'input_cache_write',
69 'input_cache_write_1h',
70 'request',
71])
72
73function isRecord(value: unknown): value is Record<string, unknown> {
74 return typeof value === 'object' && value !== null && !Array.isArray(value)
75}
76
77function positive(value: unknown): number | null {
78 return typeof value === 'number' && Number.isFinite(value) && value > 0
79 ? value
80 : null
81}
82
83function strings(value: unknown): Array<string> | null {
84 if (!Array.isArray(value)) return null
85 return value.every((item) => typeof item === 'string') ? value : null
86}
87
88/** Activity from the listed output modalities; search/rerank/ocr are none. */
89function activityOf(output: Array<string>): Activity | null {
90 if (output.includes('text')) return 'chat'
91 if (output.includes('embedding')) return 'embeddings'
92 if (output.includes('video')) return 'video'
93 if (output.includes('image')) return 'image'
94 if (output.includes('audio') || output.includes('transcription')) {
95 return 'audio'
96 }
97 return null
98}
99
100function endpointFor(
101 activity: Activity | null,
102 output: Array<string>,
103): string | null {
104 switch (activity) {
105 case 'chat':
106 return 'v1/chat/completions'
107 case 'embeddings':
108 return 'v1/embeddings'
109 case 'image':
110 return 'v1/images/generations'
111 case 'video':
112 return 'v1/videos'
113 case 'audio':
114 return output.includes('transcription')
115 ? 'v1/audio/transcriptions'
116 : 'v1/audio/speech'
117 default:
118 return null
119 }
120}
121
122/**
123 * The route's token prices with zero entries dropped, or null when the
124 * route quotes nothing or a key this does not read.
125 */
126function tokenPrices(pricing: unknown): Record<string, number> | null {
127 if (!isRecord(pricing)) return null
128 const out: Record<string, number> = {}
129 for (const [key, value] of Object.entries(pricing)) {
130 const n = typeof value === 'string' ? Number(value) : NaN
131 if (!Number.isFinite(n) || n < 0) return null
132 if (n === 0) continue
133 if (!TOKEN_PRICE_KEYS.has(key)) return null
134 out[key] = n
135 }
136 return 'prompt' in out || 'completion' in out ? out : null
137}
138
139function samePrices(
140 a: Record<string, number>,
141 b: Record<string, number>,
142): boolean {
143 const keys = Object.keys(a)
144 return (
145 keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k])
146 )
147}
148
149/**
150 * The route's own effort list. `none` disables reasoning (openapi.json,
151 * `reasoning_effort`), so a list with it states thinking can be turned
152 * off; a list without it states nothing.
153 */
154function routeReasoning(route: Record<string, unknown>): ModelReasoning | null {
155 if (route.reasoning !== true) return null
156 const efforts = strings(route.reasoning_efforts)
157 if (!efforts || efforts.length === 0) return null
158 return {
159 mode: 'effort',
160 mandatory: efforts.includes('none') ? false : null,
161 efforts,
162 }
163}
164
165function sameReasoning(
166 a: ModelReasoning | null,
167 b: ModelReasoning | null,
168): boolean {
169 return JSON.stringify(a) === JSON.stringify(b)
170}
171
172/** Chat Completions body for the effort values the row lists. */
173function chatRequest(
174 params: Array<string>,
175 reasoning: ModelReasoning | null,
176): ChatRequestMap | null {
177 const maxTokensField = params.includes('max_tokens') ? 'max_tokens' : null
178 const efforts = reasoning?.efforts ?? []
179 const thinking = efforts.includes('high')
180 ? {
181 on: { reasoning_effort: 'high' },
182 off: efforts.includes('none') ? { reasoning_effort: 'none' } : null,
183 levels: Object.fromEntries(
184 SHARED_EFFORT_LEVELS.map((level) => {
185 const value = level === 'off' ? 'none' : level
186 return [level, efforts.includes(value) ? value : null]
187 }),
188 ) as EffortLevelMap,
189 }
190 : null
191 if (maxTokensField === null && thinking === null) return null
192 return {
193 thinking,
194 maxTokensField,
195 developerRole: null,
196 replayReasoningContent: null,
197 store: null,
198 strictTools: null,
199 sessionAffinity: null,
200 cacheControl: null,
201 toolStream: null,
202 reasoningEffort: null,
203 }
204}
205
206function capabilityFlags(params: Array<string>): Array<string> {
207 return [...new Set(params.flatMap((name) => PARAMETER_FLAGS[name] ?? []))]
208}
209
210function deprecated(row: Record<string, unknown>, now: number): boolean {
211 return [row.deprecated_at, row.deactivated_at].some(
212 (at) => typeof at === 'string' && Date.parse(at) <= now,
213 )
214}
215
216function listed(source: RateCard['source'], path: string): FactSource {
217 return {
218 derivation: 'listing',
219 sourceUrl: source.url,
220 sourceHash: source.hash,
221 path,
222 }
223}
224
225interface Route {
226 providerId: string
227 externalId: string
228 row: Record<string, unknown>
229}
230
231function routesOf(row: Record<string, unknown>): Array<Route> {
232 if (!Array.isArray(row.providers)) return []
233 return row.providers.flatMap((route) =>
234 isRecord(route) &&
235 typeof route.providerId === 'string' &&
236 route.providerId.length > 0 &&
237 typeof route.externalId === 'string' &&
238 route.externalId.length > 0
239 ? [
240 {
241 providerId: route.providerId,
242 externalId: route.externalId,
243 row: route,
244 },
245 ]
246 : [],
247 )
248}
249
250export function parseLlmGatewayModels(
251 payload: unknown,
252 source: RateCard['source'],
253 now: number = Date.now(),
254): Array<ModelInfo> {
255 if (!isRecord(payload) || !Array.isArray(payload.data)) {
256 throw new Error('llmgateway: models payload has no data array')
257 }
258 const models: Array<ModelInfo> = []
259 for (const row of payload.data) {
260 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
261 continue
262 }
263 const id = row.id
264 const arch = isRecord(row.architecture) ? row.architecture : {}
265 const input = strings(arch.input_modalities)
266 const output = strings(arch.output_modalities) ?? []
267 const activity = activityOf(output)
268 const routes = routesOf(row)
269 const params = strings(row.supported_parameters) ?? []
270 const flags = capabilityFlags(params)
271 const realtime = routes.some((route) => route.row.realtime === true)
272 const shared: ModelInfo = {
273 rawId: id,
274 activity,
275 modalities:
276 input && input.length > 0 && output.length > 0
277 ? { input, output }
278 : null,
279 releasedAt: positive(row.created),
280 deprecated: deprecated(row, now),
281 // Realtime models are served over a socket, not the listed routes.
282 schemaEndpointId: realtime ? null : endpointFor(activity, output),
283 }
284 const name = typeof row.name === 'string' ? row.name : null
285
286 const routeFacts = routes.map((route) => {
287 const prices = tokenPrices(route.row.pricing)
288 const card = prices ? compileOpenRouterPricing(prices, source) : null
289 return { route, prices, card, reasoning: routeReasoning(route.row) }
290 })
291
292 // Bare id: a fact only when every route agrees on it.
293 const [first, ...rest] = routeFacts
294 const prices = first?.prices ?? null
295 const bareCard =
296 first?.card &&
297 prices &&
298 rest.every((r) => r.prices && samePrices(r.prices, prices))
299 ? first.card
300 : null
301 const bareReasoning =
302 first && rest.every((r) => sameReasoning(r.reasoning, first.reasoning))
303 ? first.reasoning
304 : null
305 const single = routes.length === 1 ? routes[0] : undefined
306 models.push(
307 rowInfo({
308 ...shared,
309 displayName: name,
310 contextWindow: positive(row.context_length),
311 maxOutput: activity === 'chat' ? positive(row.max_output) : null,
312 pricing: bareCard,
313 reasoning: bareReasoning,
314 aliases: strings(row.aliases),
315 upstream: single ? upstreamOf(single, source) : null,
316 pricePath: 'data[].providers[].pricing',
317 flags,
318 params,
319 source,
320 }),
321 )
322
323 // Pinned `provider/model` rows: one per route, that route's facts.
324 for (const { route, card, reasoning } of routeFacts) {
325 if (route.providerId === SELF) continue
326 const routeFlags =
327 route.row.tools === false
328 ? flags.filter((flag) => flag !== 'tools' && flag !== 'tool_choice')
329 : flags
330 models.push(
331 rowInfo({
332 ...shared,
333 rawId: `${route.providerId}/${id}`,
334 displayName: name ? `${name} (${route.providerId})` : null,
335 // The listed context is the model's largest; a pinned route
336 // may be a smaller deployment.
337 contextWindow: single ? positive(row.context_length) : null,
338 maxOutput:
339 activity === 'chat' ? positive(route.row.max_output) : null,
340 pricing: card,
341 reasoning,
342 upstream: upstreamOf(route, source),
343 pricePath: `data[].providers[providerId=${route.providerId}].pricing`,
344 flags: routeFlags,
345 params,
346 source,
347 }),
348 )
349 }
350 }
351 if (models.length === 0) {
352 throw new Error('llmgateway: models payload listed no ids')
353 }
354 return models
355}
356
357function upstreamOf(
358 route: Route,
359 source: RateCard['source'],
360): ModelInfo['upstream'] {
361 if (route.providerId === SELF) return null
362 return {
363 providerNamespace: route.providerId,
364 rawId: route.externalId,
365 source: listed(source, 'data[].providers[].externalId'),
366 }
367}
368
369function rowInfo(
370 info: ModelInfo & {
371 pricePath: string
372 flags: Array<string>
373 params: Array<string>
374 source: RateCard['source']
375 },
376): ModelInfo {
377 const { pricePath, flags, params, source, ...model } = info
378 const factSources: NonNullable<ModelInfo['factSources']> = {}
379 if (model.pricing) factSources.pricing = listed(source, pricePath)
380 const requestMap =
381 model.activity === 'chat'
382 ? chatRequest(params, model.reasoning ?? null)
383 : null
384 return {
385 ...model,
386 ...(flags.length > 0
387 ? { capabilities: flags, exactCapabilities: true }
388 : {}),
389 ...(requestMap ? { requestMap } : {}),
390 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
391 }
392}
393
394async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
395 const payload = await fetchJson(LLMGATEWAY_MODELS_URL)
396 return {
397 models: parseLlmGatewayModels(payload, {
398 url: LLMGATEWAY_MODELS_URL,
399 hash: await sha256Text(JSON.stringify(payload)),
400 extractedAt: new Date().toISOString(),
401 }),
402 }
403}
404
405async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
406 const { spec, hash } = await fetchOpenApi(LLMGATEWAY_SPEC_URL)
407 return {
408 specs: [spec],
409 sources: [{ url: LLMGATEWAY_SPEC_URL, hash }],
410 outputStrategy: 'post-200',
411 // Unversioned URL: the document hash is the revision id.
412 specRevision: hash,
413 }
414}
415
416export const provider: ProviderConfig = {
417 id: 'llmgateway',
418 displayName: 'LLM Gateway',
419 specSourceUrl: LLMGATEWAY_SPEC_URL,
420 modelsEndpoint: LLMGATEWAY_MODELS_URL,
421 defaultDerivation: 'upstream-spec',
422 specGrain: 'provider',
423 connect: bearerConnect('https://api.llmgateway.io'),
424 fetchSpec,
425 listModels,
426 classify: classifyOpenAiCompat,
427}