theater-reader/server/providers.mjs
agent f353c14619 Transcribe through OpenRouter when OPENROUTER_API_KEY is set
A Claude subscription can't be used by the app, so let it use any cheap
vision model on OpenRouter instead (default google/gemini-3.1-flash-lite,
OPENROUTER_MODEL to change). The Anthropic API stays available as the
second choice. Both providers share the prompt and live behind one
{ name, model, transcribe } interface in server/providers.mjs; OpenRouter
retries 408/429/5xx and network errors and turns 401/402/404 into
messages the editor can show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 15:38:24 +00:00

144 lines
6.2 KiB
JavaScript

// Vision model backends. Each provider is { name, model, transcribe(jpeg) -> markup text }.
// OpenRouter is used when OPENROUTER_API_KEY is set, otherwise the Anthropic API
// when ANTHROPIC_API_KEY is set, otherwise transcription is off.
import Anthropic from "@anthropic-ai/sdk";
import { SYSTEM_PROMPT, USER_PROMPT } from "./prompt.mjs";
export const DEFAULT_CLAUDE_MODEL = "claude-haiku-5-5";
export const DEFAULT_OPENROUTER_MODEL = "google/gemini-3.1-flash-lite";
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
// A failure with a message fit to show in the editor.
export class PageError extends Error {}
export function makeProvider(env) {
if (env.OPENROUTER_API_KEY)
return openRouterProvider({ apiKey: env.OPENROUTER_API_KEY, model: env.OPENROUTER_MODEL || DEFAULT_OPENROUTER_MODEL });
if (env.ANTHROPIC_API_KEY)
return anthropicProvider({ client: new Anthropic({ apiKey: env.ANTHROPIC_API_KEY, maxRetries: 4 }), model: env.CLAUDE_MODEL || DEFAULT_CLAUDE_MODEL });
return null;
}
// ---- Anthropic Messages API (via the official SDK)
export function anthropicProvider({ client, model }) {
return {
name: "anthropic",
model,
async transcribe(jpeg) {
let response;
try {
response = await client.messages.create({
model,
max_tokens: 16000,
// Copying text off a page needs little reasoning; low effort keeps it cheap.
output_config: { effort: "low" },
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
messages: [{
role: "user",
content: [
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: jpeg.toString("base64") } },
{ type: "text", text: USER_PROMPT },
],
}],
});
} catch (err) {
throw new PageError(describeAnthropicError(err));
}
if (response.stop_reason === "refusal") throw new PageError("model declined to transcribe this page");
if (response.stop_reason === "max_tokens") throw new PageError("transcription was cut off (page too long)");
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("").trim();
if (!text) throw new PageError("model returned no text");
return text;
},
};
}
function describeAnthropicError(err) {
if (err instanceof Anthropic.AuthenticationError) return "API key rejected (check ANTHROPIC_API_KEY)";
if (err instanceof Anthropic.PermissionDeniedError) return "API key not allowed to use this model";
if (err instanceof Anthropic.NotFoundError) return "model not found (check CLAUDE_MODEL)";
if (err instanceof Anthropic.RateLimitError) return "rate limited by the API, try again later";
if (err instanceof Anthropic.BadRequestError) return `API rejected the request: ${err.message}`;
if (err instanceof Anthropic.APIError) return `API error ${err.status ?? ""}: ${err.message}`.trim();
return String(err?.message || err);
}
// ---- OpenRouter (OpenAI-style chat completions over plain fetch)
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
export function openRouterProvider({ apiKey, model, fetchImpl = fetch, retries = 3, retryDelayMs = 2000 }) {
async function post(body) {
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetchImpl(OPENROUTER_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"X-Title": "Divadelni ctecka", // shown in the OpenRouter activity log
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(180_000),
});
} catch (err) {
if (attempt < retries) { await sleep(retryDelayMs * 2 ** attempt); continue; }
throw new PageError(`could not reach OpenRouter: ${err.message}`);
}
let data = null;
try { data = await res.json(); } catch { /* not JSON */ }
if (res.ok && !data?.error) return data;
const status = data?.error?.code && Number.isInteger(data.error.code) ? data.error.code : res.status;
if (RETRYABLE.has(status) && attempt < retries) {
const wait = Number(res.headers.get("retry-after")) * 1000 || retryDelayMs * 2 ** attempt;
await sleep(wait);
continue;
}
throw new PageError(describeOpenRouterError(status, data?.error?.message));
}
}
return {
name: "openrouter",
model,
async transcribe(jpeg) {
const data = await post({
model,
max_tokens: 16000,
messages: [
{ role: "system", content: SYSTEM_PROMPT },
{
role: "user",
content: [
{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${jpeg.toString("base64")}` } },
{ type: "text", text: USER_PROMPT },
],
},
],
});
const choice = data?.choices?.[0];
if (!choice) throw new PageError("OpenRouter returned no answer");
if (choice.error) throw new PageError(`model error: ${choice.error.message || "unknown"}`);
if (choice.finish_reason === "content_filter") throw new PageError("model declined to transcribe this page");
if (choice.finish_reason === "length") throw new PageError("transcription was cut off (page too long)");
const content = choice.message?.content;
const text = (Array.isArray(content) ? content.map((c) => c.text || "").join("") : content || "").trim();
if (!text) throw new PageError("model returned no text");
return text;
},
};
}
function describeOpenRouterError(status, message = "") {
const detail = message ? `: ${message}` : "";
switch (status) {
case 401: return "OpenRouter key rejected (check OPENROUTER_API_KEY)";
case 402: return "OpenRouter account is out of credit";
case 403: return `OpenRouter refused the request${detail}`;
case 404: return `model not found or can't read images (check OPENROUTER_MODEL)${detail}`;
case 429: return "rate limited by OpenRouter, try again later";
default: return `OpenRouter error ${status}${detail}`;
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));