Refactor Planning Exercise Suggestion and Enhance LLM Integration
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m16s

- Replaced the previous exercise matching logic with a new multistage planning retrieval process, improving the accuracy of exercise suggestions.
- Introduced LLM gates to limit LLM calls based on query length and intent application, optimizing performance and resource usage.
- Updated the `compose_retrieval_phase` function to include profile preselection, enhancing the retrieval process.
- Incremented version to 0.5.0 and updated changelog to reflect these significant enhancements in planning AI capabilities.
This commit is contained in:
Lars committed 2026-05-22 22:56:28 +02:00
1 parent b0611b9f7f
commit 8e68261bc1
6 files changed
+756 -275

No files matched your search

+34 -166
View File
@@ -12,14 +12,12 @@ from fastapi import HTTPException
from pydantic import BaseModel, Field
from tenant_context import TenantContext, library_content_visibility_sql
from planning_exercise_profiles import (
load_exercise_match_profiles_bulk,
score_exercise_against_target,
)
from planning_exercise_retrieval import run_multistage_planning_retrieval
from planning_exercise_llm_rank import try_llm_rerank_planning_hits
from planning_exercise_target_pipeline import (
build_planning_target_with_query_pipeline,
compose_retrieval_phase,
should_run_llm_rank_pipeline,
)
# Planungs-Berechtigung + Sektionen (bestehende Implementierung)
@@ -43,7 +41,7 @@ VALID_INTENTS = {
INTENT_FREE_SEARCH,
}
_CANDIDATE_POOL_LIMIT = 400
_LLM_RERANK_PRE_LIMIT = 32
@@ -257,14 +255,6 @@ def _normalize_query(query: Optional[str]) -> str:
return re.sub(r"\s+", " ", (query or "").strip())
def _skill_jaccard(a: Set[int], b: Set[int]) -> float:
if not a or not b:
return 0.0
inter = len(a & b)
union = len(a | b)
return inter / union if union else 0.0
def _apply_client_planned_override(
cur,
pack: Dict[str, Any],
@@ -493,162 +483,37 @@ def suggest_planning_exercises(
effective_club_id=tenant.effective_club_id,
)
where = [vis_sql, "COALESCE(e.status, '') <> %s"]
params: List[Any] = []
if query:
ft_select = "ts_rank_cd(e.search_vector, plainto_tsquery('german', %s)) AS ft_rank"
params.append(query)
else:
ft_select = "0.0::float AS ft_rank"
params.extend(list(vis_params))
params.append("archived")
ek_filtered: List[str] = []
if body.exercise_kind_any:
for raw in body.exercise_kind_any:
s = str(raw or "").strip().lower()
if s in ("simple", "combination") and s not in ek_filtered:
ek_filtered.append(s)
if ek_filtered:
ph = ",".join(["%s"] * len(ek_filtered))
where.append(f"(LOWER(TRIM(COALESCE(e.exercise_kind::text,''))) IN ({ph}))")
params.extend(ek_filtered)
sql = f"""
SELECT e.id, e.title, e.summary,
(
SELECT fa.name FROM exercise_focus_areas efa
JOIN focus_areas fa ON fa.id = efa.focus_area_id
WHERE efa.exercise_id = e.id
ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC
LIMIT 1
) AS primary_focus_name,
{ft_select}
FROM exercises e
WHERE {' AND '.join(where)}
ORDER BY e.updated_at DESC, e.id DESC
LIMIT %s
"""
params.append(_CANDIDATE_POOL_LIMIT)
cur.execute(sql, params)
rows = cur.fetchall()
hits, skills_by_ex, profile_preselect_applied = run_multistage_planning_retrieval(
cur,
vis_sql=vis_sql,
vis_params=vis_params,
query=query,
exercise_kind_any=body.exercise_kind_any,
target=target_profile,
intent=intent,
intent_weights=weights,
pack=pack,
)
planned_set = set(pack["planned_exercise_ids"])
group_recent_set = set(pack["group_recent_exercise_ids"])
progression_set = set(pack["progression_successor_ids"])
anchor_skills = set(pack["anchor_skill_ids"])
anchor_id = pack.get("anchor_exercise_id")
progression_notes = pack.get("progression_edge_notes") or {}
last_planned_skills: Set[int] = set()
if pack["planned_exercise_ids"]:
last_planned_skills = _load_skill_ids_for_exercise(cur, pack["planned_exercise_ids"][-1])
# Skill-IDs + ExerciseMatchProfile pro Kandidat (Batch)
cand_ids = [int(r["id"]) for r in rows]
skills_by_ex: Dict[int, Set[int]] = {cid: set() for cid in cand_ids}
match_profiles = load_exercise_match_profiles_bulk(cur, cand_ids)
if cand_ids:
ph = ",".join(["%s"] * len(cand_ids))
cur.execute(
f"SELECT exercise_id, skill_id FROM exercise_skills WHERE exercise_id IN ({ph})",
cand_ids,
)
for r in cur.fetchall():
skills_by_ex.setdefault(int(r["exercise_id"]), set()).add(int(r["skill_id"]))
max_ft = 0.0
scored: List[Dict[str, Any]] = []
for row in rows:
eid = int(row["id"])
if anchor_id and eid == int(anchor_id):
continue
ft = float(row.get("ft_rank") or 0.0)
if ft > max_ft:
max_ft = ft
scored.append(
{
"row": row,
"eid": eid,
"ft": ft,
"skills": skills_by_ex.get(eid, set()),
}
)
hits: List[Dict[str, Any]] = []
for item in scored:
eid = item["eid"]
row = item["row"]
ft_norm = (item["ft"] / max_ft) if max_ft > 0 else 0.0
prog_hit = 1.0 if eid in progression_set else 0.0
skill_sim = _skill_jaccard(anchor_skills, item["skills"]) if anchor_skills else 0.0
plan_aff = 0.0
if last_planned_skills and item["skills"]:
plan_aff = _skill_jaccard(last_planned_skills, item["skills"])
repeat_unit = 1.0 if eid in planned_set else 0.0
repeat_group = 1.0 if eid in group_recent_set else 0.0
profile_score = 0.0
profile_reasons: List[str] = []
emp = match_profiles.get(eid)
if emp:
profile_score, profile_reasons = score_exercise_against_target(
emp, target_profile, intent=intent
)
score = (
weights["fulltext"] * ft_norm
+ weights["progression"] * prog_hit
+ weights["skill"] * skill_sim
+ weights["plan"] * plan_aff
+ weights["profile"] * profile_score
+ weights["repeat_unit"] * repeat_unit
+ weights["repeat_group"] * repeat_group
)
reasons: List[str] = []
if query and ft_norm >= 0.35:
reasons.append("Volltext-Treffer")
if prog_hit > 0:
note = progression_notes.get(eid)
reasons.append(
f"Nachfolger im Progressionsgraph{f': {note}' if note else ''}"
)
if skill_sim >= 0.2 and anchor_id:
reasons.append("Fähigkeiten passen zur Anker-Übung")
if plan_aff >= 0.25:
reasons.append("Schließt an Skills der letzten geplanten Übung an")
if repeat_unit > 0:
reasons.append("Bereits in dieser Einheit eingeplant")
if repeat_group > 0 and repeat_unit <= 0:
reasons.append("Kürzlich in der Gruppe verwendet")
for pr in profile_reasons:
if pr not in reasons:
reasons.append(pr)
if score <= 0 and not reasons and not query:
# Leere Query: trotzdem schwache Kandidaten mit Skill/Progression
if prog_hit or skill_sim or plan_aff or profile_score:
score = 0.05 + prog_hit * 0.3 + skill_sim * 0.2 + profile_score * 0.25
hits.append(
{
"id": eid,
"title": row.get("title"),
"summary": row.get("summary"),
"focus_area": row.get("primary_focus_name"),
"score": round(max(0.0, min(1.0, score)), 4),
"reasons": reasons,
}
)
hits.sort(key=lambda h: (-h["score"], h.get("title") or ""))
llm_applied = False
retrieval_phase = compose_retrieval_phase(query_intent=query_intent_applied, llm_rank=False)
if body.include_llm_rank:
llm_rank_applied = False
retrieval_phase = compose_retrieval_phase(
profile_preselect=profile_preselect_applied,
query_intent=query_intent_applied,
llm_rank=False,
)
run_llm_rank = should_run_llm_rank_pipeline(
query,
scenario_kind,
include_llm_rank=body.include_llm_rank,
query_intent_applied=query_intent_applied,
hits=hits,
)
if run_llm_rank:
pre_limit = max(int(body.limit), _LLM_RERANK_PRE_LIMIT)
pool_hits = hits[:pre_limit]
pool_hits, llm_applied = try_llm_rerank_planning_hits(
pool_hits, llm_rank_applied = try_llm_rerank_planning_hits(
cur,
hits=pool_hits,
skills_by_ex=skills_by_ex,
@@ -665,8 +530,9 @@ def suggest_planning_exercises(
target_profile_summary=target_profile_summary,
limit=int(body.limit),
)
if llm_applied:
if llm_rank_applied:
retrieval_phase = compose_retrieval_phase(
profile_preselect=profile_preselect_applied,
query_intent=query_intent_applied,
llm_rank=True,
)
@@ -696,7 +562,9 @@ def suggest_planning_exercises(
"scenario_kind": scenario_kind,
"query_intent_summary": query_intent_summary,
"retrieval_phase": retrieval_phase,
"llm_rank_applied": llm_applied,
"profile_preselect_applied": profile_preselect_applied,
"llm_rank_applied": llm_rank_applied,
"llm_intent_applied": query_intent_applied,
"intent_resolved": intent,
"intent_heuristic": heuristic_intent,
"query_normalized": query or None,