Let superadmins choose the OpenRouter model from the live catalog.
Deploy Development / deploy (push) Successful in 1m0s
Test Suite / pytest-backend (push) Successful in 50s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 20s
Test Suite / k6 /health Baseline (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 7m52s

The platform default can be replaced in the admin UI when a model is no longer available, without editing OPENROUTER_MODEL.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-23 09:38:56 +01:00
1 parent 1bdb039a91
commit f49de9c971
21 files changed
+1246 -35

No files matched your search

+259 -8
View File
@@ -1,12 +1,19 @@
"""
Minimal OpenRouter REST client (sync). Reads OPENROUTER_API_KEY / OPENROUTER_MODEL / OPENROUTER_BASE_URL from env.
Minimal OpenRouter REST client (sync).
API-Key und Basis-URL aus der Umgebung. Das wirksame Standardmodell kommt aus
platform_ai_settings (Superadmin), sonst aus OPENROUTER_MODEL.
"""
from __future__ import annotations
import json
import logging
import os
from typing import Any, Dict, List, Mapping, Optional
import re
import threading
import time
from datetime import datetime, timezone
from typing import Any, Dict, List, Mapping, Optional, Tuple
import httpx
@@ -206,21 +213,101 @@ def openrouter_chat_completion(
return joined
_MODEL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@+/-]{0,198}$")
_CATALOG_TTL_SEC = 600
_catalog_lock = threading.Lock()
_catalog_cache: Dict[str, Any] = {"fetched_at": 0.0, "fetched_at_iso": None, "models": None}
_settings_read_failed = False
_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
def openrouter_base_url() -> str:
return (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1"
def normalize_openrouter_model_id(raw: Optional[str]) -> Optional[str]:
"""Leer wird None. Ungültige IDs werfen ValueError."""
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
if any(ch.isspace() for ch in text):
raise ValueError("OpenRouter-Modell-ID darf keine Leer- oder Steuerzeichen enthalten.")
if (
not _MODEL_ID_RE.match(text)
or "/" not in text
or text.startswith("/")
or text.endswith("/")
or "//" in text
):
raise ValueError("OpenRouter-Modell-ID muss wie anbieter/modell aussehen.")
return text
def env_openrouter_model_id() -> str:
model = (os.getenv("OPENROUTER_MODEL") or _FALLBACK_MODEL).strip()
return model or _FALLBACK_MODEL
def resolve_default_openrouter_model_id(
stored: Optional[str],
env_model: Optional[str] = None,
) -> Tuple[str, str]:
"""Wirksame ID und Quelle (`database` oder `environment`)."""
custom: Optional[str] = None
try:
custom = normalize_openrouter_model_id(stored)
except ValueError:
custom = None
if custom:
return custom, "database"
env = env_openrouter_model_id() if env_model is None else (str(env_model).strip() or _FALLBACK_MODEL)
return env or _FALLBACK_MODEL, "environment"
def read_stored_platform_openrouter_model() -> Optional[str]:
"""Gespeichertes Plattformmodell. Bei fehlender Tabelle oder DB-Fehler: None."""
global _settings_read_failed
try:
from db import get_cursor, get_db
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
row = cur.fetchone()
_settings_read_failed = False
if not row:
return None
raw = row.get("openrouter_model") if isinstance(row, dict) else row[0]
text = str(raw or "").strip()
return text or None
except Exception as exc:
if not _settings_read_failed:
_logger.warning(
"Plattform-OpenRouter-Modell nicht lesbar, nutze OPENROUTER_MODEL: %s",
exc,
)
_settings_read_failed = True
return None
def normalize_openrouter_env() -> tuple[str, str]:
"""API-Key und Env-Modell. Das wirksame Modell liefert default_openrouter_model_id()."""
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
model = (os.getenv("OPENROUTER_MODEL") or "anthropic/claude-sonnet-4").strip()
return key, model
return key, env_openrouter_model_id()
def default_openrouter_model_id() -> str:
"""Standard-Modell aus OPENROUTER_MODEL (ohne API-Key zu pruefen)."""
_, model = normalize_openrouter_env()
return model
"""Plattform-Standard aus der Datenbank, sonst OPENROUTER_MODEL."""
effective, _source = resolve_default_openrouter_model_id(read_stored_platform_openrouter_model())
return effective
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
"""
Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Env-Default.
Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Plattform-Standard.
`row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …).
"""
@@ -229,3 +316,167 @@ def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]])
if custom:
return custom
return default_openrouter_model_id()
def _price_str(pricing: Any, key: str) -> Optional[str]:
if not isinstance(pricing, dict):
return None
raw = pricing.get(key)
if raw is None or raw == "":
return None
try:
float(str(raw))
except (TypeError, ValueError):
return None
return str(raw)
def _modalities(item: Mapping[str, Any], side: str) -> List[str]:
arch = item.get("architecture") if isinstance(item.get("architecture"), dict) else {}
key = "input_modalities" if side == "input" else "output_modalities"
raw = arch.get(key)
if isinstance(raw, list):
out = [str(x).strip().lower() for x in raw if str(x).strip()]
if out:
return out
modality = str(arch.get("modality") or "")
parts = modality.split("->")
chunk = parts[0] if side == "input" else (parts[1] if len(parts) > 1 else "")
return [p.strip().lower() for p in chunk.split("+") if p.strip()]
def _context_length(item: Mapping[str, Any]) -> Optional[int]:
candidates = [item.get("context_length")]
top = item.get("top_provider")
if isinstance(top, dict):
candidates.append(top.get("context_length"))
for raw in candidates:
try:
value = int(raw)
except (TypeError, ValueError):
continue
if value > 0:
return value
return None
def parse_openrouter_models_payload(data: Any) -> List[Dict[str, Any]]:
"""OpenRouter `/models` auf eine schlanke, stabile Liste bringen."""
rows = data.get("data") if isinstance(data, dict) else None
if not isinstance(rows, list):
raise OpenRouterError("OpenRouter: Modellliste ohne data-Array")
out: List[Dict[str, Any]] = []
seen = set()
for item in rows:
if not isinstance(item, dict):
continue
model_id = str(item.get("id") or "").strip()
if not model_id or model_id in seen:
continue
seen.add(model_id)
provider = model_id.split("/", 1)[0]
description = str(item.get("description") or "").replace("\r", " ").replace("\n", " ").strip()
if len(description) > 400:
description = description[:397].rstrip() + "…"
prompt_price = _price_str(item.get("pricing"), "prompt")
completion_price = _price_str(item.get("pricing"), "completion")
try:
prompt_num = float(prompt_price) if prompt_price is not None else None
completion_num = float(completion_price) if completion_price is not None else None
except ValueError:
prompt_num = None
completion_num = None
is_free = model_id.endswith(":free") or (
prompt_num == 0 and completion_num == 0 and (prompt_num is not None or completion_num is not None)
)
out.append(
{
"id": model_id,
"name": str(item.get("name") or model_id).strip() or model_id,
"description": description,
"context_length": _context_length(item),
"prompt_usd_per_token": prompt_price,
"completion_usd_per_token": completion_price,
"input_modalities": _modalities(item, "input"),
"output_modalities": _modalities(item, "output"),
"provider": provider,
"is_free": bool(is_free),
}
)
out.sort(key=lambda row: (row["name"].lower(), row["id"].lower()))
return out
def clear_openrouter_model_catalog_cache() -> None:
with _catalog_lock:
_catalog_cache["fetched_at"] = 0.0
_catalog_cache["fetched_at_iso"] = None
_catalog_cache["models"] = None
def _download_openrouter_models() -> List[Dict[str, Any]]:
url = f"{openrouter_base_url()}/models"
headers: Dict[str, str] = {"Accept": "application/json"}
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
if key:
headers["Authorization"] = f"Bearer {key}"
referer = (os.getenv("APP_URL") or "").strip()
if referer:
headers["HTTP-Referer"] = referer
title = (os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip()
if title:
headers["X-Title"] = title
try:
with httpx.Client(timeout=25.0) as client:
resp = client.get(url, headers=headers)
except httpx.RequestError as exc:
raise OpenRouterError("Verbindung zu OpenRouter fehlgeschlagen") from exc
if resp.status_code >= 400:
raise OpenRouterError(f"OpenRouter antwortet mit HTTP {resp.status_code}")
try:
payload = resp.json()
except json.JSONDecodeError as exc:
raise OpenRouterError("OpenRouter hat kein gültiges JSON geliefert") from exc
return parse_openrouter_models_payload(payload)
def fetch_openrouter_model_catalog(*, force: bool = False) -> Dict[str, Any]:
"""Modellkatalog, zehn Minuten im Prozess zwischengespeichert."""
now = time.monotonic()
with _catalog_lock:
cached = _catalog_cache.get("models")
age = now - float(_catalog_cache.get("fetched_at") or 0)
if isinstance(cached, list) and not force and age < _CATALOG_TTL_SEC:
return {
"models": cached,
"count": len(cached),
"cached": True,
"stale": False,
"fetched_at": _catalog_cache.get("fetched_at_iso"),
}
try:
models = _download_openrouter_models()
except OpenRouterError:
with _catalog_lock:
cached = _catalog_cache.get("models")
if isinstance(cached, list):
return {
"models": cached,
"count": len(cached),
"cached": True,
"stale": True,
"fetched_at": _catalog_cache.get("fetched_at_iso"),
}
raise
fetched_iso = datetime.now(timezone.utc).isoformat()
with _catalog_lock:
_catalog_cache["models"] = models
_catalog_cache["fetched_at"] = time.monotonic()
_catalog_cache["fetched_at_iso"] = fetched_iso
return {
"models": models,
"count": len(models),
"cached": False,
"stale": False,
"fetched_at": fetched_iso,
}