Study/server/ai/providers/openrouter.ts
Elijah 25bc03ea75
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s
Fourth revision: OpenRouter, live tool stages, Explain layout, share sections
- Interactive blocks are encouraged by default; Explain gets a reduced library
  and never writes practice questions.
- Assistant tool steps breathe while running, show live stages from generation
  and the Python check, and read in the past tense when done.
- The assistant asks before searching the web when class materials do not
  cover a question; clarifying questions list every class's exams and never
  ask about format (always NCLEX).
- Explain opens beside the question from 900px wide, moving the question left
  while open and back on the next one.
- Generate dialog drops the practice set/exam switch (presets cover it) and the
  Generate buttons lose their icon.
- Python check notes are green when every check passed, applied fixes neutral.
- Share pages group by exam, then Quizzes, Flashcards, Notes, Class Materials,
  hiding empty groups; the class page uses the same order. "Documents" is now
  "Class Materials".
- OpenRouter provider replaces the Ollama type; migration 6 turns Ollama
  connections into OpenAI-compatible ones at /v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:54:39 -07:00

81 lines
3.5 KiB
TypeScript

/**
* 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<DiscoveredModel[]> {
return listCompatModels(options(cfg), signal, timeoutMs);
}
async function test(cfg: ProviderConfig): Promise<TestResult> {
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,
};