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) In progress
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) In progress
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
@@ -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
|
||||
|
||||
@@ -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**)
|
||||
|
||||
@@ -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`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+3
-2
@@ -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).
|
||||
|
||||
+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",
|
||||
|
||||
+2
-2
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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([
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/openrouter',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminOpenRouterPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/exercise-enrichment',
|
||||
element: (
|
||||
|
||||
@@ -10075,3 +10075,134 @@ button.combo-coach-cand-link:hover {
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Superadmin: OpenRouter-Modellkatalog */
|
||||
.or-settings {
|
||||
padding: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.or-settings__line {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 8px;
|
||||
align-items: baseline;
|
||||
}
|
||||
.or-settings__line span {
|
||||
min-width: 6.5rem;
|
||||
color: var(--text3);
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-settings__line code,
|
||||
.or-picker__id {
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.or-settings__notice {
|
||||
margin: 8px 0 0;
|
||||
color: var(--accent-dark);
|
||||
}
|
||||
.or-settings__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.or-picker__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.or-picker__count {
|
||||
margin: 0;
|
||||
color: var(--text2);
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-picker__filters {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 10px 12px;
|
||||
}
|
||||
.or-picker__filters .form-row {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.or-picker__note,
|
||||
.or-picker__error,
|
||||
.or-picker__empty {
|
||||
margin: 8px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.or-picker__error {
|
||||
color: var(--danger);
|
||||
}
|
||||
.or-picker__note,
|
||||
.or-picker__empty {
|
||||
color: var(--text2);
|
||||
}
|
||||
.or-picker__clear {
|
||||
margin: 12px 0;
|
||||
}
|
||||
.or-picker__list {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.or-picker__option {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
text-align: left;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--text1);
|
||||
padding: 10px 12px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
}
|
||||
.or-picker__list li:last-child .or-picker__option {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.or-picker__option:hover {
|
||||
background: var(--surface2);
|
||||
}
|
||||
.or-picker__option--selected {
|
||||
background: var(--surface2);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
.or-picker__option:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.or-picker__name {
|
||||
font-weight: 600;
|
||||
}
|
||||
.or-picker__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 12px;
|
||||
color: var(--text3);
|
||||
font-size: 12px;
|
||||
}
|
||||
.or-model-embed {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.or-model-embed summary {
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.or-model-embed .or-picker {
|
||||
margin-top: 12px;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Wand2, Activity, Building2, Shield } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
@@ -16,6 +16,7 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
|
||||
{ to: '/admin/legal-documents', label: 'Rechtstexte', icon: Scale },
|
||||
{ to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles },
|
||||
{ to: '/admin/openrouter', label: 'KI-Modell', icon: Bot },
|
||||
{ to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 },
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
|
||||
function formatContext(value) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n) || n <= 0) return '—'
|
||||
if (n >= 1000) {
|
||||
const k = n / 1000
|
||||
return Number.isInteger(k) ? `${k}k` : `${k.toFixed(1)}k`
|
||||
}
|
||||
return String(n)
|
||||
}
|
||||
|
||||
function tokenUsd(raw) {
|
||||
if (raw == null || raw === '') return null
|
||||
const n = Number(raw)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
function usdPerMillion(raw) {
|
||||
const n = tokenUsd(raw)
|
||||
if (n == null) return null
|
||||
const perM = n * 1_000_000
|
||||
if (perM === 0) return '0'
|
||||
if (perM < 0.01) return perM.toFixed(4)
|
||||
if (perM < 1) return perM.toFixed(3)
|
||||
return perM.toFixed(2)
|
||||
}
|
||||
|
||||
function priceLabel(model) {
|
||||
const prompt = usdPerMillion(model.prompt_usd_per_token)
|
||||
const completion = usdPerMillion(model.completion_usd_per_token)
|
||||
if (prompt == null && completion == null) return 'Preis unbekannt'
|
||||
return `${prompt ?? '—'} / ${completion ?? '—'} USD je 1 Mio. Tokens`
|
||||
}
|
||||
|
||||
function matchesFilters(model, filters) {
|
||||
const query = filters.query.trim().toLowerCase()
|
||||
if (query) {
|
||||
const hay = `${model.name || ''} ${model.id || ''} ${model.description || ''}`.toLowerCase()
|
||||
if (!hay.includes(query)) return false
|
||||
}
|
||||
if (filters.provider && model.provider !== filters.provider) return false
|
||||
const inputs = Array.isArray(model.input_modalities) ? model.input_modalities : []
|
||||
if (filters.modality === 'text' && !(inputs.length === 1 && inputs[0] === 'text')) return false
|
||||
if (filters.modality === 'image' && !inputs.includes('image')) return false
|
||||
if (filters.modality === 'audio' && !inputs.includes('audio')) return false
|
||||
if (filters.contextMin && (Number(model.context_length) || 0) < filters.contextMin) return false
|
||||
if (filters.price === 'free' && !model.is_free) return false
|
||||
if (filters.price === 'paid' && model.is_free) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function compareModels(sort, a, b) {
|
||||
if (sort === 'context') {
|
||||
const diff = (Number(b.context_length) || 0) - (Number(a.context_length) || 0)
|
||||
if (diff) return diff
|
||||
}
|
||||
if (sort === 'price') {
|
||||
const ap = tokenUsd(a.prompt_usd_per_token)
|
||||
const bp = tokenUsd(b.prompt_usd_per_token)
|
||||
const aMissing = ap == null
|
||||
const bMissing = bp == null
|
||||
if (aMissing !== bMissing) return aMissing ? 1 : -1
|
||||
if (!aMissing && ap !== bp) return ap - bp
|
||||
}
|
||||
return String(a.name || a.id).localeCompare(String(b.name || b.id), 'de')
|
||||
}
|
||||
|
||||
/**
|
||||
* Durchsuchbare OpenRouter-Modellliste. value ist die Modell-ID oder leer.
|
||||
*/
|
||||
export default function OpenRouterModelPicker({
|
||||
value,
|
||||
onChange,
|
||||
allowClear = false,
|
||||
clearLabel = 'Plattformstandard verwenden',
|
||||
listMaxHeight = '22rem',
|
||||
}) {
|
||||
const [models, setModels] = useState([])
|
||||
const [meta, setMeta] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [provider, setProvider] = useState('')
|
||||
const [modality, setModality] = useState('')
|
||||
const [contextMin, setContextMin] = useState(0)
|
||||
const [price, setPrice] = useState('')
|
||||
const [sort, setSort] = useState('name')
|
||||
const uid = useId()
|
||||
|
||||
async function load(refresh = false) {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const data = await api.listAdminOpenRouterModels(refresh)
|
||||
setModels(Array.isArray(data?.models) ? data.models : [])
|
||||
setMeta(data)
|
||||
} catch (e) {
|
||||
setError(e.message || 'Modellliste konnte nicht geladen werden.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
api
|
||||
.listAdminOpenRouterModels(false)
|
||||
.then((data) => {
|
||||
if (cancelled) return
|
||||
setModels(Array.isArray(data?.models) ? data.models : [])
|
||||
setMeta(data)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message || 'Modellliste konnte nicht geladen werden.')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const providers = useMemo(() => {
|
||||
const names = new Set(models.map((model) => model.provider).filter(Boolean))
|
||||
return Array.from(names).sort((a, b) => a.localeCompare(b, 'de'))
|
||||
}, [models])
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const filters = { query, provider, modality, contextMin, price }
|
||||
return models
|
||||
.filter((model) => matchesFilters(model, filters))
|
||||
.sort((a, b) => compareModels(sort, a, b))
|
||||
}, [models, query, provider, modality, contextMin, price, sort])
|
||||
|
||||
const selected = models.find((model) => model.id === value) || null
|
||||
const selectedHidden = Boolean(value) && !visible.some((model) => model.id === value)
|
||||
|
||||
return (
|
||||
<div className="or-picker">
|
||||
<div className="or-picker__toolbar">
|
||||
<p className="or-picker__count">
|
||||
{loading
|
||||
? 'Modelle werden geladen …'
|
||||
: `${visible.length} von ${models.length} Modellen`}
|
||||
</p>
|
||||
<button type="button" className="btn btn-secondary" disabled={loading} onClick={() => load(true)}>
|
||||
Liste aktualisieren
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{meta?.stale ? (
|
||||
<p className="or-picker__note">
|
||||
OpenRouter ist gerade nicht erreichbar. Angezeigt wird die zuletzt geladene Liste.
|
||||
</p>
|
||||
) : null}
|
||||
{error ? <p className="or-picker__error">{error}</p> : null}
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-search`}>
|
||||
Suche
|
||||
</label>
|
||||
<input
|
||||
id={`${uid}-search`}
|
||||
className="form-input"
|
||||
type="search"
|
||||
value={query}
|
||||
placeholder="Name oder Modell-ID"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="or-picker__filters">
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-provider`}>
|
||||
Anbieter
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-provider`}
|
||||
className="form-input"
|
||||
value={provider}
|
||||
onChange={(e) => setProvider(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
{providers.map((name) => (
|
||||
<option key={name} value={name}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-modality`}>
|
||||
Eingabe
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-modality`}
|
||||
className="form-input"
|
||||
value={modality}
|
||||
onChange={(e) => setModality(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
<option value="text">Nur Text</option>
|
||||
<option value="image">Mit Bild</option>
|
||||
<option value="audio">Mit Audio</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-context`}>
|
||||
Kontext
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-context`}
|
||||
className="form-input"
|
||||
value={String(contextMin)}
|
||||
onChange={(e) => setContextMin(Number(e.target.value) || 0)}
|
||||
>
|
||||
<option value="0">Alle</option>
|
||||
<option value="32000">mindestens 32k</option>
|
||||
<option value="128000">mindestens 128k</option>
|
||||
<option value="200000">mindestens 200k</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-price`}>
|
||||
Preis
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-price`}
|
||||
className="form-input"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
<option value="free">Kostenlos</option>
|
||||
<option value="paid">Kostenpflichtig</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor={`${uid}-sort`}>
|
||||
Sortierung
|
||||
</label>
|
||||
<select
|
||||
id={`${uid}-sort`}
|
||||
className="form-input"
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value)}
|
||||
>
|
||||
<option value="name">Name</option>
|
||||
<option value="context">Kontext, größter zuerst</option>
|
||||
<option value="price">Eingabepreis, niedrigster zuerst</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{allowClear ? (
|
||||
<div className="or-picker__clear">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${value ? 'btn-secondary' : 'btn-primary'}`}
|
||||
onClick={() => onChange('')}
|
||||
>
|
||||
{clearLabel}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{value && !selected && !loading ? (
|
||||
<p className="or-picker__note">
|
||||
Gespeichert ist <code>{value}</code>. Diese ID steht in der aktuellen OpenRouter-Liste nicht.
|
||||
</p>
|
||||
) : null}
|
||||
{selectedHidden && selected ? (
|
||||
<p className="or-picker__note">
|
||||
Die aktuelle Auswahl <code>{selected.id}</code> passt nicht zu Suche oder Filtern.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ul className="or-picker__list" role="listbox" aria-label="OpenRouter-Modelle" style={{ maxHeight: listMaxHeight }}>
|
||||
{!loading && visible.length === 0 ? (
|
||||
<li className="or-picker__empty">Kein Modell passt zu Suche und Filtern.</li>
|
||||
) : null}
|
||||
{visible.map((model) => {
|
||||
const isSelected = model.id === value
|
||||
return (
|
||||
<li key={model.id}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={`or-picker__option${isSelected ? ' or-picker__option--selected' : ''}`}
|
||||
onClick={() => onChange(model.id)}
|
||||
>
|
||||
<span className="or-picker__name">{model.name}</span>
|
||||
<code className="or-picker__id">{model.id}</code>
|
||||
<span className="or-picker__meta">
|
||||
<span>Kontext {formatContext(model.context_length)}</span>
|
||||
<span>{priceLabel(model)}</span>
|
||||
{model.is_free ? <span>kostenlos</span> : null}
|
||||
{(model.input_modalities || []).length ? (
|
||||
<span>{model.input_modalities.join(', ')}</span>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { Link, Navigate } from 'react-router-dom'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import OpenRouterModelPicker from '../components/OpenRouterModelPicker'
|
||||
|
||||
/**
|
||||
* Pflege von ai_prompts (OpenRouter-Vorlagen) — nur Superadmin.
|
||||
@@ -25,6 +26,7 @@ export default function AdminAiPromptsPage() {
|
||||
const [draftTemplate, setDraftTemplate] = useState('')
|
||||
const [draftOpenrouterModel, setDraftOpenrouterModel] = useState('')
|
||||
const [draftActive, setDraftActive] = useState(true)
|
||||
const [modelListOpen, setModelListOpen] = useState(false)
|
||||
|
||||
const [pvTitle, setPvTitle] = useState('Testübung')
|
||||
const [pvGoal, setPvGoal] = useState('<p>Ziel hier</p>')
|
||||
@@ -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() {
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">OpenRouter-Modell (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="Leer = Server-OPENROUTER_MODEL · z.B. anthropic/claude-3.5-haiku"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={draftOpenrouterModel}
|
||||
onChange={(e) => setDraftOpenrouterModel(e.target.value)}
|
||||
/>
|
||||
<label className="form-label">OpenRouter-Modell für diesen Prompt</label>
|
||||
<p style={{ margin: '0 0 8px', color: 'var(--text2)', fontSize: 13 }}>
|
||||
{draftOpenrouterModel ? (
|
||||
<>
|
||||
Gewählt: <code>{draftOpenrouterModel}</code>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Plattformstandard.{' '}
|
||||
<Link to="/admin/openrouter">KI-Modell festlegen</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="or-model-embed">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setModelListOpen((open) => !open)}
|
||||
>
|
||||
{modelListOpen ? 'Liste schließen' : 'Modell aus der OpenRouter-Liste wählen'}
|
||||
</button>
|
||||
{modelListOpen ? (
|
||||
<OpenRouterModelPicker
|
||||
value={draftOpenrouterModel}
|
||||
onChange={setDraftOpenrouterModel}
|
||||
allowClear
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<input type="checkbox" checked={draftActive} onChange={(e) => setDraftActive(e.target.checked)} />
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { Bot } from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import OpenRouterModelPicker from '../components/OpenRouterModelPicker'
|
||||
|
||||
/**
|
||||
* Plattform-Standardmodell bei OpenRouter — nur Superadmin.
|
||||
*/
|
||||
export default function AdminOpenRouterPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [settings, setSettings] = useState(null)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return undefined
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
api
|
||||
.getAdminOpenRouterSettings()
|
||||
.then((data) => {
|
||||
if (cancelled) return
|
||||
setSettings(data)
|
||||
setDraft(data?.openrouter_model || '')
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message || 'Einstellung konnte nicht geladen werden.')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin])
|
||||
|
||||
async function save(nextModel) {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
try {
|
||||
const data = await api.updateAdminOpenRouterSettings(nextModel)
|
||||
setSettings(data)
|
||||
setDraft(data?.openrouter_model || '')
|
||||
setNotice(nextModel ? 'Standardmodell gespeichert.' : 'Es gilt wieder der Umgebungswert.')
|
||||
} catch (e) {
|
||||
setError(e.message || 'Speichern fehlgeschlagen.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSuperadmin) return <Navigate to="/" replace />
|
||||
|
||||
const stored = settings?.openrouter_model || ''
|
||||
const dirty = draft !== stored
|
||||
const sourceLabel = settings?.source === 'database' ? 'Datenbank' : 'Umgebung'
|
||||
|
||||
return (
|
||||
<div className="admin-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '16px', paddingBottom: 96 }}>
|
||||
<AdminPageNav />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
|
||||
<Bot size={22} aria-hidden />
|
||||
<h1 style={{ margin: 0, fontSize: '1.25rem' }}>KI-Modell</h1>
|
||||
</div>
|
||||
<p style={{ fontSize: 13, color: 'var(--text3)', marginTop: 0, maxWidth: '42rem' }}>
|
||||
Dieses Modell nutzt Shinkan für alle KI-Aufrufe, bei denen am einzelnen Prompt kein eigenes Modell
|
||||
hinterlegt ist. Die Liste kommt live von OpenRouter.
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
<div className="card" style={{ padding: 24, textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="card or-settings">
|
||||
<p className="or-settings__line">
|
||||
<span>Aktiv</span>
|
||||
<code>{settings?.effective_model || '—'}</code>
|
||||
</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Quelle</span>
|
||||
<strong>{sourceLabel}</strong>
|
||||
</p>
|
||||
<p className="or-settings__line">
|
||||
<span>Umgebung</span>
|
||||
<code>{settings?.env_model || '—'}</code>
|
||||
</p>
|
||||
{dirty ? <p className="or-picker__note">Die Auswahl ist noch nicht gespeichert.</p> : null}
|
||||
{notice ? <p className="or-settings__notice">{notice}</p> : null}
|
||||
{error ? <p className="or-picker__error">{error}</p> : null}
|
||||
<div className="or-settings__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={saving || !draft || !dirty}
|
||||
onClick={() => save(draft)}
|
||||
>
|
||||
Als Standard speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={saving || !stored}
|
||||
onClick={() => save('')}
|
||||
>
|
||||
Umgebungswert verwenden
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OpenRouterModelPicker value={draft} onChange={setDraft} listMaxHeight="min(62vh, 640px)" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -674,6 +674,22 @@ export async function getAdminAiPromptPlaceholdersCatalog() {
|
||||
return request('/api/admin/ai-prompts/catalog/placeholders')
|
||||
}
|
||||
|
||||
/** Superadmin: OpenRouter-Standardmodell und live Modellkatalog */
|
||||
export async function getAdminOpenRouterSettings() {
|
||||
return request('/api/admin/openrouter/settings')
|
||||
}
|
||||
|
||||
export async function updateAdminOpenRouterSettings(openrouterModel) {
|
||||
return request('/api/admin/openrouter/settings', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ openrouter_model: openrouterModel || '' }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listAdminOpenRouterModels(refresh = false) {
|
||||
return request(`/api/admin/openrouter/models${refresh ? '?refresh=true' : ''}`)
|
||||
}
|
||||
|
||||
export async function listCatalogPromptSlotTypes() {
|
||||
return request('/api/catalog-prompt-slot-types')
|
||||
}
|
||||
@@ -1160,6 +1176,9 @@ export const api = {
|
||||
previewAdminAiPrompt,
|
||||
resetAdminAiPromptTemplate,
|
||||
getAdminAiPromptPlaceholdersCatalog,
|
||||
getAdminOpenRouterSettings,
|
||||
updateAdminOpenRouterSettings,
|
||||
listAdminOpenRouterModels,
|
||||
listCatalogPromptSlotTypes,
|
||||
getCatalogPromptSlots,
|
||||
updateCatalogPromptSlots,
|
||||
|
||||
Reference in new issue
Block a user