Enhance Exercise Management and AI Integration
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Has been cancelled
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Has been cancelled
- Updated the exercise form to include a tabbed navigation structure, improving user experience with sections for Stammdaten, Anleitung, Einordnung, Varianten, and Medien & Mehr. - Introduced the concept of **Freigabelevel** (visibility level) in the UI, replacing previous terminology for clarity and consistency across components. - Implemented new AI endpoints for exercise suggestions and regeneration, allowing for dynamic content generation without direct database writes. - Removed the legacy `is_primary` flag from exercise skills in the UI, ensuring that intensity levels (`niedrig`, `mittel`, `hoch`) are the primary focus for skill management. - Enhanced the variant management process with improved saving mechanisms and UI updates to reflect changes more intuitively.
This commit is contained in:
1 parent
7245bbb1da
commit
e4451e1362
25 files changed
+1240
-78
No files matched your search
+7
-2
@@ -180,12 +180,17 @@ def init_db():
|
||||
cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'")
|
||||
if cur.fetchone()['count'] == 0:
|
||||
cur.execute("""
|
||||
INSERT INTO ai_prompts (slug, name, description, template, active, sort_order)
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, active, sort_order
|
||||
)
|
||||
VALUES (
|
||||
'pipeline',
|
||||
'Mehrstufige Gesamtanalyse',
|
||||
'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.',
|
||||
'Master-Schalter fuer die gesamte Pipeline. Deaktiviere diese Zeile um die Pipeline zu verstecken.',
|
||||
'PIPELINE_MASTER',
|
||||
'admin',
|
||||
'text',
|
||||
true,
|
||||
-10
|
||||
)
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
KI-Vorschlaege fuer Uebungsformular: Laedt Prompts aus ai_prompts, ruft OpenRouter auf.
|
||||
Keine persistente Aenderung an exercises — nur Response-DTO fuer das Frontend.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from openrouter_chat import OpenRouterError, normalize_openrouter_env, openrouter_chat_completion
|
||||
|
||||
_CANONICAL_SKILL_LEVELS = frozenset({"basis", "grundlagen", "aufbau", "fortgeschritten", "optimierung"})
|
||||
_LEGACY_SKILL_LEVEL_SLUG = {
|
||||
"einsteiger": "basis",
|
||||
"experte": "optimierung",
|
||||
"1": "basis",
|
||||
"2": "grundlagen",
|
||||
"3": "aufbau",
|
||||
"4": "fortgeschritten",
|
||||
"5": "optimierung",
|
||||
}
|
||||
_ALLOWED_SKILL_INTENSITY = frozenset({"niedrig", "mittel", "hoch"})
|
||||
|
||||
|
||||
def _normalize_exercise_skill_level(value) -> Optional[str]:
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip().lower()
|
||||
if not s:
|
||||
return None
|
||||
if s in _CANONICAL_SKILL_LEVELS:
|
||||
return s
|
||||
return _LEGACY_SKILL_LEVEL_SLUG.get(s)
|
||||
|
||||
|
||||
def _normalize_exercise_skill_intensity(value) -> str:
|
||||
if value is None:
|
||||
return "mittel"
|
||||
key = str(value).strip().lower()
|
||||
if key in ("low",):
|
||||
return "niedrig"
|
||||
if key in ("medium",):
|
||||
return "mittel"
|
||||
if key in ("high",):
|
||||
return "hoch"
|
||||
if key in _ALLOWED_SKILL_INTENSITY:
|
||||
return key
|
||||
return "mittel"
|
||||
|
||||
_TAG_RE = re.compile(r"<[^>]+>", re.IGNORECASE)
|
||||
|
||||
_MAX_PLAIN_FIELD = 28_000
|
||||
_MAX_SKILLS_CATALOG_LINES = 240
|
||||
_MAX_SUMMARY_CHARS = 220
|
||||
|
||||
|
||||
def strip_html_to_plain(html: Optional[str], *, max_len: int = _MAX_PLAIN_FIELD) -> str:
|
||||
if not html:
|
||||
return ""
|
||||
t = _TAG_RE.sub(" ", str(html))
|
||||
t = re.sub(r"\s+", " ", t).strip()
|
||||
if len(t) > max_len:
|
||||
t = t[: max_len - 1].rstrip() + "…"
|
||||
return t
|
||||
|
||||
|
||||
def _load_prompt_row(cur, slug: str) -> Optional[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT slug, display_name, template, output_format, active
|
||||
FROM ai_prompts
|
||||
WHERE slug = %s
|
||||
""",
|
||||
(slug,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = dict(row)
|
||||
if not d.get("active", True):
|
||||
return None
|
||||
return d
|
||||
|
||||
|
||||
def _render_template(template: str, ctx: Dict[str, str]) -> str:
|
||||
out = template or ""
|
||||
for key, val in ctx.items():
|
||||
placeholder = "{{" + key + "}}"
|
||||
out = out.replace(placeholder, val if val is not None else "")
|
||||
return out
|
||||
|
||||
|
||||
def _build_skills_catalog_block(cur) -> str:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id, s.name, s.category, s.description, s.karate_relevance, s.relevance_level,
|
||||
sc.name AS subcategory_name
|
||||
FROM skills s
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE (s.status IS NULL OR s.status = 'active')
|
||||
ORDER BY s.importance DESC NULLS LAST, s.name
|
||||
LIMIT %s
|
||||
""",
|
||||
(_MAX_SKILLS_CATALOG_LINES,),
|
||||
)
|
||||
lines: List[str] = []
|
||||
for r in cur.fetchall():
|
||||
rid = int(r["id"])
|
||||
nm = (r.get("name") or "").strip() or f"Skill #{rid}"
|
||||
cat = (r.get("category") or "").strip()
|
||||
sub = (r.get("subcategory_name") or "").strip()
|
||||
dsc = strip_html_to_plain(r.get("description"), max_len=320)
|
||||
kr = strip_html_to_plain(r.get("karate_relevance"), max_len=200)
|
||||
rel = r.get("relevance_level")
|
||||
rel_s = ""
|
||||
if rel is not None:
|
||||
rel_s = str(rel)
|
||||
|
||||
cats = " / ".join(x for x in (cat, sub) if x)
|
||||
|
||||
blob = (
|
||||
f"- id={rid} | name={nm} | kategorie={cats or '-'}"
|
||||
f" | beschreibung={dsc or '-'} | karate_relevanz={kr or '-'}"
|
||||
f" | relevanz_stufe={rel_s or '-'}"
|
||||
)
|
||||
lines.append(blob)
|
||||
return "\n".join(lines) if lines else "(keine aktiven Skills im Katalog)"
|
||||
|
||||
|
||||
def _extract_json_array(text: str) -> Any:
|
||||
s = text.strip()
|
||||
if s.startswith("```"):
|
||||
s = re.sub(r"^```[a-zA-Z0-9]*\s*", "", s)
|
||||
if s.endswith("```"):
|
||||
s = s[:-3].strip()
|
||||
# array whole string
|
||||
if s.startswith("["):
|
||||
end = s.rfind("]")
|
||||
if end > 0:
|
||||
s = s[: end + 1]
|
||||
return json.loads(s)
|
||||
# object wrapping array
|
||||
if s.startswith("{"):
|
||||
obj = json.loads(s)
|
||||
if isinstance(obj, dict):
|
||||
for k in ("skills", "items", "data"):
|
||||
v = obj.get(k)
|
||||
if isinstance(v, list):
|
||||
return v
|
||||
raise ValueError("JSON-Objekt ohne Skills-Liste")
|
||||
return json.loads(s)
|
||||
|
||||
|
||||
def _sanitize_skill_entries(cur, rows: Any) -> List[Dict[str, Any]]:
|
||||
if not isinstance(rows, list):
|
||||
return []
|
||||
out: List[Dict[str, Any]] = []
|
||||
for raw in rows:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
sid = raw.get("skill_id")
|
||||
try:
|
||||
skill_id = int(sid)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id, s.name, s.category,
|
||||
sc.name AS subcategory_name
|
||||
FROM skills s
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE s.id = %s AND (s.status IS NULL OR s.status = 'active')
|
||||
""",
|
||||
(skill_id,),
|
||||
)
|
||||
sk = cur.fetchone()
|
||||
if not sk:
|
||||
continue
|
||||
|
||||
req = _normalize_exercise_skill_level(raw.get("required_level")) or "grundlagen"
|
||||
tgt = _normalize_exercise_skill_level(raw.get("target_level")) or req
|
||||
if req not in _CANONICAL_SKILL_LEVELS:
|
||||
req = _LEGACY_SKILL_LEVEL_SLUG.get(str(raw.get("required_level") or "").strip().lower(), "grundlagen")
|
||||
if req not in _CANONICAL_SKILL_LEVELS:
|
||||
req = "grundlagen"
|
||||
if tgt not in _CANONICAL_SKILL_LEVELS:
|
||||
tgt = _LEGACY_SKILL_LEVEL_SLUG.get(str(raw.get("target_level") or "").strip().lower(), req)
|
||||
if tgt not in _CANONICAL_SKILL_LEVELS:
|
||||
tgt = req
|
||||
|
||||
inten = _normalize_exercise_skill_intensity(raw.get("intensity"))
|
||||
|
||||
is_primary = bool(raw.get("is_primary")) if raw.get("is_primary") is not None else len(out) == 0
|
||||
|
||||
cat = (sk.get("category") or "").strip()
|
||||
sub = (sk.get("subcategory_name") or "").strip()
|
||||
skill_category = " / ".join(x for x in (cat, sub) if x) or (cat or None)
|
||||
|
||||
conf = raw.get("confidence")
|
||||
try:
|
||||
conf_f = float(conf) if conf is not None else None
|
||||
except (TypeError, ValueError):
|
||||
conf_f = None
|
||||
|
||||
item: Dict[str, Any] = {
|
||||
"skill_id": skill_id,
|
||||
"skill_name": (sk.get("name") or "").strip() or f"Skill #{skill_id}",
|
||||
"required_level": req,
|
||||
"target_level": tgt,
|
||||
"intensity": inten,
|
||||
"is_primary": is_primary,
|
||||
}
|
||||
if skill_category:
|
||||
item["skill_category"] = skill_category
|
||||
if conf_f is not None:
|
||||
item["confidence"] = conf_f
|
||||
out.append(item)
|
||||
|
||||
# max 5
|
||||
return out[:5]
|
||||
|
||||
|
||||
def _require_openrouter() -> Tuple[str, str]:
|
||||
key, model = normalize_openrouter_env()
|
||||
if not key:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="KI nicht konfiguriert (OPENROUTER_API_KEY fehlt).",
|
||||
)
|
||||
return key, model
|
||||
|
||||
|
||||
def run_exercise_ai_suggestion(
|
||||
cur,
|
||||
*,
|
||||
title: Optional[str],
|
||||
goal: Optional[str],
|
||||
execution: Optional[str],
|
||||
focus_area_hint: Optional[str],
|
||||
want_summary: bool,
|
||||
want_skills: bool,
|
||||
) -> Dict[str, Any]:
|
||||
key, model = _require_openrouter()
|
||||
|
||||
g_plain = strip_html_to_plain(goal)
|
||||
e_plain = strip_html_to_plain(execution)
|
||||
if not (g_plain.strip() or e_plain.strip()):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Mindestens Ziel oder Durchfuehrung muss Inhalt liefern (nach Entfernen von leerem HTML).",
|
||||
)
|
||||
|
||||
t_title = (title or "").strip()
|
||||
focus = (focus_area_hint or "").strip()
|
||||
|
||||
result: Dict[str, Any] = {"model": model}
|
||||
|
||||
if want_summary:
|
||||
prow = _load_prompt_row(cur, "exercise_summary")
|
||||
if not prow:
|
||||
raise HTTPException(status_code=503, detail="Prompt exercise_summary nicht aktiv oder fehlt in DB.")
|
||||
ctx = {
|
||||
"exercise_title": t_title or "-",
|
||||
"exercise_focus_area": focus or "-",
|
||||
"exercise_goal": g_plain or "-",
|
||||
"exercise_execution": e_plain or "-",
|
||||
}
|
||||
prompt = _render_template(str(prow["template"]), ctx)
|
||||
try:
|
||||
raw = openrouter_chat_completion(api_key=key, model=model, user_content=prompt)
|
||||
except OpenRouterError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
|
||||
text = (raw or "").strip()
|
||||
if len(text) > _MAX_SUMMARY_CHARS:
|
||||
text = text[: _MAX_SUMMARY_CHARS - 1].rstrip() + "…"
|
||||
result["summary"] = {"text": text, "ai_generated": True, "model": model}
|
||||
|
||||
if want_skills:
|
||||
srow = _load_prompt_row(cur, "exercise_skill_suggestions")
|
||||
if not srow:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Prompt exercise_skill_suggestions nicht aktiv oder fehlt in DB.",
|
||||
)
|
||||
catalog = _build_skills_catalog_block(cur)
|
||||
ctx = {
|
||||
"exercise_title": t_title or "-",
|
||||
"exercise_focus_area": focus or "-",
|
||||
"exercise_goal": g_plain or "-",
|
||||
"exercise_execution": e_plain or "-",
|
||||
"skills_catalog": catalog,
|
||||
}
|
||||
prompt = _render_template(str(srow["template"]), ctx)
|
||||
sys_hint = (
|
||||
"Du antwortest nur mit validem JSON (Array). Keine Kommentare, keine Erklaerungen ausserhalb des JSON."
|
||||
)
|
||||
try:
|
||||
raw = openrouter_chat_completion(
|
||||
api_key=key,
|
||||
model=model,
|
||||
user_content=prompt,
|
||||
system_content=sys_hint,
|
||||
temperature=0.15,
|
||||
)
|
||||
except OpenRouterError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
|
||||
try:
|
||||
parsed = _extract_json_array(raw)
|
||||
except (json.JSONDecodeError, ValueError) as e:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="KI lieferte kein verwertbares JSON fuer Skills.",
|
||||
) from e
|
||||
skills = _sanitize_skill_entries(cur, parsed)
|
||||
result["skills"] = skills
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,141 @@
|
||||
-- Migration 067: Konfigurierbare KI-Prompts + Tracking-Feld fuer Uebungs-Zusammenfassung
|
||||
-- Datum: 2026-05-22
|
||||
-- Spec: technical/KI_FEATURES_SPEC.md, AI_PROMPT_SYSTEM_SPEC.md
|
||||
|
||||
-- ============================================================================
|
||||
-- AI PROMPTS
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ai_prompts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slug VARCHAR(100) NOT NULL UNIQUE,
|
||||
display_name VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
template TEXT NOT NULL,
|
||||
|
||||
category VARCHAR(50) DEFAULT 'exercise'
|
||||
CHECK (category IN ('exercise', 'training', 'matrix', 'import', 'admin')),
|
||||
|
||||
output_format VARCHAR(10) DEFAULT 'text'
|
||||
CHECK (output_format IN ('text', 'json')),
|
||||
|
||||
output_schema JSONB,
|
||||
is_system_default BOOLEAN DEFAULT false,
|
||||
default_template TEXT,
|
||||
|
||||
active BOOLEAN DEFAULT true,
|
||||
sort_order INT DEFAULT 0,
|
||||
|
||||
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_slug ON ai_prompts(slug);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_category ON ai_prompts(category);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_active ON ai_prompts(active, sort_order);
|
||||
|
||||
DROP TRIGGER IF EXISTS ai_prompts_update ON ai_prompts;
|
||||
CREATE TRIGGER ai_prompts_update
|
||||
BEFORE UPDATE ON ai_prompts
|
||||
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||
|
||||
-- ============================================================================
|
||||
-- TRACKING SUMMARY (KI)
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE exercises ADD COLUMN IF NOT EXISTS summary_ai_generated BOOLEAN DEFAULT false;
|
||||
|
||||
COMMENT ON COLUMN exercises.summary_ai_generated IS 'TRUE wenn Kurzbeschreibung zuletzt von KI vorgeschlagen und uebernommen (UI setzt bei manueller Aenderung false)';
|
||||
|
||||
-- ============================================================================
|
||||
-- SEED PROMPTS (idempotent)
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'pipeline',
|
||||
'Mehrstufige Gesamtanalyse',
|
||||
'Master-Schalter fuer die Pipeline-Anzeige.',
|
||||
'PIPELINE_MASTER',
|
||||
'admin',
|
||||
'text',
|
||||
false,
|
||||
'PIPELINE_MASTER',
|
||||
true,
|
||||
-10
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'pipeline');
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'exercise_summary',
|
||||
'Uebungs-Zusammenfassung',
|
||||
'Erzeugt eine kurze Kurzbeschreibung fuer Listen/Galerie.',
|
||||
$s$Du bist Assistent fuer Kampfsport-Trainer.
|
||||
Erstelle eine kurze Kurzbeschreibung fuer Listen und Trainingsplaene.
|
||||
|
||||
Anforderungen:
|
||||
- Hochstens etwa 200 Zeichen (bei Bedarf gekuerzt fuer Mobile)
|
||||
- Kern: Welche Trainingsqualitaeten? Wie fuehrt man die Uebung kurz aus?
|
||||
- Sachlich, auf Deutsch
|
||||
|
||||
Uebung: {{exercise_title}}
|
||||
Fokuskontext: {{exercise_focus_area}}
|
||||
Ziel (Fliesstext, kann HTML sein): {{exercise_goal}}
|
||||
Durchfuehrung (Fliesstext, kann HTML sein): {{exercise_execution}}
|
||||
|
||||
Antworte NUR mit der Kurzbeschreibung als einfachen Text (keine Markdown-Codeblocks, keine Anfuehrungszeichen um den ganzen Text).$s$,
|
||||
'exercise',
|
||||
'text',
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
1
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'exercise_summary');
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'exercise_skill_suggestions',
|
||||
'Faehigkeiten-Empfehlungen',
|
||||
'Schlaegt passende Skills mit Stufen/Intensitaet vor (JSON-Ausgabe-Prompt).',
|
||||
$j$Du bist Assistent fuer Kampfsport-Trainer.
|
||||
Ordne diese Uebung dem globalen Skill-Katalog zu.
|
||||
|
||||
Daten zur Uebung:
|
||||
Titel: {{exercise_title}}
|
||||
Fokuskontext (optional): {{exercise_focus_area}}
|
||||
Ziel (gekuerzt_plain): {{exercise_goal}}
|
||||
Durchfuehrung (gekuerzt_plain): {{exercise_execution}}
|
||||
|
||||
Verfuegbare Faehigkeiten (Auswahl NUR ueber diese IDs — keine anderen IDs verwenden):
|
||||
{{skills_catalog}}
|
||||
|
||||
Waehle hoechstens 5 passende Skills. Für jede Faehigkeit:
|
||||
- skill_id: ganze Zahl aus der Liste
|
||||
- required_level: eines von basis, grundlagen, aufbau, fortgeschritten, optimierung
|
||||
- target_level: derselbe Wertvorrat
|
||||
- intensity: eines von niedrig, mittel, hoch
|
||||
- is_primary (optional): true fuer die Hauptfaehigkeit der Uebung, sondern false/weglassen
|
||||
|
||||
Antworte NUR mit einem JSON-Array ohne Erklaertext, keine Markdown-Fences.
|
||||
|
||||
Beispielformat:
|
||||
[{"skill_id": 1, "required_level": "grundlagen", "target_level": "aufbau", "intensity": "hoch", "is_primary": true}]
|
||||
|
||||
Wenn nichts gut passt, antworte mit [].$j$,
|
||||
'exercise',
|
||||
'json',
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
2
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'exercise_skill_suggestions');
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
Minimal OpenRouter REST client (sync). Reads OPENROUTER_API_KEY / OPENROUTER_MODEL / OPENROUTER_BASE_URL from env.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
class OpenRouterError(Exception):
|
||||
"""Upstream or transport failure."""
|
||||
|
||||
|
||||
def openrouter_chat_completion(
|
||||
*,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_content: str,
|
||||
system_content: Optional[str] = None,
|
||||
timeout_sec: float = 120.0,
|
||||
temperature: float = 0.25,
|
||||
site_url: Optional[str] = None,
|
||||
app_title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Returns assistant message content (plain string). Caller validates empty responses.
|
||||
"""
|
||||
base = (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1"
|
||||
url = f"{base}/chat/completions"
|
||||
|
||||
headers: Dict[str, str] = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
referer = (site_url or os.getenv("APP_URL") or "").strip()
|
||||
if referer:
|
||||
headers["HTTP-Referer"] = referer
|
||||
title = (app_title or os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip()
|
||||
if title:
|
||||
headers["X-Title"] = title
|
||||
|
||||
messages: List[Dict[str, str]] = []
|
||||
if system_content and str(system_content).strip():
|
||||
messages.append({"role": "system", "content": str(system_content).strip()})
|
||||
messages.append({"role": "user", "content": user_content})
|
||||
|
||||
payload: Dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
}
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=timeout_sec) as client:
|
||||
resp = client.post(url, headers=headers, json=payload)
|
||||
except httpx.RequestError as e:
|
||||
raise OpenRouterError(str(e)) from e
|
||||
|
||||
if resp.status_code >= 400:
|
||||
detail = ""
|
||||
try:
|
||||
j = resp.json()
|
||||
detail = (
|
||||
str(j.get("error", {}).get("message"))
|
||||
if isinstance(j.get("error"), dict)
|
||||
else str(j.get("message") or j)
|
||||
)
|
||||
except Exception:
|
||||
detail = (resp.text or "")[:600]
|
||||
raise OpenRouterError(f"HTTP {resp.status_code}: {detail}".strip())
|
||||
|
||||
try:
|
||||
data = resp.json()
|
||||
except json.JSONDecodeError as e:
|
||||
raise OpenRouterError("Ungueltige JSON-Antwort von OpenRouter") from e
|
||||
|
||||
choices = data.get("choices") if isinstance(data, dict) else None
|
||||
if not choices or not isinstance(choices, list):
|
||||
raise OpenRouterError("OpenRouter: keine choices in Antwort")
|
||||
|
||||
msg0 = choices[0] if choices else {}
|
||||
inner = msg0.get("message") if isinstance(msg0, dict) else None
|
||||
content = ""
|
||||
if isinstance(inner, dict):
|
||||
content = str(inner.get("content") or "")
|
||||
elif isinstance(inner, str):
|
||||
content = inner
|
||||
elif isinstance(msg0.get("content"), str):
|
||||
content = msg0.get("content") or ""
|
||||
|
||||
return content.strip()
|
||||
|
||||
|
||||
def normalize_openrouter_env() -> tuple[str, str]:
|
||||
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||
model = (os.getenv("OPENROUTER_MODEL") or "anthropic/claude-sonnet-4").strip()
|
||||
return key, model
|
||||
@@ -1,3 +1,4 @@
|
||||
httpx==0.27.2
|
||||
fastapi==0.111.0
|
||||
uvicorn[standard]==0.29.0
|
||||
anthropic==0.26.0
|
||||
|
||||
@@ -35,6 +35,8 @@ from tenant_context import TenantContext, get_tenant_context, get_tenant_context
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
|
||||
from media_rights import assert_rights_for_exercise_link, validate_rights_declaration, write_rights_declaration, update_rights_quick_fields
|
||||
from media_legal_hold import assert_not_under_legal_hold
|
||||
from exercise_ai import run_exercise_ai_suggestion
|
||||
|
||||
from exercise_rich_text import (
|
||||
RICH_HTML_EXERCISE_FIELDS,
|
||||
assert_no_inline_media_references_on_create,
|
||||
@@ -356,6 +358,42 @@ class ExerciseMediaFromAsset(BaseModel):
|
||||
media_type: Optional[str] = None
|
||||
|
||||
|
||||
class ExerciseAiSuggestBody(BaseModel):
|
||||
title: Optional[str] = Field(None, max_length=300)
|
||||
goal: Optional[str] = Field(None, max_length=64000)
|
||||
execution: Optional[str] = Field(None, max_length=128000)
|
||||
focus_area_hint: Optional[str] = Field(None, max_length=1200)
|
||||
include_summary: bool = True
|
||||
include_skills: bool = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_include_any(self):
|
||||
if not self.include_summary and not self.include_skills:
|
||||
raise ValueError("Mindestens include_summary oder include_skills aktivieren.")
|
||||
return self
|
||||
|
||||
|
||||
class ExerciseAiRegenerateBody(BaseModel):
|
||||
"""Welche Artefakte neu angefragt werden sollen."""
|
||||
|
||||
regenerate: list[str] = Field(default_factory=lambda: ["summary", "skills"])
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_regs(self):
|
||||
allowed = {"summary", "skills"}
|
||||
raw = [str(x).strip().lower() for x in (self.regenerate or [])]
|
||||
out = []
|
||||
seen = set()
|
||||
for lx in raw:
|
||||
if lx in allowed and lx not in seen:
|
||||
out.append(lx)
|
||||
seen.add(lx)
|
||||
if not out:
|
||||
out = ["summary", "skills"]
|
||||
self.regenerate = out
|
||||
return self
|
||||
|
||||
|
||||
class ExerciseVariantCreate(BaseModel):
|
||||
variant_name: str = Field(..., min_length=3, max_length=200)
|
||||
description: Optional[str] = None
|
||||
@@ -1244,7 +1282,7 @@ def assign_exercise_relations(
|
||||
(
|
||||
exercise_id,
|
||||
skill["skill_id"],
|
||||
False,
|
||||
bool(skill.get("is_primary")),
|
||||
normalize_exercise_skill_intensity(skill.get("intensity")),
|
||||
normalize_exercise_skill_level(skill.get("required_level")),
|
||||
normalize_exercise_skill_level(skill.get("target_level")),
|
||||
@@ -2216,6 +2254,75 @@ def list_exercises_like_get(
|
||||
)
|
||||
|
||||
|
||||
def _focus_area_hint_from_detail(exercise: Dict[str, Any]) -> str:
|
||||
parts: List[str] = []
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if isinstance(row, dict):
|
||||
nm = (row.get("name") or "").strip()
|
||||
if nm:
|
||||
parts.append(nm)
|
||||
txt = ", ".join(parts).strip()
|
||||
if len(txt) > 900:
|
||||
return txt[:899] + "…"
|
||||
return txt
|
||||
|
||||
|
||||
@router.post("/exercises/ai/suggest")
|
||||
def exercise_ai_suggest_endpoint(
|
||||
body: ExerciseAiSuggestBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
KI-Vorschlaege (Kurzfassung und/oder Skill-Zuordnung) ohne Speichern.
|
||||
OPENROUTER_API_KEY erforderlich.
|
||||
"""
|
||||
_ = tenant.profile_id
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = run_exercise_ai_suggestion(
|
||||
cur,
|
||||
title=(body.title or "").strip(),
|
||||
goal=body.goal,
|
||||
execution=body.execution,
|
||||
focus_area_hint=(body.focus_area_hint or "").strip() or None,
|
||||
want_summary=body.include_summary,
|
||||
want_skills=body.include_skills,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@router.post("/exercises/{exercise_id}/ai/regenerate")
|
||||
def exercise_ai_regenerate_endpoint(
|
||||
exercise_id: int,
|
||||
body: ExerciseAiRegenerateBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Neu-Anfrage KI fuer eine gespeicherte Uebung; schreibendes Ergebnis nur im Frontend (PUT)."""
|
||||
want_summary = "summary" in body.regenerate
|
||||
want_skills = "skills" in body.regenerate
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
if not exercise:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
|
||||
focus = _focus_area_hint_from_detail(exercise)
|
||||
|
||||
payload = run_exercise_ai_suggestion(
|
||||
cur,
|
||||
title=str(exercise.get("title") or "").strip(),
|
||||
goal=exercise.get("goal"),
|
||||
execution=exercise.get("execution"),
|
||||
focus_area_hint=focus or None,
|
||||
want_summary=want_summary,
|
||||
want_skills=want_skills,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/exercises/{exercise_id}")
|
||||
def get_exercise(
|
||||
exercise_id: int,
|
||||
|
||||
+11
-4
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.151"
|
||||
BUILD_DATE = "2026-05-20"
|
||||
DB_SCHEMA_VERSION = "20260520066"
|
||||
APP_VERSION = "0.8.152"
|
||||
BUILD_DATE = "2026-05-22"
|
||||
DB_SCHEMA_VERSION = "20260522067"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -22,7 +22,7 @@ MODULE_VERSIONS = {
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
||||
"exercises": "2.29.0", # POST exercises/ai/suggest + …/ai/regenerate (OpenRouter); exercise_ai; is_primary fuer exercise_skills
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
|
||||
@@ -37,6 +37,13 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.152",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"KI bei Uebungen: Migration 067 ai_prompts + summary_ai_generated; OpenRouter-Hilfsmodul; POST /api/exercises/ai/suggest und POST /api/exercises/{id}/ai/regenerate",
|
||||
"Uebungsformular: Buttons KI Kurzfassung / Fähigkeiten; exercise_skills is_primary wird aus Payload gespeichert",
|
||||
],
|
||||
{
|
||||
"version": "0.8.151",
|
||||
"date": "2026-05-20",
|
||||
|
||||
Reference in new issue
Block a user