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
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:
1 parent
1bdb039a91
commit
f49de9c971
21 files changed
+1246
-35
No files matched your search
+2
-1
@@ -243,7 +243,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -278,6 +278,7 @@ app.include_router(import_wiki_admin.router)
|
||||
app.include_router(legal_documents.router)
|
||||
app.include_router(content_reports.router)
|
||||
app.include_router(ai_prompts_admin.router)
|
||||
app.include_router(openrouter_admin.router)
|
||||
app.include_router(ai_skill_retrieval_admin.router)
|
||||
app.include_router(exercise_enrichment_admin.router)
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Migration 097: Plattform-Standard für das OpenRouter-Modell (Superadmin).
|
||||
-- NULL = Umgebungsvariable OPENROUTER_MODEL.
|
||||
-- Ein Prompt-Override in ai_prompts.openrouter_model hat weiter Vorrang.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS platform_ai_settings (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1,
|
||||
CONSTRAINT platform_ai_settings_singleton CHECK (id = 1),
|
||||
openrouter_model VARCHAR(200),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO platform_ai_settings (id, openrouter_model)
|
||||
VALUES (1, NULL)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMENT ON COLUMN platform_ai_settings.openrouter_model IS
|
||||
'Plattform-Standard OpenRouter model id; NULL = OPENROUTER_MODEL aus der Umgebung';
|
||||
+259
-8
@@ -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,
|
||||
}
|
||||
@@ -21,6 +21,7 @@ from ai_prompt_planning_preview import (
|
||||
)
|
||||
from ai_prompt_runtime import render_ai_prompt_template_for_row
|
||||
from db import get_cursor, get_db, r2d
|
||||
from openrouter_chat import normalize_openrouter_model_id
|
||||
from prompt_resolver import exercise_placeholder_catalog
|
||||
from planning_prompt_variables import planning_prompt_placeholder_catalog
|
||||
|
||||
@@ -161,10 +162,10 @@ def update_ai_prompt(
|
||||
|
||||
next_openrouter = old.get("openrouter_model")
|
||||
if body.openrouter_model is not None:
|
||||
cand = body.openrouter_model.strip() if isinstance(body.openrouter_model, str) else ""
|
||||
if any(c in cand for c in ("\r", "\n", "\t")):
|
||||
raise HTTPException(status_code=400, detail="openrouter_model: keine Steuerzeichen erlaubt.")
|
||||
next_openrouter = cand or None
|
||||
try:
|
||||
next_openrouter = normalize_openrouter_model_id(body.openrouter_model)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""
|
||||
Superadmin: OpenRouter-Modellkatalog und Plattform-Standardmodell.
|
||||
|
||||
# ACCESS_LAYER exempt: Plattform-KI-Konfiguration ohne Vereinsbezug;
|
||||
# require_auth + is_superadmin, kein TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db, r2d
|
||||
from openrouter_chat import (
|
||||
OpenRouterError,
|
||||
env_openrouter_model_id,
|
||||
fetch_openrouter_model_catalog,
|
||||
normalize_openrouter_model_id,
|
||||
resolve_default_openrouter_model_id,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["admin_openrouter"])
|
||||
|
||||
|
||||
def _require_superadmin(session: dict = Depends(require_auth)) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
class OpenRouterSettingsUpdate(BaseModel):
|
||||
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||
|
||||
|
||||
def _iso(value: Any) -> Optional[str]:
|
||||
if value is None:
|
||||
return None
|
||||
if hasattr(value, "isoformat"):
|
||||
return value.isoformat()
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _settings_payload(stored: Optional[str], updated_at: Any = None) -> dict:
|
||||
effective, source = resolve_default_openrouter_model_id(stored)
|
||||
return {
|
||||
"openrouter_model": stored or None,
|
||||
"effective_model": effective,
|
||||
"env_model": env_openrouter_model_id(),
|
||||
"source": source,
|
||||
"updated_at": _iso(updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _missing_table(exc: Exception) -> bool:
|
||||
text = str(exc).lower()
|
||||
return "platform_ai_settings" in text or "does not exist" in text or "undefinedtable" in text
|
||||
|
||||
|
||||
@router.get("/api/admin/openrouter/settings")
|
||||
def get_openrouter_settings(session: dict = Depends(_require_superadmin)):
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT openrouter_model, updated_at FROM platform_ai_settings WHERE id = 1"
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
except Exception as exc:
|
||||
if _missing_table(exc):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
if not row:
|
||||
return _settings_payload(None, None)
|
||||
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||
return _settings_payload(stored, row.get("updated_at"))
|
||||
|
||||
|
||||
@router.put("/api/admin/openrouter/settings")
|
||||
def put_openrouter_settings(
|
||||
body: OpenRouterSettingsUpdate,
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
try:
|
||||
model = normalize_openrouter_model_id(body.openrouter_model)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
profile_id = session.get("profile_id")
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO platform_ai_settings (id, openrouter_model, updated_at, updated_by_profile_id)
|
||||
VALUES (1, %s, NOW(), %s)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET openrouter_model = EXCLUDED.openrouter_model,
|
||||
updated_at = NOW(),
|
||||
updated_by_profile_id = EXCLUDED.updated_by_profile_id
|
||||
RETURNING openrouter_model, updated_at
|
||||
""",
|
||||
(model, profile_id),
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
except Exception as exc:
|
||||
if _missing_table(exc):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||
) from exc
|
||||
raise
|
||||
if not row:
|
||||
raise HTTPException(status_code=500, detail="platform_ai_settings konnte nicht gespeichert werden.")
|
||||
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||
return _settings_payload(stored, row.get("updated_at"))
|
||||
|
||||
|
||||
@router.get("/api/admin/openrouter/models")
|
||||
def list_openrouter_models(
|
||||
refresh: bool = Query(False),
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
try:
|
||||
return fetch_openrouter_model_catalog(force=refresh)
|
||||
except OpenRouterError as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter-Modellliste nicht erreichbar: {exc}",
|
||||
) from exc
|
||||
@@ -25,6 +25,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
||||
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
||||
"ai_skill_retrieval_admin.py", # Superadmin-Plattform-Konfiguration Skill-KI-Retrieval; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"ai_prompts_admin.py", # Superadmin ai_prompts; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"openrouter_admin.py", # Superadmin OpenRouter-Modell; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"exercise_enrichment_admin.py", # Superadmin Batch-Übungs-Anreicherung KI; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""OpenRouter-Modellkatalog und Plattform-Standard — ohne Live-API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from openrouter_chat import (
|
||||
clear_openrouter_model_catalog_cache,
|
||||
normalize_openrouter_model_id,
|
||||
parse_openrouter_models_payload,
|
||||
resolve_default_openrouter_model_id,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
clear_openrouter_model_catalog_cache()
|
||||
|
||||
|
||||
def _superadmin():
|
||||
return {"profile_id": 7, "role": "superadmin"}
|
||||
|
||||
|
||||
def test_model_id_rejects_free_text():
|
||||
assert normalize_openrouter_model_id(" ") is None
|
||||
assert normalize_openrouter_model_id(None) is None
|
||||
assert normalize_openrouter_model_id("openai/gpt-4o-mini") == "openai/gpt-4o-mini"
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("claude")
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("openai/gpt\n4")
|
||||
with pytest.raises(ValueError):
|
||||
normalize_openrouter_model_id("openai//gpt")
|
||||
|
||||
|
||||
def test_resolve_prefers_stored_model():
|
||||
effective, source = resolve_default_openrouter_model_id(
|
||||
"anthropic/claude-3.5-haiku",
|
||||
"openai/gpt-4o",
|
||||
)
|
||||
assert effective == "anthropic/claude-3.5-haiku"
|
||||
assert source == "database"
|
||||
effective, source = resolve_default_openrouter_model_id("", "openai/gpt-4o")
|
||||
assert effective == "openai/gpt-4o"
|
||||
assert source == "environment"
|
||||
effective, source = resolve_default_openrouter_model_id("kein-slash", "openai/gpt-4o")
|
||||
assert effective == "openai/gpt-4o"
|
||||
assert source == "environment"
|
||||
|
||||
|
||||
def test_parse_models_payload_keeps_filter_fields():
|
||||
rows = parse_openrouter_models_payload(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "openai/gpt-4o-mini",
|
||||
"name": "OpenAI: GPT-4o mini",
|
||||
"description": "Klein\nund schnell",
|
||||
"context_length": 128000,
|
||||
"architecture": {
|
||||
"input_modalities": ["text", "image"],
|
||||
"output_modalities": ["text"],
|
||||
},
|
||||
"pricing": {"prompt": "0.00000015", "completion": "0.0000006"},
|
||||
},
|
||||
{
|
||||
"id": "meta-llama/llama-3.1-8b-instruct:free",
|
||||
"name": "Llama 3.1 8B (free)",
|
||||
"architecture": {"modality": "text->text"},
|
||||
"pricing": {"prompt": "0", "completion": "0"},
|
||||
},
|
||||
{"id": "", "name": "leer"},
|
||||
"kein-objekt",
|
||||
]
|
||||
}
|
||||
)
|
||||
assert [row["id"] for row in rows] == [
|
||||
"meta-llama/llama-3.1-8b-instruct:free",
|
||||
"openai/gpt-4o-mini",
|
||||
]
|
||||
mini = rows[1]
|
||||
assert mini["provider"] == "openai"
|
||||
assert mini["context_length"] == 128000
|
||||
assert mini["input_modalities"] == ["text", "image"]
|
||||
assert mini["is_free"] is False
|
||||
assert "\n" not in mini["description"]
|
||||
assert rows[0]["is_free"] is True
|
||||
assert rows[0]["input_modalities"] == ["text"]
|
||||
|
||||
|
||||
def test_models_requires_superadmin(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
|
||||
response = client.get("/api/admin/openrouter/models", headers={"X-Auth-Token": "t"})
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_models_returns_catalog_for_superadmin(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
payload = {
|
||||
"models": [{"id": "openai/gpt-4o-mini", "name": "GPT-4o mini"}],
|
||||
"count": 1,
|
||||
"cached": False,
|
||||
"stale": False,
|
||||
"fetched_at": "2026-11-23T08:00:00+00:00",
|
||||
}
|
||||
with patch(
|
||||
"routers.openrouter_admin.fetch_openrouter_model_catalog",
|
||||
return_value=payload,
|
||||
) as fetch:
|
||||
response = client.get("/api/admin/openrouter/models?refresh=true", headers={"X-Auth-Token": "t"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["count"] == 1
|
||||
fetch.assert_called_once_with(force=True)
|
||||
|
||||
|
||||
def test_settings_put_rejects_invalid_id(client: TestClient):
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
response = client.put(
|
||||
"/api/admin/openrouter/settings",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "nur-text"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
@patch("routers.openrouter_admin.get_db")
|
||||
def test_settings_put_stores_model(mock_get_db, client: TestClient, monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
mock_get_db.return_value = mock_cm
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = {
|
||||
"openrouter_model": "openai/gpt-4o-mini",
|
||||
"updated_at": "2026-11-23T08:00:00+00:00",
|
||||
}
|
||||
with patch("routers.openrouter_admin.get_cursor", return_value=cur):
|
||||
response = client.put(
|
||||
"/api/admin/openrouter/settings",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"openrouter_model": "openai/gpt-4o-mini"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["openrouter_model"] == "openai/gpt-4o-mini"
|
||||
assert body["effective_model"] == "openai/gpt-4o-mini"
|
||||
assert body["source"] == "database"
|
||||
assert body["env_model"] == "anthropic/claude-sonnet-4"
|
||||
params = cur.execute.call_args.args[1]
|
||||
assert params[0] == "openai/gpt-4o-mini"
|
||||
assert params[1] == 7
|
||||
+12
-4
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.247"
|
||||
BUILD_DATE = "2026-10-29"
|
||||
DB_SCHEMA_VERSION = "20261012096"
|
||||
APP_VERSION = "0.8.248"
|
||||
BUILD_DATE = "2026-11-23"
|
||||
DB_SCHEMA_VERSION = "20261123097"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -29,7 +29,8 @@ MODULE_VERSIONS = {
|
||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
"admin_ai_skill_retrieval": "1.0.0", # Superadmin CRUD /api/admin/ai-skill-retrieval-profiles (Migration 068)
|
||||
"exercise_enrichment_admin": "1.1.1", # Preview max 3/Request + parallel LLM (Gateway-504 vermeiden)
|
||||
"admin_ai_prompts": "1.0.5", # H2: granulare Katalog-Slot-Platzhalter im Katalog
|
||||
"admin_ai_prompts": "1.0.6", # Prompt-Modell aus OpenRouter-Katalog statt Freitext
|
||||
"admin_openrouter": "1.0.0", # Superadmin: Plattform-Standardmodell, Live-Katalog OpenRouter
|
||||
"ai_prompt_job": "0.2.1", # want_instructions; run_exercise_form_ai_suggestion
|
||||
"ai_prompt_context": "0.2.0", # preparation/trainer_notes; has_instruction_source_text
|
||||
"ai_prompt_runtime": "0.2.2", # Slug planning_exercise_expectation_profile
|
||||
@@ -53,6 +54,13 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.248",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Superadmin wählt unter Administration → KI-Modell das OpenRouter-Standardmodell aus der live geladenen, filterbaren Modellliste. Gespeichert in platform_ai_settings (Migration 097); OPENROUTER_MODEL bleibt Fallback. Prompt-Overrides nutzen dieselbe Liste.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.247",
|
||||
"date": "2026-10-29",
|
||||
|
||||
Reference in new issue
Block a user