Files
shinkan-jinkendo/backend/routers/openrouter_admin.py
T
LarsandCursor b537750671
Deploy Development / deploy (push) Successful in 53s
Test Suite / pytest-backend (push) Successful in 50s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m40s
Let superadmins assign one OpenRouter model per task group.
Reasoning, drafting, and matching prompts inherit that model, so each prompt does not need its own setting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 09:59:28 +01:00

313 lines
11 KiB
Python

"""
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, ConfigDict, Field
from auth import require_auth
from club_tenancy import is_superadmin
from db import get_cursor, get_db, r2d
from ai_model_roles import ROLE_KEYS, resolve_prompt_openrouter_model
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)
class OpenRouterRoleUpdate(BaseModel):
openrouter_model: Optional[str] = Field(None, max_length=200)
class OpenRouterPromptRoleUpdate(BaseModel):
model_config = ConfigDict(protected_namespaces=())
model_role: Optional[str] = Field(None, max_length=40)
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"))
def _prompt_view(row: dict, role_models: dict, platform_model: Optional[str], env_model: str) -> dict:
prompt_model = str(row.get("openrouter_model") or "").strip() or None
role_key = str(row.get("model_role") or "").strip() or None
effective, source = resolve_prompt_openrouter_model(
prompt_model=prompt_model,
role_model=role_models.get(role_key or ""),
platform_model=platform_model,
env_model=env_model,
)
return {
"id": row.get("id"),
"slug": row.get("slug"),
"display_name": row.get("display_name"),
"model_role": role_key,
"openrouter_model": prompt_model,
"effective_model": effective,
"source": source,
}
def _load_role_overview(cur) -> dict:
cur.execute(
"""
SELECT role_key, display_name, description, openrouter_model, sort_order
FROM platform_ai_model_roles
ORDER BY sort_order ASC, role_key ASC
"""
)
role_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
cur.execute(
"""
SELECT id, slug, display_name, model_role, openrouter_model, sort_order
FROM ai_prompts
ORDER BY sort_order ASC NULLS LAST, id ASC
"""
)
prompt_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
settings = r2d(cur.fetchone())
platform_model = str((settings or {}).get("openrouter_model") or "").strip() or None
env_model = env_openrouter_model_id()
role_models = {
str(row.get("role_key") or ""): str(row.get("openrouter_model") or "").strip() or None
for row in role_rows
}
prompts = [_prompt_view(row, role_models, platform_model, env_model) for row in prompt_rows]
roles = []
for row in role_rows:
key = str(row.get("role_key") or "")
stored = role_models.get(key)
effective, source = resolve_prompt_openrouter_model(
prompt_model=None,
role_model=stored,
platform_model=platform_model,
env_model=env_model,
)
roles.append(
{
"role_key": key,
"display_name": row.get("display_name"),
"description": row.get("description"),
"openrouter_model": stored,
"effective_model": effective,
"source": source,
"prompts": [p for p in prompts if p.get("model_role") == key],
}
)
return {
"roles": roles,
"unassigned": [p for p in prompts if not p.get("model_role")],
"platform_model": platform_model,
"env_model": env_model,
}
@router.get("/api/admin/openrouter/roles")
def get_openrouter_roles(session: dict = Depends(_require_superadmin)):
try:
with get_db() as conn:
cur = get_cursor(conn)
return _load_role_overview(cur)
except Exception as exc:
if _missing_table(exc) or "platform_ai_model_roles" in str(exc).lower():
raise HTTPException(
status_code=503,
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
) from exc
raise
@router.put("/api/admin/openrouter/roles/{role_key}")
def put_openrouter_role(
role_key: str,
body: OpenRouterRoleUpdate,
session: dict = Depends(_require_superadmin),
):
key = (role_key or "").strip()
if key not in ROLE_KEYS:
raise HTTPException(status_code=404, detail="Unbekannte Aufgabengruppe.")
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(
"""
UPDATE platform_ai_model_roles
SET openrouter_model = %s, updated_at = NOW(), updated_by_profile_id = %s
WHERE role_key = %s
RETURNING role_key
""",
(model, profile_id, key),
)
updated = cur.fetchone()
if not updated:
raise HTTPException(status_code=404, detail="Aufgabengruppe fehlt.")
return _load_role_overview(cur)
except HTTPException:
raise
except Exception as exc:
if "platform_ai_model_roles" in str(exc).lower() or _missing_table(exc):
raise HTTPException(
status_code=503,
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
) from exc
raise
@router.put("/api/admin/openrouter/prompts/{prompt_id}/role")
def put_openrouter_prompt_role(
prompt_id: int,
body: OpenRouterPromptRoleUpdate,
session: dict = Depends(_require_superadmin),
):
role = str(body.model_role or "").strip() or None
if role and role not in ROLE_KEYS:
raise HTTPException(status_code=400, detail="Unbekannte Aufgabengruppe.")
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
UPDATE ai_prompts
SET model_role = %s, updated_at = NOW()
WHERE id = %s
RETURNING id
""",
(role, prompt_id),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Prompt nicht gefunden.")
return _load_role_overview(cur)
except HTTPException:
raise
except Exception as exc:
if "model_role" in str(exc).lower() or "platform_ai_model_roles" in str(exc).lower():
raise HTTPException(
status_code=503,
detail="Aufgabengruppen fehlen. Migration 098 ausführen.",
) from exc
raise
@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