/** * OpenRouter — one key for models from many labs, over Chat Completions at * https://openrouter.ai/api/v1. * https://openrouter.ai/docs/api/reference/overview · https://openrouter.ai/docs/guides/best-practices/reasoning-tokens * * The wire format is OpenAI-compatible, so this reuses the compatible engine with what * OpenRouter does differently: * - Reasoning is controlled with `reasoning: { effort }` (xhigh, high, medium, low, minimal) * instead of `reasoning_effort`, and streams back as `delta.reasoning`. * - `/models` is public and rich: context length, top provider output limit, per-token prices * (including cache reads), supported parameters and input modalities. * - `/key` describes the API key, which is how a test proves the key works (the model list * would answer without one). * - `X-Title` names the app in the user's OpenRouter activity log. */ import { AIError, type DiscoveredModel, type ProviderAdapter, type ProviderConfig, type TestResult } from '../types.ts'; import { runTest, TEST_TIMEOUT_MS } from './common.ts'; import { isRecord, requestJson, trimBaseUrl } from './http.ts'; import { listCompatModels, streamChatCompletions, type CompatOptions } from './openaiCompatible.ts'; export const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1'; const LABEL = 'OpenRouter'; function base(cfg: ProviderConfig): string { return trimBaseUrl(cfg.baseUrl?.trim() || OPENROUTER_BASE_URL); } function options(cfg: ProviderConfig): CompatOptions { if (!cfg.apiKey) throw new AIError('not_configured', `Add your OpenRouter API key for "${cfg.name}" in Settings.`); return { kind: 'openrouter', label: cfg.name || LABEL, baseUrl: base(cfg), apiKey: cfg.apiKey, headers: { 'X-Title': 'Study Desk', ...cfg.headers }, adjustBody: (body) => { // OpenRouter's unified reasoning switch. if (typeof body.reasoning_effort === 'string') { body.reasoning = { effort: body.reasoning_effort }; delete body.reasoning_effort; } }, }; } async function listModels(cfg: ProviderConfig, signal?: AbortSignal, timeoutMs?: number): Promise { return listCompatModels(options(cfg), signal, timeoutMs); } async function test(cfg: ProviderConfig): Promise { return runTest(cfg.name || LABEL, async () => { const o = options(cfg); const key = await requestJson(`${base(cfg)}/key`, { provider: o.label, secrets: [o.apiKey, ...Object.values(o.headers ?? {})], headers: { ...o.headers, Authorization: `Bearer ${o.apiKey}` }, firstByteTimeoutMs: TEST_TIMEOUT_MS, totalTimeoutMs: TEST_TIMEOUT_MS, }); const data = isRecord(key) && isRecord(key.data) ? key.data : {}; const models = (await listModels(cfg, undefined, TEST_TIMEOUT_MS)).length; const remaining = typeof data.limit_remaining === 'number' ? data.limit_remaining : null; return { modelCount: models, ...(remaining !== null && remaining <= 0 ? { note: 'Connected, but this key has no credit left. Add credit on openrouter.ai to use paid models.' } : {}) }; }); } export const openrouterAdapter: ProviderAdapter = { kind: 'openrouter', meta: { label: LABEL, defaultBaseUrl: OPENROUTER_BASE_URL, requiresApiKey: true, requiresBaseUrl: false, supportsDiscovery: true, docsUrl: 'https://openrouter.ai/settings/keys', keyHint: 'Starts with sk-or-', }, stream: (cfg, req) => streamChatCompletions(options(cfg), req), listModels: (cfg, signal) => listModels(cfg, signal), test, };