Enhance Planning Exercise Path Builder and Retrieval Logic
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m23s

- Updated the path selection logic to incorporate semantic gating, ensuring only relevant exercises are considered based on semantic scores.
- Introduced new functions for building path target profiles and resolving semantic skill weights, enhancing the contextual understanding of exercise suggestions.
- Improved the retrieval process by applying dynamic retrieval weights based on semantic strength, refining the accuracy of exercise recommendations.
- Incremented version to 0.8.188 and updated changelog to document these enhancements in planning AI functionality.
This commit is contained in:
Lars committed 2026-05-23 12:38:38 +02:00
1 parent c2c736dafc
commit 5b73d1a1f5
6 files changed
+333 -73

No files matched your search

+173 -34
View File
@@ -39,6 +39,17 @@ _OTHER_TECHNIQUE_PATTERNS: Tuple[Tuple[str, Tuple[str, ...]], ...] = (
("gedan barai", ("age uke", "soto uke")),
)
_TECHNIQUE_EXPECTED_SKILLS: Dict[str, Tuple[str, ...]] = {
"mae geri": ("Geri Waza", "Koordination", "Gleichgewicht", "Kime"),
"mawashi geri": ("Geri Waza", "Koordination", "Gleichgewicht"),
"yoko geri": ("Geri Waza", "Koordination", "Gleichgewicht"),
"ushiro geri": ("Geri Waza", "Koordination", "Gleichgewicht"),
"sakuto geri": ("Geri Waza", "Koordination", "Gleichgewicht"),
"mikazuki geri": ("Geri Waza", "Koordination", "Gleichgewicht"),
}
_DEFAULT_TECHNIQUE_SKILLS: Tuple[str, ...] = ("Geri Waza", "Koordination", "Gleichgewicht")
_ARC_PHASES: Tuple[Tuple[str, Tuple[str, ...]], ...] = (
("einstieg", ("einstieg", "erlernen", "lernen", "anfänger", "anfaenger", "beginn", "grund")),
("grundlage", ("grundlage", "fundament", "basis", "basic")),
@@ -223,19 +234,17 @@ def build_semantic_brief(query: Optional[str]) -> PlanningSemanticBrief:
if arc:
strength = max(strength, 0.55 if technique else 0.45)
extra_phrases = _keyword_phrases_from_query(q)
for ph in extra_phrases:
if ph not in must and not any(ph in m or m in ph for m in must):
if len(ph) >= 5:
must.append(ph)
# Keine generischen Stichwörter in must_phrases — sonst verwässert das Scoring.
retrieval_parts = list(must)
if primary:
retrieval_parts.append(primary)
if arc:
retrieval_parts.extend(arc[:2])
retrieval = " ".join(dict.fromkeys(retrieval_parts))[:500] if retrieval_parts else q
if len(q) >= 24 and not technique:
strength = max(strength, 0.4)
retrieval = " ".join(must[:4]) if must else q
if arc and primary:
retrieval = f"{primary} {' '.join(arc[:2])}"
return PlanningSemanticBrief(
primary_topic=primary,
topic_type=topic_type,
@@ -279,7 +288,8 @@ def merge_semantic_brief_llm(
pass
if data.get("must_phrases"):
data["retrieval_query"] = " ".join(data["must_phrases"][:4])[:500]
core = semantic_core_phrases(PlanningSemanticBrief.model_validate(data))
data["retrieval_query"] = " ".join(core[:4])[:500] if core else data.get("retrieval_query", "")
out = PlanningSemanticBrief.model_validate(data)
if out.primary_topic and out.topic_type == "general":
out = out.model_copy(update={"topic_type": "technique"})
@@ -351,16 +361,17 @@ def step_retrieval_query(
) -> str:
phase = step_phase_for_index(brief, step_index, max_steps)
parts: List[str] = []
if brief.retrieval_query:
parts.append(brief.retrieval_query)
elif goal_query:
parts.append(goal_query)
if brief.primary_topic and brief.primary_topic not in " ".join(parts).lower():
if brief.primary_topic:
parts.append(brief.primary_topic)
elif brief.retrieval_query:
parts.append(brief.retrieval_query.split()[0] if brief.retrieval_query else "")
if phase:
hint = _PHASE_QUERY_HINTS.get(phase, phase)
parts.append(hint)
return _normalize_query(" ".join(parts)) or _normalize_query(goal_query)
parts.append(phase)
if not parts and brief.retrieval_query:
parts.append(brief.retrieval_query)
elif not parts and goal_query:
parts.append(goal_query)
return _normalize_query(" ".join(p for p in parts if p)) or _normalize_query(goal_query)
def apply_dynamic_retrieval_weights(
@@ -440,30 +451,37 @@ def score_exercise_semantic_relevance(
reasons: List[str] = []
must = list(brief.must_phrases or [])
exclude = list(brief.exclude_phrases or [])
core = semantic_core_phrases(brief)
core_hits = sum(1 for ph in core if _phrase_in_blob(ph, blob))
must_hits = sum(1 for ph in must if _phrase_in_blob(ph, blob))
exclude_hits = sum(1 for ph in exclude if _phrase_in_blob(ph, blob))
score = 0.0
if must:
must_ratio = must_hits / len(must)
score += 0.55 * must_ratio
if must_hits == len(must):
reasons.append("Alle Kernbegriffe der Anfrage im Übungstext")
elif must_hits > 0:
reasons.append("Teilweise passende Kernbegriffe")
elif brief.primary_topic and _phrase_in_blob(brief.primary_topic, blob):
score += 0.45
reasons.append(f"Thema „{brief.primary_topic}“ im Übungstext")
if core:
core_ratio = core_hits / len(core)
score += 0.62 * core_ratio
if core_hits == len(core):
reasons.append("Kern-Thema der Anfrage im Übungstext")
elif core_hits > 0:
reasons.append("Teilweise passend zum Kern-Thema")
elif brief.primary_topic and _phrase_in_blob(brief.primary_topic, blob):
score += 0.5
score += 0.55
reasons.append(f"Thema „{brief.primary_topic}“ im Übungstext")
if exclude_hits > 0:
penalty = min(0.55, 0.18 * exclude_hits)
if must_hits == 0 or exclude_hits >= must_hits:
score -= penalty
reasons.append("Enthält ausgeschlossene Nebenthemen")
if must and core != must:
extra_ratio = must_hits / len(must)
score += 0.12 * extra_ratio
primary_ok = bool(core_hits) or (
brief.primary_topic and _phrase_in_blob(brief.primary_topic, blob)
)
if exclude_hits > 0 and not primary_ok:
penalty = min(0.65, 0.22 * exclude_hits)
score -= penalty
reasons.append("Enthält ausgeschlossene Nebenthemen")
elif exclude_hits > 0 and primary_ok:
score -= min(0.12, 0.06 * exclude_hits)
if step_phase and step_phase in _PHASE_QUERY_HINTS:
phase_markers = next((markers for phase, markers in _ARC_PHASES if phase == step_phase), ())
@@ -479,13 +497,134 @@ def score_exercise_semantic_relevance(
return max(0.0, min(1.0, round(score, 4))), reasons[:4]
def semantic_core_phrases(brief: PlanningSemanticBrief) -> List[str]:
"""Harte Kernphrasen fürs Matching."""
if brief.primary_topic:
return [_normalize_phrase(brief.primary_topic)]
core = [_normalize_phrase(p) for p in (brief.must_phrases or [])[:2] if p]
return [p for p in core if p]
def resolve_semantic_skill_weights(cur, brief: PlanningSemanticBrief) -> Dict[int, float]:
"""Deterministisches Fähigkeitserwartungsprofil aus Technik-Thema."""
topic = _normalize_phrase(brief.primary_topic or "")
if topic in _TECHNIQUE_EXPECTED_SKILLS:
names = list(_TECHNIQUE_EXPECTED_SKILLS[topic])
elif brief.topic_type == "technique" or "geri" in topic:
names = list(_DEFAULT_TECHNIQUE_SKILLS)
else:
return {}
weights: Dict[int, float] = {}
for name in names[:6]:
cur.execute(
"""
SELECT id, name FROM skills
WHERE (status IS NULL OR status = 'active')
AND LOWER(name) LIKE %s
ORDER BY CASE WHEN LOWER(name) = %s THEN 0 WHEN LOWER(name) LIKE %s THEN 1 ELSE 2 END,
LENGTH(name) ASC
LIMIT 1
""",
(f"%{name.lower()}%", name.lower(), f"{name.lower()}%"),
)
row = cur.fetchone()
if row:
sid = int(row["id"])
weights[sid] = max(weights.get(sid, 0.0), 1.0)
return weights
def enrich_target_with_semantic_expectations(
target,
*,
skill_weights: Dict[int, float],
):
from planning_exercise_profiles import PlanningTargetProfile, _merge_weight_maps, _normalize_weight_map
if not skill_weights:
return target
merged = _normalize_weight_map(_merge_weight_maps(dict(target.skill_weights), skill_weights, scale=1.0))
sources = list(target.sources)
if "semantic_expectation" not in sources:
sources.append("semantic_expectation")
return PlanningTargetProfile(
focus_area_ids=dict(target.focus_area_ids),
style_direction_ids=dict(target.style_direction_ids),
training_type_ids=dict(target.training_type_ids),
target_group_ids=dict(target.target_group_ids),
skill_weights=merged,
skill_gap_weights=dict(target.skill_gap_weights),
skill_plan_weights=dict(target.skill_plan_weights),
sources=sources,
)
def apply_path_retrieval_weights(brief: PlanningSemanticBrief) -> Dict[str, float]:
"""Pfad-Builder: Semantik + Profil dominieren."""
sem = float(brief.semantic_strength or 0.0)
if sem >= 0.65:
return {
"semantic": 0.50,
"fulltext": 0.16,
"profile": 0.26,
"progression": 0.04,
"skill": 0.04,
"plan": 0.0,
"repeat_unit": -0.40,
"repeat_group": -0.15,
}
if sem >= 0.35:
return {
"semantic": 0.38,
"fulltext": 0.18,
"profile": 0.28,
"progression": 0.06,
"skill": 0.06,
"plan": 0.04,
"repeat_unit": -0.35,
"repeat_group": -0.15,
}
return {
"semantic": 0.22,
"fulltext": 0.22,
"profile": 0.28,
"progression": 0.10,
"skill": 0.10,
"plan": 0.08,
"repeat_unit": -0.30,
"repeat_group": -0.15,
}
def exercise_passes_path_semantic_gate(
*,
semantic_score: float,
title: str,
brief: PlanningSemanticBrief,
) -> bool:
if brief.semantic_strength < 0.55:
return True
if semantic_score >= 0.20:
return True
topic = brief.primary_topic or ""
if topic and _phrase_in_blob(topic, (title or "").lower()):
return True
return False
__all__ = [
"PlanningSemanticBrief",
"apply_dynamic_retrieval_weights",
"apply_path_retrieval_weights",
"brief_to_summary_dict",
"build_semantic_brief",
"enrich_target_with_semantic_expectations",
"exercise_passes_path_semantic_gate",
"merge_semantic_brief_llm",
"resolve_semantic_skill_weights",
"score_exercise_semantic_relevance",
"semantic_core_phrases",
"step_phase_for_index",
"step_retrieval_query",
"try_enrich_semantic_brief_with_llm",