Implement exercise_instruction_rewrite for AI Prompt System
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m16s

- Added `exercise_instruction_rewrite` functionality to enhance AI-generated instructions, incorporating fields for goal, execution, preparation, and trainer notes.
- Updated `ExerciseFormAiPromptContext` to include new fields and methods for instruction handling.
- Enhanced the `run_exercise_form_ai_suggestion` function to support instruction rewriting and validation.
- Modified API endpoints and frontend components to integrate instruction features, including a new button for AI instruction revision.
- Incremented application version to 0.8.163 and updated changelog to reflect these changes, including migration details and new functionality.
This commit is contained in:
Lars committed 2026-05-22 18:53:36 +02:00
1 parent 5331eab39c
commit 9f4678f418
12 files changed
+623 -36

No files matched your search

+248 -5
View File
@@ -7,6 +7,7 @@ Skill-Katalog fuer Prompts: priorisierte Auswahl (ai_skill_retrieval_profiles, F
from __future__ import annotations
import copy
import html
import json
import logging
import math
@@ -26,6 +27,7 @@ from openrouter_chat import (
from ai_prompt_context import ExerciseFormAiPromptContext
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
from exercise_rich_text import collect_inline_exercise_media_ids, normalize_inline_exercise_media_markup
_LOGGER = logging.getLogger("shinkan.exercise_ai")
@@ -497,6 +499,146 @@ def build_contextual_skills_catalog_block(
return "\n".join(lines) if lines else "(keine aktiven Skills im Katalog)"
_MAX_INSTRUCTION_GOAL_PLAIN = 4_000
_MAX_INSTRUCTION_EXECUTION_PLAIN = 12_000
_MAX_INSTRUCTION_PREP_PLAIN = 2_500
_MAX_INSTRUCTION_TRAINER_PLAIN = 2_500
_INSTRUCTION_JSON_KEYS = ("goal", "execution", "preparation", "trainer_notes")
_INSTRUCTION_FIELD_MAX_PLAIN = {
"goal": _MAX_INSTRUCTION_GOAL_PLAIN,
"execution": _MAX_INSTRUCTION_EXECUTION_PLAIN,
"preparation": _MAX_INSTRUCTION_PREP_PLAIN,
"trainer_notes": _MAX_INSTRUCTION_TRAINER_PLAIN,
}
_DISALLOWED_HTML_TAG_RE = re.compile(
r"</?\s*(?!p\b|ul\b|ol\b|li\b|strong\b|b\b|em\b|i\b|br\b|span\b)[a-zA-Z][^>]*>",
re.IGNORECASE,
)
_SCRIPT_STYLE_RE = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
def _plain_to_minimal_instruction_html(text: str) -> str:
raw = (text or "").strip()
if not raw:
return ""
parts = [p.strip() for p in re.split(r"\n+", raw) if p.strip()]
if not parts:
return ""
return "".join(f"<p>{html.escape(p)}</p>" for p in parts)
def _truncate_plain(text: str, max_len: int) -> str:
t = (text or "").strip()
if len(t) <= max_len:
return t
return t[: max_len - 1].rstrip() + "…"
def _sanitize_instruction_field_html(raw: Any, *, max_plain: int) -> str:
if raw is None:
return ""
s = str(raw).strip()
if not s:
return ""
if s.startswith("```"):
s = re.sub(r"^```[a-zA-Z0-9]*\s*", "", s)
if s.endswith("```"):
s = s[:-3].strip()
s = _SCRIPT_STYLE_RE.sub("", s)
s = _DISALLOWED_HTML_TAG_RE.sub("", s)
if "<" not in s:
s = _plain_to_minimal_instruction_html(s)
else:
s = normalize_inline_exercise_media_markup(s) or ""
plain = strip_html_to_plain(s, max_len=max_plain + 200)
if len(plain) > max_plain:
plain = _truncate_plain(plain, max_plain)
s = _plain_to_minimal_instruction_html(plain)
return (normalize_inline_exercise_media_markup(s) or "").strip()
def _merge_preserved_inline_media(original: Optional[str], revised: str) -> str:
"""Haengt fehlende Medien-Verweise aus dem Ausgangstext ans Ende an."""
out = (revised or "").strip()
orig_ids = collect_inline_exercise_media_ids(original)
if not orig_ids:
return out
new_ids = collect_inline_exercise_media_ids(out)
missing = sorted(orig_ids - new_ids)
if not missing:
return out
spans = []
for mid in missing:
spans.append(
f'<span data-shinkan-exercise-media="{mid}" data-shinkan-exercise-media-size="medium" '
f'class="shinkan-inline-media"></span>'
)
block = f"<p>{''.join(spans)}</p>"
return (out + block).strip() if out else block
def _first_balanced_json_object(text: str) -> Optional[str]:
i = text.find("{")
if i < 0:
return None
depth = 0
in_str = False
esc = False
for j in range(i, len(text)):
ch = text[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
continue
if ch == '"':
in_str = True
continue
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[i : j + 1]
return None
def _extract_instruction_rewrite_object(text: str) -> Dict[str, Any]:
s = (text or "").strip()
if not s:
raise ValueError("leer")
if s.startswith("```"):
s = re.sub(r"^```[a-zA-Z0-9]*\s*", "", s)
if s.endswith("```"):
s = s[:-3].strip()
frag = _first_balanced_json_object(s)
if frag:
s = frag
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError("kein JSON-Objekt")
return obj
def _sanitize_instruction_rewrite_payload(
parsed: Mapping[str, Any],
*,
originals: Mapping[str, Optional[str]],
) -> Dict[str, str]:
out: Dict[str, str] = {}
for key in _INSTRUCTION_JSON_KEYS:
max_plain = _INSTRUCTION_FIELD_MAX_PLAIN[key]
html = _sanitize_instruction_field_html(parsed.get(key), max_plain=max_plain)
html = _merge_preserved_inline_media(originals.get(key), html)
out[key] = html
return out
def build_exercise_placeholder_variables(
cur,
*,
@@ -506,6 +648,8 @@ def build_exercise_placeholder_variables(
execution: Optional[str],
focus_area_hint: Optional[str],
focus_areas_context: Optional[Sequence[Tuple[int, bool]]],
preparation: Optional[str] = None,
trainer_notes: Optional[str] = None,
) -> Dict[str, str]:
"""
Baut die Variable-Map fuer {{platzhalter}} passend zur Slug fuer Uebungs-KI.
@@ -515,6 +659,8 @@ def build_exercise_placeholder_variables(
return {}
g_plain = strip_html_to_plain(goal)
e_plain = strip_html_to_plain(execution)
p_plain = strip_html_to_plain(preparation)
n_plain = strip_html_to_plain(trainer_notes)
t_title = (title or "").strip()
focus = (focus_area_hint or "").strip()
ctx: Dict[str, str] = {
@@ -522,8 +668,12 @@ def build_exercise_placeholder_variables(
"exercise_focus_area": focus or "-",
"exercise_goal": g_plain or "-",
"exercise_execution": e_plain or "-",
"exercise_preparation": p_plain or "-",
"exercise_trainer_notes": n_plain or "-",
}
if s == "exercise_summary":
return {k: ctx[k] for k in ("exercise_title", "exercise_focus_area", "exercise_goal", "exercise_execution")}
if s == "exercise_instruction_rewrite":
return ctx
if s == "exercise_skill_suggestions":
catalog = build_contextual_skills_catalog_block(
@@ -686,18 +836,27 @@ def run_exercise_ai_suggestion(
form_ctx: ExerciseFormAiPromptContext,
want_summary: bool,
want_skills: bool,
want_instructions: bool = False,
) -> Dict[str, Any]:
key = _require_openrouter_key()
title = form_ctx.title
goal = form_ctx.goal
execution = form_ctx.execution
preparation = form_ctx.preparation
trainer_notes = form_ctx.trainer_notes
focus_area_hint = form_ctx.focus_hint
focus_areas_context = form_ctx.focus_area_tuples()
g_plain = strip_html_to_plain(goal)
e_plain = strip_html_to_plain(execution)
if not (g_plain.strip() or e_plain.strip()):
if want_instructions:
if not form_ctx.has_instruction_source_text():
raise HTTPException(
status_code=400,
detail="Fuer Anleitungs-Ueberarbeitung mindestens Titel oder ein Anleitungsfeld ausfuellen.",
)
elif 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).",
@@ -712,14 +871,15 @@ def run_exercise_ai_suggestion(
if _ai_debug_on():
fid_list = ",".join(str(x) for x in _ordered_focus_ids(focus_areas_context))
_LOGGER.warning(
"AI_DEBUG exercise_ai suggest want_summary=%s want_skills=%s title_chars=%s goal_plain_chars=%s "
"exec_plain_chars=%s focus_hint_chars=%s focus_ctx_ids=[%s]",
"AI_DEBUG exercise_ai suggest want_summary=%s want_skills=%s want_instructions=%s "
"title_chars=%s goal_plain_chars=%s exec_plain_chars=%s focus_hint_chars=%s focus_ctx_ids=[%s]",
want_summary,
want_skills,
len(t_title),
want_instructions,
len((title or "").strip()),
len(g_plain),
len(e_plain),
len(focus),
len((focus_area_hint or "").strip()),
fid_list,
)
@@ -843,9 +1003,92 @@ def run_exercise_ai_suggestion(
result["skills"] = skills
if want_instructions:
try:
ctx = build_exercise_placeholder_variables(
cur,
slug="exercise_instruction_rewrite",
title=title,
goal=goal,
execution=execution,
preparation=preparation,
trainer_notes=trainer_notes,
focus_area_hint=focus_area_hint,
focus_areas_context=focus_areas_context,
)
except ValueError as e:
raise HTTPException(status_code=500, detail=str(e)) from e
try:
irow, rendered = load_and_render_ai_prompt(cur, "exercise_instruction_rewrite", ctx)
except AiPromptUnavailableError:
raise HTTPException(
status_code=503,
detail="Prompt exercise_instruction_rewrite nicht aktiv oder fehlt in DB.",
) from None
model_instr = effective_openrouter_model_for_prompt_row(irow)
models_by_slug["exercise_instruction_rewrite"] = model_instr
prompt = rendered.text
if _ai_debug_on():
_LOGGER.warning(
"AI_DEBUG exercise_ai instructions prompt_slug=exercise_instruction_rewrite prompt_chars=%s",
len(prompt),
)
sys_hint = (
"Du antwortest nur mit validem JSON-Objekt (Schluessel goal, execution, preparation, trainer_notes). "
"Keine Kommentare ausserhalb des JSON."
)
try:
raw = openrouter_chat_completion(
api_key=key,
model=model_instr,
user_content=prompt,
system_content=sys_hint,
temperature=0.2,
)
except OpenRouterError as e:
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
body = (raw or "").strip()
if not body:
raise HTTPException(
status_code=502,
detail="OpenRouter/KI lieferte leeren Inhalt fuer Anleitungs-Ueberarbeitung.",
)
try:
parsed = _extract_instruction_rewrite_object(body)
except (json.JSONDecodeError, ValueError) as e:
if _ai_debug_on():
_LOGGER.warning(
"AI_DEBUG exercise_ai instructions JSON parse_failed err=%s head=%s",
e,
(body.replace("\r", "").replace("\n", " ").strip())[:400],
)
raise HTTPException(
status_code=502,
detail="KI lieferte kein verwertbares JSON fuer die Anleitung.",
) from e
originals = {
"goal": goal,
"execution": execution,
"preparation": preparation,
"trainer_notes": trainer_notes,
}
fields = _sanitize_instruction_rewrite_payload(parsed, originals=originals)
if not any((fields.get(k) or "").strip() for k in _INSTRUCTION_JSON_KEYS):
raise HTTPException(
status_code=502,
detail="KI lieferte leere Anleitungs-Felder.",
)
result["instructions"] = {
"fields": fields,
"ai_generated": True,
"model": model_instr,
}
result["models_by_slug"] = models_by_slug
if want_skills:
result["model"] = models_by_slug["exercise_skill_suggestions"]
elif want_instructions:
result["model"] = models_by_slug["exercise_instruction_rewrite"]
elif want_summary:
result["model"] = models_by_slug["exercise_summary"]
else: