diff --git a/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md b/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
index 0198951..29feb92 100644
--- a/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
+++ b/.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md
@@ -8,7 +8,10 @@
**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 Aufgabengruppe (`ai_prompts.model_role`, Migration **098**: `reasoning` Denken, `drafting` Formulieren, `matching` Zuordnen), sonst Datenbank-Standard, sonst Umgebung.
+- Gruppenmodelle: `GET/PUT /api/admin/openrouter/roles` und `PUT /api/admin/openrouter/prompts/{id}/role`.
**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/technical/PROD_DEPLOYMENTS.md b/.claude/docs/technical/PROD_DEPLOYMENTS.md
index f6d78a1..e54b1f3 100644
--- a/.claude/docs/technical/PROD_DEPLOYMENTS.md
+++ b/.claude/docs/technical/PROD_DEPLOYMENTS.md
@@ -2,7 +2,7 @@
Stand: 2026-10-29
-Zwei unabhängige Prod-Deployments laufen parallel. Beide starten bei jedem Push auf `main`, jeweils als eigener Workflow-Lauf auf eigenem Runner. Ein Fehler im einen blockiert das andere nicht.
+**Seit dem Cutover am 2026-10-29 ist llm-node die einzige Prod.** Der Reverse-Proxy für `shinkan.jinkendo.de` zeigt auf llm-node. Nur `deploy-prod-llm-node.yml` startet bei Push auf `main`; `deploy-prod.yml` (Pi) ist nur noch per „Run workflow“ startbar und dient als Rückfallweg (siehe „Rückfall auf den Pi“). Die Tabelle beschreibt beide Seiten.
Backup, Recovery und Erstbefüllung der llm-node-DB: `RECOVERY_CONTRACT.md`.
@@ -18,9 +18,9 @@ Backup, Recovery und Erstbefüllung der llm-node-DB: `RECOVERY_CONTRACT.md`.
| Datenbank | Volume `shinkan_shinkan-db-data` auf dem Pi | Volume `shinkan-prod_shinkan-db-data` auf llm-node |
| Medien (Host) | `SHINKAN_MEDIA_HOST` laut Pi-`.env` | `/srv/shinkan/prod/media` (NFSv4 von `192.168.2.63:/volume1/shinkan-media/prod`) |
| Medien (Container) | `/app/media` | `/app/media` |
-| Medienbereinigung | `retention-cron` läuft immer mit | aus; nur mit `MEDIA_RETENTION: enabled` |
+| Medienbereinigung | `retention-cron` läuft bei jedem Lauf mit; nach Cutover gestoppt | an (`MEDIA_RETENTION: enabled`) |
| Ports | 3003, 127.0.0.1:8003, 127.0.0.1:5434 | 3003, 127.0.0.1:8003, 127.0.0.1:5434 |
-| Manuell auslösen | nur per Push auf `main` | Push auf `main` oder Gitea „Run workflow“ (`workflow_dispatch`) |
+| Auslösen | nur Gitea „Run workflow“ (`workflow_dispatch`) | Push auf `main` oder Gitea „Run workflow“ |
Die Runner-Labels sind am 2026-10-29 aus den `.runner`-Dateien beider Hosts abgelesen worden (act_runner v0.2.11). Jeder Workflow prüft im ersten Schritt Hostname und Architektur und bricht auf einem fremden Runner ab. Wer Labels an einem Runner ändert, muss beide Workflows mitprüfen; `ubuntu-latest` darf nicht auf llm-node, `linux_host` nicht auf dem Pi registriert werden.
@@ -59,28 +59,33 @@ docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.
Bei Fehler: `compose ps` und Backend-Logs, Lauf rot.
-## Medienbereinigung auf llm-node aktivieren
+## Medienbereinigung
-Pi und llm-node nutzen denselben Medienbestand, aber getrennte Datenbanken. Eine Bereinigung auf einer Seite kann Dateien löschen, die die andere Datenbank noch referenziert. Deshalb ist `retention-cron` auf llm-node aus.
+Pi und llm-node nutzen denselben Medienbestand, aber getrennte Datenbanken. Eine Bereinigung auf einer Seite kann Dateien löschen, die die andere Datenbank noch referenziert. Deshalb darf immer nur eine Seite bereinigen.
-Aktivieren erst, wenn nur noch eine Datenbank den Bestand führt (Pi-Bereinigung abgeschaltet bzw. Cutover erfolgt):
+Seit 0.8.247 bereinigt llm-node (`MEDIA_RETENTION: enabled`): Der Lauf baut und startet `retention-cron` mit Profil `media-retention`. Voraussetzung: Der Pi-`retention-cron` ist gestoppt.
-1. In `deploy-prod-llm-node.yml` `MEDIA_RETENTION: disabled` auf `enabled` setzen.
-2. Über `develop` → `main` ausrollen. Der Lauf baut und startet `retention-cron` mit Profil `media-retention`.
+Abschalten: `MEDIA_RETENTION: disabled` setzen und über `develop` → `main` ausrollen; der Lauf entfernt den Container.
-Die Bereinigungslogik selbst (`backend/scripts/media_retention_scheduler.py`, täglich 03:00 Europe/Berlin, kein Löschen beim Start) ist dieselbe wie auf dem Pi.
+Die Bereinigungslogik (`backend/scripts/media_retention_scheduler.py`, täglich 03:00 Europe/Berlin, kein Löschen beim Start) ist auf beiden Seiten dieselbe.
-## Altes Deployment (Pi) abschalten
+## Pi-Deployment (abgeschaltet)
-Nur den Workflow abschalten, nicht den Pi-Runner: der Runner bedient auch `Deploy Development` und `Test Suite`.
+Seit 0.8.247 hat `deploy-prod.yml` nur noch `on: workflow_dispatch`; ein Push oder Merge auf `main` startet es nicht. Der Pi-Runner bleibt aktiv, er bedient `Deploy Development` und `Test Suite`.
-Eine der beiden Varianten:
+Nach dem Cutover auf dem Pi stoppen (manuell, nicht Teil eines Workflows):
-- **Gitea-UI (ohne Commit):** Repository → Actions → `Deploy Production` → „Disable workflow“. Rückgängig über „Enable workflow“.
-- **Im Repo:** `.gitea/workflows/deploy-prod.yml` löschen oder den Trigger auf `on: workflow_dispatch` reduzieren und über `develop` → `main` ausrollen.
+```bash
+cd /home/lars/docker/shinkan && docker compose down
+```
-Folgen:
+Das DB-Volume `shinkan_shinkan-db-data` bleibt dabei erhalten.
-- `deploy-prod-llm-node.yml` ist davon unberührt.
-- `test.yml` startet seine Prod-Prüfungen per `workflow_run` nach `Deploy Production`. Diese Prüfungen laufen gegen das Pi-Verzeichnis und entfallen mit dem Abschalten. Sie sind nicht auf llm-node umgestellt.
-- Die Pi-Container laufen weiter, einschließlich der Pi-Medienbereinigung, bis sie dort mit `docker compose down` gestoppt werden.
+`test.yml` läuft nur für `develop` gegen Dev und hängt an keinem Prod-Workflow. Prod prüfen allein die Healthchecks des Deploy-Workflows. (Bis 0.8.246 startete `test.yml` nach `Deploy Production` per `workflow_run`. Die Weiche über `workflow_run.name` griff in Gitea nicht, und repariert hätten die Integrationstests in die Prod-DB geschrieben.)
+
+### Rückfall auf den Pi
+
+1. In `deploy-prod-llm-node.yml` `MEDIA_RETENTION: disabled` setzen und ausrollen; nie beide Bereinigungen gleichzeitig.
+2. Pi-DB auf den aktuellen Stand bringen: Sie ist seit dem Cutover veraltet.
+3. Gitea → Actions → `Deploy Production` → „Run workflow“ (Branch `main`).
+4. Reverse-Proxy zurück auf den Pi.
diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
index b46e857..d13886e 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`, `GET/PUT /api/admin/openrouter/roles`, `PUT /api/admin/openrouter/prompts/{id}/role` | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Plattform-Standard, Aufgabengruppen 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/.gitea/workflows/deploy-prod-llm-node.yml b/.gitea/workflows/deploy-prod-llm-node.yml
index 50d4dca..429ea1f 100644
--- a/.gitea/workflows/deploy-prod-llm-node.yml
+++ b/.gitea/workflows/deploy-prod-llm-node.yml
@@ -1,8 +1,7 @@
name: Deploy Production llm-node
-# Zweites, unabhängiges Prod-Deployment auf llm-node (192.168.2.144, AMD64).
-# Läuft parallel zu "Deploy Production" (Raspberry Pi). Den Namen nicht auf
-# "Deploy Production" ändern: test.yml hört per workflow_run exakt auf diesen Namen.
+# Prod-Deployment auf llm-node (192.168.2.144, AMD64), seit dem Cutover 2026-10-29 die einzige Prod.
+# "Deploy Production" (Raspberry Pi) ist nur noch manuell startbar.
# Runner: llm-node-runner mit einzigem Label linux_host (Host-Modus).
# Der Pi-Runner (Raspi5-Paperless) hat nur ubuntu-latest und nimmt diesen Job nie an.
# Compose: docker-compose.yml + docker-compose.llm-node.yml, Konfiguration aus ENV_FILE.
@@ -23,9 +22,9 @@ jobs:
REPO_URL: http://192.168.2.144:3000/Lars/shinkan-jinkendo.git
MEDIA_HOST: /srv/shinkan/prod/media
# Medienbereinigung (retention-cron): disabled | enabled.
- # Pi und llm-node teilen den Medienbestand bei getrennten Datenbanken.
- # Nur nach Abschalten der Pi-Bereinigung bzw. dem Cutover auf enabled setzen.
- MEDIA_RETENTION: disabled
+ # Seit dem Cutover führt nur llm-node den Medienbestand. Der Pi-retention-cron muss gestoppt sein:
+ # beide Seiten teilen den Bestand bei getrennten Datenbanken.
+ MEDIA_RETENTION: enabled
steps:
- name: Runner prüfen (nur llm-node)
shell: bash
diff --git a/.gitea/workflows/deploy-prod.yml b/.gitea/workflows/deploy-prod.yml
index ff22f9d..75fa234 100644
--- a/.gitea/workflows/deploy-prod.yml
+++ b/.gitea/workflows/deploy-prod.yml
@@ -1,14 +1,14 @@
name: Deploy Production
-# Prod-Deployment auf dem Raspberry Pi. Parallel dazu: deploy-prod-llm-node.yml.
-# Namen nicht ändern: test.yml hört per workflow_run exakt auf "Deploy Production".
+# ABGESCHALTET seit dem Cutover auf llm-node (2026-10-29): kein Trigger auf main mehr.
+# Prod läuft über deploy-prod-llm-node.yml. Nur noch manuell startbar, als Rückfallweg.
+# Ein manueller Lauf startet auch den Pi-retention-cron auf dem gemeinsamen Medienbestand:
+# vorher MEDIA_RETENTION auf llm-node abschalten. Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
# Runner: Raspi5-Paperless mit einzigem Label ubuntu-latest (Host-Modus); der
# llm-node-Runner trägt dieses Label nicht. Der Guard bricht auf jedem anderen Host ab.
-# Abschalten: .claude/docs/technical/PROD_DEPLOYMENTS.md
on:
- push:
- branches: [main]
+ workflow_dispatch:
jobs:
deploy:
diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml
index aee8c47..556ca8c 100644
--- a/.gitea/workflows/test.yml
+++ b/.gitea/workflows/test.yml
@@ -1,22 +1,18 @@
name: Test Suite
# Eigener Workflow, getrennt von Deploy Development.
-# push/PR auf develop: diese Datei, Ziel ist das Testsystem.
-# workflow_run nur nach Deploy Production. Nicht nach dem Dev-Deploy:
-# der Listener auf main nutzt bei fehlendem Namen sonst das Prod-Verzeichnis.
+# push/PR auf develop: Ziel ist ausschließlich das Testsystem.
+# Kein Lauf gegen Produktion: die Integrationstests schreiben in die Datenbank.
+# Prod prüfen nur die Healthchecks der Deploy-Workflows.
on:
push:
branches: [develop]
pull_request:
branches: [develop]
- workflow_run:
- workflows: ["Deploy Production"]
- types: [completed]
jobs:
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
pytest-backend:
- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Backend pytest im deployten Container
@@ -25,18 +21,8 @@ jobs:
EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}"
- RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
- HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
- if [ "$EVENT_NAME" = "workflow_run" ]; then
- if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
- echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
- echo "Produktion wird nicht angefasst."
- exit 1
- fi
- APP_DIR="/home/lars/docker/shinkan"
- COMPOSE_FILE="docker-compose.yml"
- elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
+ if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev"
COMPOSE_FILE="docker-compose.dev-env.yml"
else
@@ -70,7 +56,6 @@ jobs:
"
lint-backend:
- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Check backend syntax
@@ -78,17 +63,8 @@ jobs:
EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}"
- RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
- HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
- if [ "$EVENT_NAME" = "workflow_run" ]; then
- if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
- echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
- echo "Produktion wird nicht angefasst."
- exit 1
- fi
- APP_DIR="/home/lars/docker/shinkan"
- elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
+ if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev"
else
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
@@ -100,7 +76,6 @@ jobs:
echo "✓ Backend syntax OK"
build-frontend:
- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Build frontend
@@ -108,17 +83,8 @@ jobs:
EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}"
- RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
- HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
- if [ "$EVENT_NAME" = "workflow_run" ]; then
- if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
- echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
- echo "Produktion wird nicht angefasst."
- exit 1
- fi
- APP_DIR="/home/lars/docker/shinkan"
- elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
+ if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev"
else
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
@@ -134,7 +100,6 @@ jobs:
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
k6-health-baseline:
name: k6 /health Baseline
- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
env:
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
@@ -142,29 +107,9 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- - name: E2E-Ziel wählen (Dev über Proxy vs. Production)
- id: e2e
- run: |
- EVENT="${{ github.event_name }}"
- WF_NAME="${{ github.event.workflow_run.name }}"
- DEV_BASE="${{ env.E2E_TARGET_URL }}"
- if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
- echo "mode=prod" >> $GITHUB_OUTPUT
- echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
- echo "→ k6 gegen Prod-Basis."
- elif [ "$EVENT" = "workflow_run" ]; then
- echo "workflow_run ist nicht Deploy Production (name=$WF_NAME). Abbruch."
- exit 1
- else
- echo "mode=dev" >> $GITHUB_OUTPUT
- echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
- echo "→ k6 gegen Dev (${DEV_BASE})."
- fi
-
- name: Dev /health abwarten
- if: ${{ steps.e2e.outputs.mode == 'dev' }}
run: |
- BASE="${{ steps.e2e.outputs.base_url }}"
+ BASE="${{ env.E2E_TARGET_URL }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 90); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
@@ -177,22 +122,6 @@ jobs:
curl -v "$BASE/health" || true
exit 1
- - name: Prod /health abwarten
- if: ${{ steps.e2e.outputs.mode == 'prod' }}
- run: |
- BASE="${{ steps.e2e.outputs.base_url }}"
- echo "Warte auf $BASE/health …"
- for i in $(seq 1 60); do
- if curl -sf "$BASE/health" >/dev/null 2>&1; then
- echo "Health OK (Versuch $i)"
- exit 0
- fi
- sleep 5
- done
- echo "Timeout: Prod /health nicht erreichbar"
- curl -v "$BASE/health" || true
- exit 1
-
- name: Install k6
run: |
set -e
@@ -211,7 +140,7 @@ jobs:
- name: k6 Health-Baseline (parallele /health)
env:
- BASE_URL: ${{ steps.e2e.outputs.base_url }}
+ BASE_URL: ${{ env.E2E_TARGET_URL }}
run: |
set -e
echo "k6 gegen BASE_URL=$BASE_URL"
@@ -219,10 +148,9 @@ jobs:
echo "✓ k6 Health-Baseline passed"
playwright-tests:
- if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
- # Dev: Tests gegen bereits deployte URL (HTTPS, Reverse-Proxy). Prod: gleicher Ablauf.
+ # Tests gegen die bereits deployte Dev-URL (HTTPS, Reverse-Proxy).
env:
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
@@ -235,29 +163,9 @@ jobs:
with:
node-version: '20'
- - name: E2E-Ziel wählen (Dev über Proxy vs. Production)
- id: e2e
- run: |
- EVENT="${{ github.event_name }}"
- WF_NAME="${{ github.event.workflow_run.name }}"
- DEV_BASE="${{ env.E2E_TARGET_URL }}"
- if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
- echo "mode=prod" >> $GITHUB_OUTPUT
- echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
- echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
- elif [ "$EVENT" = "workflow_run" ]; then
- echo "workflow_run ist nicht Deploy Production (name=$WF_NAME). Abbruch."
- exit 1
- else
- echo "mode=dev" >> $GITHUB_OUTPUT
- echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
- echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
- fi
-
- name: Dev /health abwarten
- if: ${{ steps.e2e.outputs.mode == 'dev' }}
run: |
- BASE="${{ steps.e2e.outputs.base_url }}"
+ BASE="${{ env.E2E_TARGET_URL }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 90); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
@@ -270,29 +178,12 @@ jobs:
curl -v "$BASE/health" || true
exit 1
- - name: Prod /health abwarten
- if: ${{ steps.e2e.outputs.mode == 'prod' }}
- run: |
- BASE="${{ steps.e2e.outputs.base_url }}"
- echo "Warte auf $BASE/health …"
- for i in $(seq 1 60); do
- if curl -sf "$BASE/health" >/dev/null 2>&1; then
- echo "Health OK (Versuch $i)"
- exit 0
- fi
- sleep 5
- done
- echo "Timeout: Prod /health nicht erreichbar"
- curl -v "$BASE/health" || true
- exit 1
-
- name: Testnutzer registrieren (Dev, nur wenn möglich)
- if: ${{ steps.e2e.outputs.mode == 'dev' }}
env:
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
run: |
- BASE="${{ steps.e2e.outputs.base_url }}"
+ BASE="${{ env.E2E_TARGET_URL }}"
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
exit 0
@@ -313,24 +204,12 @@ jobs:
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
run: |
set -e
- MODE="${{ steps.e2e.outputs.mode }}"
- BASE_URL="${{ steps.e2e.outputs.base_url }}"
- export PLAYWRIGHT_BASE_URL="$BASE_URL"
-
- if [ "$MODE" = "prod" ]; then
- export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
- export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
- if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
- echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
- exit 1
- fi
- else
- export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
- export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
- if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
- echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
- exit 1
- fi
+ export PLAYWRIGHT_BASE_URL="${{ env.E2E_TARGET_URL }}"
+ export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
+ export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
+ if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
+ echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
+ exit 1
fi
mkdir -p screenshots
diff --git a/CLAUDE.md b/CLAUDE.md
index 5942ed8..f96ea4c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -137,12 +137,11 @@ Internet → Fritz!Box (privat.stommer.com) → Synology NAS → Raspberry Pi 5
Git Workflow:
develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098)
- main → Auto-Deploy → shinkan.jinkendo.de (shinkan/, Port 3003/8003)
-
- main → Auto-Deploy → llm-node (192.168.2.144, /home/llmadmin/docker/shinkan-prod)
- parallel, eigener Workflow deploy-prod-llm-node.yml
+ main → Auto-Deploy → shinkan.jinkendo.de auf llm-node (192.168.2.144, /home/llmadmin/docker/shinkan-prod)
+ Workflow deploy-prod-llm-node.yml, Port 3003/8003
Compose-Override docker-compose.llm-node.yml, Config /etc/shinkan/prod.env
- Details + Abschalten des Pi-Prod: .claude/docs/technical/PROD_DEPLOYMENTS.md
+ Pi-Prod (shinkan/, deploy-prod.yml) seit Cutover 2026-10-29 nur noch manuell
+ Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo
Runner: Raspberry Pi (/home/lars/gitea-runner/, Label ubuntu-latest)
diff --git a/backend/ai_model_roles.py b/backend/ai_model_roles.py
new file mode 100644
index 0000000..55e241d
--- /dev/null
+++ b/backend/ai_model_roles.py
@@ -0,0 +1,38 @@
+"""Aufgabengruppen für OpenRouter-Modelle. Die Zuordnung der Prompts lebt in ai_prompts.model_role."""
+from __future__ import annotations
+
+from typing import Optional, Tuple
+
+ROLE_KEYS = frozenset({"reasoning", "drafting", "matching"})
+
+_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
+
+
+def resolve_prompt_openrouter_model(
+ *,
+ prompt_model: Optional[str],
+ role_model: Optional[str],
+ platform_model: Optional[str],
+ env_model: Optional[str],
+) -> Tuple[str, str]:
+ """
+ Auflösung und Quelle.
+
+ Quelle ist `prompt`, `role`, `database` oder `environment`.
+ Ungültige IDs werden übersprungen.
+ """
+ from openrouter_chat import normalize_openrouter_model_id
+
+ for raw, source in (
+ (prompt_model, "prompt"),
+ (role_model, "role"),
+ (platform_model, "database"),
+ ):
+ try:
+ model = normalize_openrouter_model_id(raw)
+ except ValueError:
+ model = None
+ if model:
+ return model, source
+ env = (str(env_model or "").strip() or _FALLBACK_MODEL)
+ return env, "environment"
diff --git a/backend/ai_prompt_runtime.py b/backend/ai_prompt_runtime.py
index 5944f36..50b1def 100644
--- a/backend/ai_prompt_runtime.py
+++ b/backend/ai_prompt_runtime.py
@@ -57,7 +57,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
if active_only:
cur.execute(
"""
- SELECT slug, display_name, template, output_format, active, openrouter_model
+ SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
FROM ai_prompts
WHERE slug = %s AND active = true
""",
@@ -66,7 +66,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
else:
cur.execute(
"""
- SELECT slug, display_name, template, output_format, active, openrouter_model
+ SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
FROM ai_prompts
WHERE slug = %s
""",
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/migrations/098_ai_model_roles.sql b/backend/migrations/098_ai_model_roles.sql
new file mode 100644
index 0000000..c247d4e
--- /dev/null
+++ b/backend/migrations/098_ai_model_roles.sql
@@ -0,0 +1,86 @@
+-- Migration 098: Aufgabengruppen für OpenRouter-Modelle.
+-- Ein Prompt nutzt: eigenes openrouter_model, sonst das Modell seiner Gruppe,
+-- sonst platform_ai_settings.openrouter_model, sonst OPENROUTER_MODEL.
+-- model_role IS NULL wird nur beim ersten Setzen gefüllt, damit spätere
+-- Umgruppierungen im Admin bei einem erneuten Lauf erhalten bleiben.
+
+CREATE TABLE IF NOT EXISTS platform_ai_model_roles (
+ role_key VARCHAR(40) PRIMARY KEY,
+ display_name VARCHAR(120) NOT NULL,
+ description TEXT NOT NULL,
+ openrouter_model VARCHAR(200),
+ sort_order INT NOT NULL DEFAULT 0,
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
+);
+
+INSERT INTO platform_ai_model_roles (role_key, display_name, description, sort_order)
+VALUES
+ (
+ 'reasoning',
+ 'Denken',
+ 'Didaktische Entwürfe und Qualitätsurteile: Start und Ziel, Zielanalyse, Roadmap, Stufen und die Prüfung eines Übungspfads.',
+ 10
+ ),
+ (
+ 'drafting',
+ 'Formulieren',
+ 'Texte und eng gefasste Profile: Zusammenfassung, Anleitung, Suchabsicht, Semantik und Erwartungsprofil.',
+ 20
+ ),
+ (
+ 'matching',
+ 'Zuordnen',
+ 'Auswahl aus einer vorgegebenen Menge: Fähigkeiten vorschlagen und Suchtreffer neu ordnen.',
+ 30
+ )
+ON CONFLICT (role_key) DO UPDATE
+SET display_name = EXCLUDED.display_name,
+ description = EXCLUDED.description,
+ sort_order = EXCLUDED.sort_order;
+
+ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS model_role VARCHAR(40);
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint WHERE conname = 'ai_prompts_model_role_fkey'
+ ) THEN
+ ALTER TABLE ai_prompts
+ ADD CONSTRAINT ai_prompts_model_role_fkey
+ FOREIGN KEY (model_role) REFERENCES platform_ai_model_roles(role_key);
+ END IF;
+END $$;
+
+COMMENT ON COLUMN ai_prompts.model_role IS
+ 'Aufgabengruppe für das Standardmodell; NULL = Plattformstandard. openrouter_model am Prompt hat Vorrang.';
+
+UPDATE ai_prompts
+SET model_role = 'reasoning'
+WHERE model_role IS NULL
+ AND slug IN (
+ 'planning_progression_start_target',
+ 'planning_progression_goal_analysis',
+ 'planning_progression_roadmap',
+ 'planning_progression_stage_spec',
+ 'planning_exercise_path_qa'
+ );
+
+UPDATE ai_prompts
+SET model_role = 'drafting'
+WHERE model_role IS NULL
+ AND slug IN (
+ 'exercise_summary',
+ 'exercise_instruction_rewrite',
+ 'planning_exercise_search_intent',
+ 'planning_exercise_query_semantics',
+ 'planning_exercise_expectation_profile'
+ );
+
+UPDATE ai_prompts
+SET model_role = 'matching'
+WHERE model_role IS NULL
+ AND slug IN (
+ 'exercise_skill_suggestions',
+ 'planning_exercise_search_rank'
+ );
diff --git a/backend/openrouter_chat.py b/backend/openrouter_chat.py
index 516b2dc..622efac 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,26 +213,305 @@ 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 read_platform_role_models() -> Dict[str, str]:
+ """Gespeicherte Gruppenmodelle. Fehlende Tabelle oder DB-Fehler: leeres Dict."""
+ try:
+ from db import get_cursor, get_db
+
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ "SELECT role_key, openrouter_model FROM platform_ai_model_roles"
+ )
+ rows = cur.fetchall()
+ except Exception as exc:
+ _logger.warning("Aufgabengruppen-Modelle nicht lesbar: %s", exc)
+ return {}
+ out: Dict[str, str] = {}
+ for row in rows or []:
+ key = str((row.get("role_key") if isinstance(row, dict) else row[0]) or "").strip()
+ raw = row.get("openrouter_model") if isinstance(row, dict) else row[1]
+ text = str(raw or "").strip()
+ if key and text:
+ out[key] = text
+ return out
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
"""
- Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Env-Default.
+ Prompt-Ausnahme, sonst Aufgabengruppe, sonst Plattform-Standard, sonst Umgebung.
- `row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …).
+ `row` kann eine partial Row aus load_ai_prompt_row sein
+ (Felder slug, openrouter_model, model_role, …).
"""
+ from ai_model_roles import resolve_prompt_openrouter_model
+
+ prompt_model = None
+ role_key = ""
if row:
- custom = str(row.get("openrouter_model") or "").strip()
- if custom:
- return custom
- return default_openrouter_model_id()
+ prompt_model = row.get("openrouter_model")
+ role_key = str(row.get("model_role") or "").strip()
+ role_model = read_platform_role_models().get(role_key) if role_key else None
+ effective, _source = resolve_prompt_openrouter_model(
+ prompt_model=None if prompt_model is None else str(prompt_model),
+ role_model=role_model,
+ platform_model=read_stored_platform_openrouter_model(),
+ env_model=env_openrouter_model_id(),
+ )
+ return effective
+
+
+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..9e8cade 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
@@ -47,7 +48,7 @@ def _fetch_prompt_any(cur, prompt_id: int) -> Dict[str, Any]:
cur.execute(
"""
SELECT id, slug, display_name, description, template, category, output_format,
- output_schema, is_system_default, default_template, openrouter_model,
+ output_schema, is_system_default, default_template, openrouter_model, model_role,
active, sort_order, created_at, updated_at
FROM ai_prompts WHERE id = %s
""",
@@ -95,7 +96,7 @@ def list_ai_prompts(session: dict = Depends(_require_superadmin)):
cur.execute(
"""
SELECT id, slug, display_name, description, category, output_format, active,
- sort_order, is_system_default, default_template, openrouter_model
+ sort_order, is_system_default, default_template, openrouter_model, model_role
FROM ai_prompts
ORDER BY sort_order ASC NULLS LAST, id ASC
"""
@@ -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(
"""
@@ -173,7 +174,7 @@ def update_ai_prompt(
openrouter_model = %s, updated_at = NOW()
WHERE id = %s
RETURNING id, slug, display_name, description, template, category, output_format,
- output_schema, is_system_default, default_template, openrouter_model,
+ output_schema, is_system_default, default_template, openrouter_model, model_role,
active, sort_order,
created_at, updated_at
""",
@@ -206,7 +207,7 @@ def reset_ai_prompt_template(prompt_id: int, session: dict = Depends(_require_su
SET template = default_template, updated_at = NOW()
WHERE id = %s AND default_template IS NOT NULL
RETURNING id, slug, display_name, description, template, category, output_format,
- output_schema, is_system_default, default_template, openrouter_model,
+ output_schema, is_system_default, default_template, openrouter_model, model_role,
active, sort_order,
created_at, updated_at
""",
diff --git a/backend/routers/openrouter_admin.py b/backend/routers/openrouter_admin.py
new file mode 100644
index 0000000..86150cf
--- /dev/null
+++ b/backend/routers/openrouter_admin.py
@@ -0,0 +1,312 @@
+"""
+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
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..d2f4853
--- /dev/null
+++ b/backend/tests/test_openrouter_admin.py
@@ -0,0 +1,221 @@
+"""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 ai_model_roles import resolve_prompt_openrouter_model
+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_prompt_model_resolution_prefers_exception_then_role():
+ model, source = resolve_prompt_openrouter_model(
+ prompt_model="openai/gpt-4o-mini",
+ role_model="anthropic/claude-sonnet-4",
+ platform_model="google/gemini-2.5-pro",
+ env_model="anthropic/claude-3.5-haiku",
+ )
+ assert model == "openai/gpt-4o-mini"
+ assert source == "prompt"
+ model, source = resolve_prompt_openrouter_model(
+ prompt_model="",
+ role_model="anthropic/claude-sonnet-4",
+ platform_model="google/gemini-2.5-pro",
+ env_model="anthropic/claude-3.5-haiku",
+ )
+ assert model == "anthropic/claude-sonnet-4"
+ assert source == "role"
+ model, source = resolve_prompt_openrouter_model(
+ prompt_model=None,
+ role_model=None,
+ platform_model="google/gemini-2.5-pro",
+ env_model="anthropic/claude-3.5-haiku",
+ )
+ assert source == "database"
+ model, source = resolve_prompt_openrouter_model(
+ prompt_model="kein-slash",
+ role_model="",
+ platform_model="",
+ env_model="anthropic/claude-3.5-haiku",
+ )
+ assert model == "anthropic/claude-3.5-haiku"
+ assert source == "environment"
+
+
+def test_role_update_rejects_unknown_role_and_invalid_model(client: TestClient):
+ app.dependency_overrides[require_auth] = _superadmin
+ missing = client.put(
+ "/api/admin/openrouter/roles/unbekannt",
+ headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
+ json={"openrouter_model": "openai/gpt-4o-mini"},
+ )
+ assert missing.status_code == 404
+ invalid = client.put(
+ "/api/admin/openrouter/roles/matching",
+ headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
+ json={"openrouter_model": "nur-text"},
+ )
+ assert invalid.status_code == 400
+ app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
+ forbidden = client.get("/api/admin/openrouter/roles", headers={"X-Auth-Token": "t"})
+ assert forbidden.status_code == 403
+
+
+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 97f9f6d..bb8e470 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information
-APP_VERSION = "0.8.246"
-BUILD_DATE = "2026-10-29"
-DB_SCHEMA_VERSION = "20261012096"
+APP_VERSION = "0.8.250"
+BUILD_DATE = "2026-11-23"
+DB_SCHEMA_VERSION = "20261123098"
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.1.0", # Aufgabengruppen Denken, Formulieren, Zuordnen
"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,35 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
+ {
+ "version": "0.8.250",
+ "date": "2026-11-23",
+ "changes": [
+ "OpenRouter-Modelle lassen sich für die Aufgabengruppen Denken, Formulieren und Zuordnen hinterlegen. Die Zuordnung folgt den bestehenden KI-Aufrufen; eine Ausnahme am einzelnen Prompt bleibt möglich.",
+ ],
+ },
+ {
+ "version": "0.8.249",
+ "date": "2026-11-23",
+ "changes": [
+ "Nach einem Deploy lädt ein fehlendes Frontend-Chunk die Seite einmal neu, statt die Fehlermaske zu zeigen. index.html wird nicht mehr lange gecacht.",
+ ],
+ },
+ {
+ "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",
+ "changes": [
+ "Test Suite läuft nur noch für develop gegen Dev. Der Lauf nach Deploy Production entfällt: er brach in Gitea in jedem Job ab und hätte repariert Integrationstests gegen die Prod-Datenbank ausgeführt.",
+ "Cutover auf llm-node: Deploy Production (Pi) startet nicht mehr bei Push auf main, nur noch manuell. Medienbereinigung (retention-cron) auf llm-node eingeschaltet.",
+ ],
+ },
{
"version": "0.8.246",
"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/nginx.conf b/frontend/nginx.conf
index efe13dc..2d75c27 100644
--- a/frontend/nginx.conf
+++ b/frontend/nginx.conf
@@ -21,10 +21,12 @@ server {
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
location = /media {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
+ add_header Cache-Control "no-cache" always;
try_files /index.html =404;
}
location = /media/ {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
+ add_header Cache-Control "no-cache" always;
try_files /index.html =404;
}
@@ -64,6 +66,7 @@ server {
# Document-CSP für SPA/PWA — React nutzt häufig inline-styles; Mediendateien & API sind same-origin (Proxy).
# Bei separater API-Origin: connect-src hier erweitern oder nginx-Envsubst nutzen.
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
+ add_header Cache-Control "no-cache" always;
try_files $uri $uri/ /index.html;
}
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index a23455d..715cfe9 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -1,4 +1,4 @@
-import React, { Suspense, lazy } from 'react'
+import React, { Suspense } from 'react'
import LoginPage from './pages/LoginPage'
import { lazyWithRetry } from './utils/lazyWithRetry'
import {
@@ -25,48 +25,49 @@ import TotpSetupCard from './components/TotpSetupCard'
import './app.css'
const OnboardingPage = lazyWithRetry(() => import('./pages/OnboardingPage'))
-const VerifyPage = lazy(() => import('./pages/VerifyPage'))
-const Dashboard = lazy(() => import('./pages/Dashboard'))
-const AccountSettingsPage = lazy(() => import('./pages/AccountSettingsPage'))
-const SettingsSystemInfoPage = lazy(() => import('./pages/SettingsSystemInfoPage'))
-const ExercisesListPage = lazy(() => import('./pages/ExercisesListPage'))
-const ExerciseDetailPage = lazy(() => import('./pages/ExerciseDetailPage'))
-const ExerciseFormPage = lazy(() => import('./pages/ExerciseFormPage'))
-const ProgressionGraphEditPage = lazy(() => import('./pages/ProgressionGraphEditPage'))
-const ClubsPage = lazy(() => import('./pages/ClubsPage'))
-const InboxPage = lazy(() => import('./pages/InboxPage'))
-const SkillsPage = lazy(() => import('./pages/SkillsPage'))
-const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
-const TrainingPlanTemplatesListPage = lazy(() => import('./pages/TrainingPlanTemplatesListPage'))
-const TrainingPlanTemplateEditPage = lazy(() => import('./pages/TrainingPlanTemplateEditPage'))
-const PlanningLayout = lazy(() => import('./layouts/PlanningLayout'))
-const TrainingFrameworkProgramsListPage = lazy(() =>
+const VerifyPage = lazyWithRetry(() => import('./pages/VerifyPage'))
+const Dashboard = lazyWithRetry(() => import('./pages/Dashboard'))
+const AccountSettingsPage = lazyWithRetry(() => import('./pages/AccountSettingsPage'))
+const SettingsSystemInfoPage = lazyWithRetry(() => import('./pages/SettingsSystemInfoPage'))
+const ExercisesListPage = lazyWithRetry(() => import('./pages/ExercisesListPage'))
+const ExerciseDetailPage = lazyWithRetry(() => import('./pages/ExerciseDetailPage'))
+const ExerciseFormPage = lazyWithRetry(() => import('./pages/ExerciseFormPage'))
+const ProgressionGraphEditPage = lazyWithRetry(() => import('./pages/ProgressionGraphEditPage'))
+const ClubsPage = lazyWithRetry(() => import('./pages/ClubsPage'))
+const InboxPage = lazyWithRetry(() => import('./pages/InboxPage'))
+const SkillsPage = lazyWithRetry(() => import('./pages/SkillsPage'))
+const TrainingPlanningPage = lazyWithRetry(() => import('./pages/TrainingPlanningPage'))
+const TrainingPlanTemplatesListPage = lazyWithRetry(() => import('./pages/TrainingPlanTemplatesListPage'))
+const TrainingPlanTemplateEditPage = lazyWithRetry(() => import('./pages/TrainingPlanTemplateEditPage'))
+const PlanningLayout = lazyWithRetry(() => import('./layouts/PlanningLayout'))
+const TrainingFrameworkProgramsListPage = lazyWithRetry(() =>
import('./pages/TrainingFrameworkProgramsListPage'),
)
-const TrainingFrameworkProgramEditPage = lazy(() =>
+const TrainingFrameworkProgramEditPage = lazyWithRetry(() =>
import('./pages/TrainingFrameworkProgramEditPage'),
)
-const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
-const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
-const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
-const TrainingUnitEditPage = lazy(() => import('./pages/TrainingUnitEditPage'))
-const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
-const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
-const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
-const AdminMaturityModelsPage = lazy(() => import('./pages/AdminMaturityModelsPage'))
-const TrainerContextsPage = lazy(() => import('./pages/TrainerContextsPage'))
-const MediaWikiImportPage = lazy(() => import('./pages/MediaWikiImportPage'))
-const AdminUsersPage = lazy(() => import('./pages/AdminUsersPage'))
-const AdminClubCreationRequestsPage = lazy(() => import('./pages/AdminClubCreationRequestsPage'))
-const AdminRightsPage = lazy(() => import('./pages/AdminRightsPage'))
-const MediaLibraryPage = lazy(() => import('./pages/MediaLibraryPage'))
-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 AdminExerciseEnrichmentPage = lazy(() => import('./pages/AdminExerciseEnrichmentPage'))
-const AdminUserContentPage = lazy(() => import('./pages/AdminUserContentPage'))
-const SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
+const TrainingModulesListPage = lazyWithRetry(() => import('./pages/TrainingModulesListPage'))
+const TrainingModuleEditPage = lazyWithRetry(() => import('./pages/TrainingModuleEditPage'))
+const TrainingUnitRunPage = lazyWithRetry(() => import('./pages/TrainingUnitRunPage'))
+const TrainingUnitEditPage = lazyWithRetry(() => import('./pages/TrainingUnitEditPage'))
+const TrainingCoachPage = lazyWithRetry(() => import('./pages/TrainingCoachPage'))
+const AdminCatalogsPage = lazyWithRetry(() => import('./pages/AdminCatalogsPage'))
+const AdminHierarchyPage = lazyWithRetry(() => import('./pages/AdminHierarchyPage'))
+const AdminMaturityModelsPage = lazyWithRetry(() => import('./pages/AdminMaturityModelsPage'))
+const TrainerContextsPage = lazyWithRetry(() => import('./pages/TrainerContextsPage'))
+const MediaWikiImportPage = lazyWithRetry(() => import('./pages/MediaWikiImportPage'))
+const AdminUsersPage = lazyWithRetry(() => import('./pages/AdminUsersPage'))
+const AdminClubCreationRequestsPage = lazyWithRetry(() => import('./pages/AdminClubCreationRequestsPage'))
+const AdminRightsPage = lazyWithRetry(() => import('./pages/AdminRightsPage'))
+const MediaLibraryPage = lazyWithRetry(() => import('./pages/MediaLibraryPage'))
+const LegalPage = lazyWithRetry(() => import('./pages/LegalPage'))
+const AdminLegalDocumentsPage = lazyWithRetry(() => import('./pages/AdminLegalDocumentsPage'))
+const AdminAiSkillRetrievalPage = lazyWithRetry(() => import('./pages/AdminAiSkillRetrievalPage'))
+const AdminAiPromptsPage = lazyWithRetry(() => import('./pages/AdminAiPromptsPage'))
+const AdminOpenRouterPage = lazyWithRetry(() => import('./pages/AdminOpenRouterPage'))
+const AdminExerciseEnrichmentPage = lazyWithRetry(() => import('./pages/AdminExerciseEnrichmentPage'))
+const AdminUserContentPage = lazyWithRetry(() => import('./pages/AdminUserContentPage'))
+const SettingsLegalPage = lazyWithRetry(() => import('./pages/SettingsLegalPage'))
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
function computeShowAdminNav(currentUser) {
@@ -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 +88,7 @@ export default function AdminAiPromptsPage() { setDetail(null) return } + setModelListOpen(false) let cancelled = false ;(async () => { try { @@ -264,15 +273,37 @@ export default function AdminAiPromptsPage() { />
+ {draftOpenrouterModel ? (
+ <>
+ Ausnahme: {draftOpenrouterModel}
+ >
+ ) : (
+ <>
+ {detail?.model_role
+ ? `Es gilt die Aufgabengruppe ${MODEL_ROLE_LABEL[detail.model_role] || detail.model_role}. `
+ : 'Es gilt der Plattformstandard. '}
+ Gruppen unter KI-Modell festlegen
+ >
+ )}
+