Enhance Planning Exercise Retrieval and Suggestion with Semantic Features
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
- Introduced new functions to load exercise goals and variant names in chunks, improving data retrieval efficiency. - Integrated semantic scoring into the ranking logic, allowing for more nuanced exercise suggestions based on semantic relevance. - Updated the planning exercise suggestion process to include semantic brief handling, enriching the context for exercise recommendations. - Adjusted the retrieval phase to incorporate dynamic retrieval weights based on semantic strength, enhancing the overall suggestion accuracy. - Incremented version to 0.8.186 and updated changelog to reflect these significant enhancements in planning AI functionality.
This commit is contained in:
1 parent
a19ed02300
commit
c6b8c396ad
14 files changed
+1393
-41
No files matched your search
@@ -1,18 +1,33 @@
|
||||
"""
|
||||
Planungs-KI Phase C3: Pfad-Vorschläge für Progressionsgraphen.
|
||||
Planungs-KI Phase C3/E: Pfad-Vorschläge für Progressionsgraphen.
|
||||
|
||||
Ziel-Freitext → iterative Hybrid-Suche (Schritt 1 mit optional LLM-Profil, Folgeschritte deterministisch).
|
||||
Ziel-Freitext → semantisch gewichtete Schritte → Lücken/Brücken → optional LLM-QA.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
||||
|
||||
from fastapi import HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from tenant_context import TenantContext, library_content_visibility_sql
|
||||
from planning_exercise_profiles import PlanningTargetProfile
|
||||
from planning_exercise_path_qa import (
|
||||
build_path_qa_summary,
|
||||
detect_path_gaps,
|
||||
insert_bridge_exercises,
|
||||
try_llm_qa_progression_path,
|
||||
)
|
||||
from planning_exercise_retrieval import run_multistage_planning_retrieval
|
||||
from planning_exercise_semantics import (
|
||||
PlanningSemanticBrief,
|
||||
apply_dynamic_retrieval_weights,
|
||||
brief_to_summary_dict,
|
||||
build_semantic_brief,
|
||||
step_phase_for_index,
|
||||
step_retrieval_query,
|
||||
try_enrich_semantic_brief_with_llm,
|
||||
)
|
||||
from planning_exercise_target_pipeline import build_planning_target_with_query_pipeline
|
||||
from planning_exercise_progression import apply_progression_context_to_pack
|
||||
from planning_exercise_suggest import (
|
||||
@@ -30,23 +45,32 @@ class ProgressionPathSuggestRequest(BaseModel):
|
||||
query: str = Field(..., min_length=3, max_length=2000)
|
||||
max_steps: int = Field(default=5, ge=2, le=10)
|
||||
include_llm_intent: bool = True
|
||||
include_path_qa: bool = True
|
||||
include_llm_path_qa: bool = True
|
||||
progression_graph_id: Optional[int] = Field(default=None, ge=1)
|
||||
exercise_kind_any: Optional[List[str]] = None
|
||||
|
||||
|
||||
def _pick_next_path_hit(
|
||||
def _pick_best_path_hit(
|
||||
hits: List[Dict[str, Any]],
|
||||
used_exercise_ids: Set[int],
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
best: Optional[Dict[str, Any]] = None
|
||||
best_key: Tuple[float, float] = (-1.0, -1.0)
|
||||
for hit in hits:
|
||||
eid = int(hit["id"])
|
||||
if eid in used_exercise_ids:
|
||||
continue
|
||||
return hit
|
||||
return None
|
||||
sem = float(hit.get("semantic_score") or 0.0)
|
||||
score = float(hit.get("score") or 0.0)
|
||||
key = (sem, score)
|
||||
if key > best_key:
|
||||
best_key = key
|
||||
best = hit
|
||||
return best
|
||||
|
||||
|
||||
def _hit_to_path_step(hit: Dict[str, Any]) -> Dict[str, Any]:
|
||||
def _hit_to_path_step(hit: Dict[str, Any], *, is_bridge: bool = False) -> Dict[str, Any]:
|
||||
raw_vid = hit.get("suggested_variant_id")
|
||||
variant_id: Optional[int] = None
|
||||
if raw_vid is not None:
|
||||
@@ -56,17 +80,21 @@ def _hit_to_path_step(hit: Dict[str, Any]) -> Dict[str, Any]:
|
||||
variant_id = vid
|
||||
except (TypeError, ValueError):
|
||||
variant_id = None
|
||||
return {
|
||||
step = {
|
||||
"exercise_id": int(hit["id"]),
|
||||
"variant_id": variant_id,
|
||||
"title": hit.get("title"),
|
||||
"summary": hit.get("summary"),
|
||||
"score": hit.get("score"),
|
||||
"semantic_score": hit.get("semantic_score"),
|
||||
"reasons": list(hit.get("reasons") or []),
|
||||
"variants": hit.get("variants") or [],
|
||||
"suggested_variant_id": hit.get("suggested_variant_id"),
|
||||
"suggested_variant_name": hit.get("suggested_variant_name"),
|
||||
}
|
||||
if is_bridge:
|
||||
step["is_bridge"] = True
|
||||
return step
|
||||
|
||||
|
||||
def _run_path_step_retrieval(
|
||||
@@ -75,13 +103,22 @@ def _run_path_step_retrieval(
|
||||
tenant: TenantContext,
|
||||
goal_query: str,
|
||||
step_index: int,
|
||||
max_steps: int,
|
||||
planned_ids: List[int],
|
||||
anchor_id: Optional[int],
|
||||
anchor_variant_id: Optional[int],
|
||||
progression_graph_id: Optional[int],
|
||||
include_llm_intent: bool,
|
||||
exercise_kind_any: Optional[List[str]],
|
||||
semantic_brief: PlanningSemanticBrief,
|
||||
bridge_mode: bool = False,
|
||||
step_a: Optional[Dict[str, Any]] = None,
|
||||
step_b: Optional[Dict[str, Any]] = None,
|
||||
) -> Tuple[List[Dict[str, Any]], PlanningTargetProfile, Dict[str, Any], str]:
|
||||
step_query = step_retrieval_query(semantic_brief, goal_query, step_index, max_steps)
|
||||
if bridge_mode and step_a and step_b:
|
||||
step_query = f"{semantic_brief.retrieval_query or goal_query} brücke zwischen schritten"
|
||||
|
||||
pack: Dict[str, Any] = {
|
||||
"unit_id": None,
|
||||
"unit": {
|
||||
@@ -94,14 +131,17 @@ def _run_path_step_retrieval(
|
||||
"group_name": None,
|
||||
"section_order_index": None,
|
||||
"section_title": None,
|
||||
"section_guidance_notes": goal_query if step_index == 0 else None,
|
||||
"section_guidance_notes": goal_query if step_index == 0 and not bridge_mode else step_query,
|
||||
"planned_exercise_ids": list(planned_ids),
|
||||
"anchor_exercise_id": anchor_id,
|
||||
"anchor_title": None,
|
||||
"anchor_skill_ids": sorted(_load_skill_ids_for_exercise(cur, anchor_id)),
|
||||
"group_recent_exercise_ids": [],
|
||||
"context_mode": "progression_path",
|
||||
"has_planning_reference": bool(planned_ids or anchor_id),
|
||||
"has_planning_reference": bool(planned_ids or anchor_id or bridge_mode),
|
||||
"semantic_brief": semantic_brief,
|
||||
"retrieval_query": step_query,
|
||||
"path_step_phase": step_phase_for_index(semantic_brief, step_index, max_steps),
|
||||
}
|
||||
pack = apply_progression_context_to_pack(
|
||||
cur,
|
||||
@@ -111,14 +151,12 @@ def _run_path_step_retrieval(
|
||||
anchor_variant_id=anchor_variant_id,
|
||||
)
|
||||
|
||||
if step_index == 0:
|
||||
if step_index == 0 and not bridge_mode:
|
||||
heuristic_intent = resolve_planning_exercise_intent(goal_query, "free_search")
|
||||
step_query = goal_query
|
||||
else:
|
||||
heuristic_intent = INTENT_SUGGEST_NEXT
|
||||
step_query = "nächste sinnvolle übung im pfad"
|
||||
|
||||
has_plan_ref = bool(pack.get("has_planning_reference")) or step_index > 0
|
||||
has_plan_ref = bool(pack.get("has_planning_reference"))
|
||||
pipeline_context = {
|
||||
"unit_title": None,
|
||||
"group_name": None,
|
||||
@@ -142,14 +180,20 @@ def _run_path_step_retrieval(
|
||||
planned_exercise_ids=pack["planned_exercise_ids"],
|
||||
section_planned_exercise_ids=[],
|
||||
anchor_exercise_id=pack.get("anchor_exercise_id"),
|
||||
query=goal_query if step_index == 0 else step_query,
|
||||
query=goal_query if step_index == 0 and not bridge_mode else step_query,
|
||||
heuristic_intent=heuristic_intent,
|
||||
include_llm_intent=include_llm_intent and step_index == 0,
|
||||
include_llm_intent=include_llm_intent and step_index == 0 and not bridge_mode,
|
||||
context_summary=pipeline_context,
|
||||
has_planning_reference=has_plan_ref,
|
||||
)
|
||||
|
||||
weights = _intent_weights(intent)
|
||||
weights = apply_dynamic_retrieval_weights(
|
||||
_intent_weights(intent),
|
||||
semantic_brief,
|
||||
scenario="free_search" if step_index == 0 and not bridge_mode else "progression",
|
||||
has_planning_reference=has_plan_ref,
|
||||
)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
@@ -163,7 +207,7 @@ def _run_path_step_retrieval(
|
||||
cur,
|
||||
vis_sql=vis_sql,
|
||||
vis_params=vis_params,
|
||||
query=step_query if step_index > 0 else goal_query,
|
||||
query=step_query,
|
||||
exercise_kind_any=exercise_kind_any,
|
||||
target=target_profile,
|
||||
intent=intent,
|
||||
@@ -174,6 +218,45 @@ def _run_path_step_retrieval(
|
||||
return hits, target_profile, query_intent_summary, intent
|
||||
|
||||
|
||||
def _make_bridge_search_fn(
|
||||
cur,
|
||||
*,
|
||||
tenant: TenantContext,
|
||||
goal_query: str,
|
||||
max_steps: int,
|
||||
progression_graph_id: Optional[int],
|
||||
include_llm_intent: bool,
|
||||
exercise_kind_any: Optional[List[str]],
|
||||
semantic_brief: PlanningSemanticBrief,
|
||||
planned_ids: List[int],
|
||||
) -> Callable[..., List[Dict[str, Any]]]:
|
||||
def _bridge_search(
|
||||
step_a: Dict[str, Any],
|
||||
step_b: Dict[str, Any],
|
||||
_gap: Dict[str, Any],
|
||||
) -> List[Dict[str, Any]]:
|
||||
hits, _, _, _ = _run_path_step_retrieval(
|
||||
cur,
|
||||
tenant=tenant,
|
||||
goal_query=goal_query,
|
||||
step_index=1,
|
||||
max_steps=max_steps,
|
||||
planned_ids=list(planned_ids) + [int(step_a["exercise_id"])],
|
||||
anchor_id=int(step_a["exercise_id"]),
|
||||
anchor_variant_id=step_a.get("variant_id"),
|
||||
progression_graph_id=progression_graph_id,
|
||||
include_llm_intent=include_llm_intent,
|
||||
exercise_kind_any=exercise_kind_any,
|
||||
semantic_brief=semantic_brief,
|
||||
bridge_mode=True,
|
||||
step_a=step_a,
|
||||
step_b=step_b,
|
||||
)
|
||||
return hits
|
||||
|
||||
return _bridge_search
|
||||
|
||||
|
||||
def suggest_progression_path(
|
||||
cur,
|
||||
*,
|
||||
@@ -189,6 +272,13 @@ def suggest_progression_path(
|
||||
raise HTTPException(status_code=400, detail="Ziel-Anfrage: mindestens 3 Zeichen")
|
||||
|
||||
max_steps = int(body.max_steps)
|
||||
semantic_brief = build_semantic_brief(goal_query)
|
||||
semantic_llm_applied = False
|
||||
if body.include_llm_intent and semantic_brief.semantic_strength >= 0.35:
|
||||
semantic_brief, semantic_llm_applied = try_enrich_semantic_brief_with_llm(
|
||||
cur, goal_query, semantic_brief
|
||||
)
|
||||
|
||||
used: Set[int] = set()
|
||||
steps: List[Dict[str, Any]] = []
|
||||
planned_ids: List[int] = []
|
||||
@@ -203,17 +293,19 @@ def suggest_progression_path(
|
||||
tenant=tenant,
|
||||
goal_query=goal_query,
|
||||
step_index=step_index,
|
||||
max_steps=max_steps,
|
||||
planned_ids=planned_ids,
|
||||
anchor_id=anchor_id,
|
||||
anchor_variant_id=anchor_variant_id,
|
||||
progression_graph_id=body.progression_graph_id,
|
||||
include_llm_intent=body.include_llm_intent,
|
||||
exercise_kind_any=body.exercise_kind_any,
|
||||
semantic_brief=semantic_brief,
|
||||
)
|
||||
if step_index == 0:
|
||||
first_intent_summary = query_intent_summary
|
||||
|
||||
hit = _pick_next_path_hit(hits, used)
|
||||
hit = _pick_best_path_hit(hits, used)
|
||||
if not hit:
|
||||
break
|
||||
|
||||
@@ -231,7 +323,56 @@ def suggest_progression_path(
|
||||
detail="Zu wenig passende Übungen für einen Pfad (mindestens 2 Schritte). Ziel präzisieren oder max_steps senken.",
|
||||
)
|
||||
|
||||
gaps: List[Dict[str, Any]] = []
|
||||
bridge_inserts: List[Dict[str, Any]] = []
|
||||
llm_qa: Optional[Dict[str, Any]] = None
|
||||
llm_qa_applied = False
|
||||
|
||||
if body.include_path_qa:
|
||||
gaps = detect_path_gaps(cur, steps, brief=semantic_brief)
|
||||
if gaps:
|
||||
bridge_fn = _make_bridge_search_fn(
|
||||
cur,
|
||||
tenant=tenant,
|
||||
goal_query=goal_query,
|
||||
max_steps=max_steps,
|
||||
progression_graph_id=body.progression_graph_id,
|
||||
include_llm_intent=body.include_llm_intent,
|
||||
exercise_kind_any=body.exercise_kind_any,
|
||||
semantic_brief=semantic_brief,
|
||||
planned_ids=planned_ids,
|
||||
)
|
||||
steps, bridge_inserts = insert_bridge_exercises(
|
||||
cur,
|
||||
steps,
|
||||
gaps,
|
||||
brief=semantic_brief,
|
||||
bridge_search_fn=bridge_fn,
|
||||
)
|
||||
|
||||
if body.include_llm_path_qa:
|
||||
llm_qa, llm_qa_applied = try_llm_qa_progression_path(
|
||||
cur,
|
||||
goal_query=goal_query,
|
||||
brief=semantic_brief,
|
||||
steps=steps,
|
||||
gaps=gaps,
|
||||
bridge_inserts=bridge_inserts,
|
||||
)
|
||||
|
||||
path_qa = build_path_qa_summary(
|
||||
gaps=gaps,
|
||||
bridge_inserts=bridge_inserts,
|
||||
llm_qa=llm_qa,
|
||||
llm_applied=llm_qa_applied,
|
||||
)
|
||||
|
||||
target_profile_summary = target_profile.to_summary_dict(cur) if target_profile else None
|
||||
retrieval_parts = ["profile_v1", "full_library", "path_builder", "semantics"]
|
||||
if body.include_path_qa:
|
||||
retrieval_parts.append("path_qa")
|
||||
if llm_qa_applied:
|
||||
retrieval_parts.append("llm_path_qa")
|
||||
|
||||
return {
|
||||
"goal_query": goal_query,
|
||||
@@ -239,14 +380,21 @@ def suggest_progression_path(
|
||||
"steps": steps,
|
||||
"step_count": len(steps),
|
||||
"target_profile_summary": target_profile_summary,
|
||||
"semantic_brief_summary": brief_to_summary_dict(semantic_brief),
|
||||
"semantic_llm_applied": semantic_llm_applied,
|
||||
"query_intent_summary": first_intent_summary,
|
||||
"progression_graph_id": body.progression_graph_id,
|
||||
"retrieval_phase": "profile_v1+full_library+path_builder",
|
||||
"path_qa": path_qa,
|
||||
"retrieval_phase": "+".join(retrieval_parts),
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ProgressionPathSuggestRequest",
|
||||
"suggest_progression_path",
|
||||
"_pick_best_path_hit",
|
||||
"_pick_next_path_hit",
|
||||
]
|
||||
|
||||
# Legacy-Alias für Tests
|
||||
_pick_next_path_hit = _pick_best_path_hit
|
||||
Reference in new issue
Block a user