diff --git a/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md b/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
index 0198951..8244a19 100644
--- a/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
+++ b/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
@@ -8,7 +8,9 @@
**Ist-Stand API (Superadmin):**
- `GET /api/admin/ai-prompts`, `GET /api/admin/ai-prompts/{id}`, `PUT …`, `POST …/preview`, `POST …/reset-template`, `GET /api/admin/ai-prompts/catalog/placeholders`
-- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter; **`NULL`/leer ⇒ `OPENROUTER_MODEL`** aus der Umgebung.
+- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter. Leer ⇒ Plattform-Standard.
+- **Plattform-Standard** (Migration **097**, `platform_ai_settings.openrouter_model`): Superadmin unter `/admin/openrouter`. `GET/PUT /api/admin/openrouter/settings`, Katalog `GET /api/admin/openrouter/models`. Leer ⇒ **`OPENROUTER_MODEL`** aus der Umgebung.
+- Auflösung: Prompt-Override, sonst Datenbank-Standard, sonst Umgebung.
**Autor:** Claude Code
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
diff --git a/.claude/docs/technical/DATABASE_SCHEMA.md b/.claude/docs/technical/DATABASE_SCHEMA.md
index 2531f54..3e002fb 100644
--- a/.claude/docs/technical/DATABASE_SCHEMA.md
+++ b/.claude/docs/technical/DATABASE_SCHEMA.md
@@ -271,6 +271,7 @@ exercise_variants (id, exercise_id, name, description, ...)
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
platform_media_storage (id, local_relative_root, …)
+platform_ai_settings (id = 1, openrouter_model NULL = OPENROUTER_MODEL, …) -- Migration 097
```
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
index b46e857..0ff545c 100644
--- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
+++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
@@ -38,6 +38,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
| ai_skill_retrieval_admin | `/api/admin/ai-skill-retrieval-profiles*` (CRUD) | Plattform | `require_auth` | nur `superadmin`; JSON `config` | EXEMPT wie `admin_users`; kein Vereinsbezug |
| ai_prompts_admin | `/api/admin/ai-prompts*` (Liste, Detail, PUT, Preview, Reset) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale `ai_prompts` ohne Mandantenkontext |
+| openrouter_admin | `GET/PUT /api/admin/openrouter/settings`, `GET /api/admin/openrouter/models` | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Plattform-Standardmodell und OpenRouter-Katalog, kein Vereinsbezug, kein API-Key in der Antwort |
| exercise_enrichment_admin | `/api/admin/exercise-enrichment/*` (Kandidaten, Preview, Apply) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; plattformweite Übungsliste + Skill-Schreibung; kein TenantContext |
| admin_user_content | `/api/admin/user-content/*` (Meta, Nutzer-Summary, Items, PATCH, DELETE) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Moderation nutzerangelegter Inhalte inkl. privat; kein TenantContext |
@@ -45,7 +46,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
-Letzte Änderung: 2026-06-06 — Superadmin `/api/admin/user-content/*` (Nutzer-Inhalte Moderation).
+Letzte Änderung: 2026-11-23 — Superadmin `/api/admin/openrouter/settings` und `/api/admin/openrouter/models`.
---
diff --git a/.env.example b/.env.example
index 9a04380..f052b5d 100644
--- a/.env.example
+++ b/.env.example
@@ -38,8 +38,9 @@ OPENROUTER_MODEL=anthropic/claude-sonnet-4
# Vereins-Kontingente hart blockieren (KI-Kosten!). Nur 1, true oder yes aktivieren.
# Nach Änderung: docker compose -f docker-compose.dev-env.yml up -d backend
CLUB_FEATURE_ENFORCE=1
-# Standard-OpenRouter-Modell (alle Aufrufe). Optional pro Prompt in ai_prompts.openrouter_model
-# ueberschreibbar (Migration 070, Superadmin unter „KI Prompts“).
+# Fallback-OpenRouter-Modell, wenn kein Plattform-Standard gespeichert ist.
+# Superadmin: Administration → KI-Modell (platform_ai_settings, Migration 097).
+# Optional pro Prompt in ai_prompts.openrouter_model (Migration 070, „KI Prompts“).
# Übungs-KI (Docker): ohne Eintrag im compose „environment:“ landet keine .env-Zeile im Container.
# Hier ist SHINKAN_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs (exercise_ai, openrouter).
diff --git a/backend/main.py b/backend/main.py
index 210ed6d..8ab8407 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -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)
diff --git a/backend/migrations/097_platform_ai_settings.sql b/backend/migrations/097_platform_ai_settings.sql
new file mode 100644
index 0000000..2b6f032
--- /dev/null
+++ b/backend/migrations/097_platform_ai_settings.sql
@@ -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';
diff --git a/backend/openrouter_chat.py b/backend/openrouter_chat.py
index 516b2dc..6485517 100644
--- a/backend/openrouter_chat.py
+++ b/backend/openrouter_chat.py
@@ -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,
+ }
diff --git a/backend/routers/ai_prompts_admin.py b/backend/routers/ai_prompts_admin.py
index 44861f2..e674a31 100644
--- a/backend/routers/ai_prompts_admin.py
+++ b/backend/routers/ai_prompts_admin.py
@@ -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(
"""
diff --git a/backend/routers/openrouter_admin.py b/backend/routers/openrouter_admin.py
new file mode 100644
index 0000000..6a3593f
--- /dev/null
+++ b/backend/routers/openrouter_admin.py
@@ -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
diff --git a/backend/scripts/check_access_layer_hints.py b/backend/scripts/check_access_layer_hints.py
index 8ade257..7396c41 100644
--- a/backend/scripts/check_access_layer_hints.py
+++ b/backend/scripts/check_access_layer_hints.py
@@ -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
diff --git a/backend/tests/test_openrouter_admin.py b/backend/tests/test_openrouter_admin.py
new file mode 100644
index 0000000..fc04c01
--- /dev/null
+++ b/backend/tests/test_openrouter_admin.py
@@ -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
diff --git a/backend/version.py b/backend/version.py
index 138cb58..c85bead 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -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",
diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md
index 3f7929b..864fda8 100644
--- a/docs/HANDOVER.md
+++ b/docs/HANDOVER.md
@@ -156,10 +156,10 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **Planungs-Übungssuche:** siehe Tabelle oben — getrennt von Formular-KI.
- **Doku:** Umsetzung `.claude/docs/working/AI_EXERCISE_IMPLEMENTATION_PLAN.md`; Profil-/JSON-Konzept `.claude/docs/working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`; Ist-Prompt/UI **`AI_PROMPT_SYSTEM_SPEC.md`**; API-Felder **`KI_FEATURES_SPEC.md`** §5.2
- **Kontext / Job:** **`ai_prompt_context`** (Titel, Ziel, Durchführung, Vorbereitung, Trainer-Hinweise, Fokus); **`ai_prompt_job`** — **`run_exercise_form_ai_suggestion`**; **`ai_prompt_runtime`**; **`exercise_ai`** — OpenRouter
-- **DB:** **`067`** ai_prompts · **`069`** default_template · **`068`** ai_skill_retrieval_profiles · **`070`** openrouter_model · **`071`** **`exercise_instruction_rewrite`**
+- **DB:** **`067`** ai_prompts · **`069`** default_template · **`068`** ai_skill_retrieval_profiles · **`070`** openrouter_model · **`071`** **`exercise_instruction_rewrite`** · **`097`** `platform_ai_settings` (Plattform-Standardmodell)
- **Prompt-Slugs:** `exercise_summary`, `exercise_skill_suggestions`, **`exercise_instruction_rewrite`** (Anleitung JSON, prägnant, HTML p/ul/ol/li)
- **API:** `POST /api/exercises/ai/suggest` — **`include_instructions`**, Body **`preparation`**, **`trainer_notes`**; Response **`instructions.fields`**; **`POST …/ai/regenerate`** mit **`instructions`** in `regenerate`
-- **Pflege:** Superadmin **`/admin/ai-prompts`**, **`/admin/ai-skill-retrieval`**
+- **Pflege:** Superadmin **`/admin/openrouter`** (Modellkatalog, Standardmodell), **`/admin/ai-prompts`** (Override pro Prompt aus derselben Liste), **`/admin/ai-skill-retrieval`**
- **Diagnose:** **`SHINKAN_AI_DEBUG=1`** — Logs `shinkan.exercise_ai`, `shinkan.openrouter`
- **Frontend Formular:** Tab **Anleitung** — **„KI: Anleitung überarbeiten“**; Vorschau-Dialog pro Feld (**`ExerciseFormPageRoot.jsx`**)
- **Frontend Schnellanlage:** **`ExercisePickerModal`** (Planung/Rahmen) — Volltext vs. Planungs-KI; KI-Neuanlage im Picker. **`ExercisesListPageRoot`** — Schalter **„Neu mit KI-Assistent“**: Planungs-KI-Suche (`usePlanningExerciseSuggestSearch`) + **`ExerciseAiQuickCreateModal`**; normales **„+ Neu“** ausgeblendet solange aktiv.
diff --git a/docs/jinkendo-family/design-principles/AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md b/docs/jinkendo-family/design-principles/AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md
index 3a05cbd..b1280c1 100644
--- a/docs/jinkendo-family/design-principles/AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md
+++ b/docs/jinkendo-family/design-principles/AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md
@@ -88,7 +88,7 @@ Schmale Ausführungsschicht für admin-konfigurierbare Prompts in `ai_prompts`:
| **Begründung** | Modellwechsel ohne Router-Anpassung. |
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.2 |
| **Tragfähigkeit** | **hoch** |
-| **Einschränkung** | Modell teils global Env, teils Spalte `openrouter_model` — Konvergenz offen. |
+| **Einschränkung** | Auflösung: Prompt-Spalte `openrouter_model`, sonst `platform_ai_settings` (Migration 097), sonst `OPENROUTER_MODEL`. |
### 6. Reset-to-default für System-Prompts
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index a23455d..9edee62 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -64,6 +64,7 @@ const LegalPage = lazy(() => import('./pages/LegalPage'))
const AdminLegalDocumentsPage = lazy(() => import('./pages/AdminLegalDocumentsPage'))
const AdminAiSkillRetrievalPage = lazy(() => import('./pages/AdminAiSkillRetrievalPage'))
const AdminAiPromptsPage = lazy(() => import('./pages/AdminAiPromptsPage'))
+const AdminOpenRouterPage = lazy(() => import('./pages/AdminOpenRouterPage'))
const AdminExerciseEnrichmentPage = lazy(() => import('./pages/AdminExerciseEnrichmentPage'))
const AdminUserContentPage = lazy(() => import('./pages/AdminUserContentPage'))
const SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
@@ -387,6 +388,14 @@ const appRouter = createBrowserRouter([
),
},
+ {
+ path: 'admin/openrouter',
+ element: (
+
+ {loading + ? 'Modelle werden geladen …' + : `${visible.length} von ${models.length} Modellen`} +
+ ++ OpenRouter ist gerade nicht erreichbar. Angezeigt wird die zuletzt geladene Liste. +
+ ) : null} + {error ?{error}
: null} + +
+ Gespeichert ist {value}. Diese ID steht in der aktuellen OpenRouter-Liste nicht.
+
+ Die aktuelle Auswahl {selected.id} passt nicht zu Suche oder Filtern.
+
Ziel hier
') @@ -80,6 +82,7 @@ export default function AdminAiPromptsPage() { setDetail(null) return } + setModelListOpen(false) let cancelled = false ;(async () => { try { @@ -264,15 +267,35 @@ export default function AdminAiPromptsPage() { />
+ {draftOpenrouterModel ? (
+ <>
+ Gewählt: {draftOpenrouterModel}
+ >
+ ) : (
+ <>
+ Plattformstandard.{' '}
+ KI-Modell festlegen
+ >
+ )}
+