From cc12dcf993331516ffd8401a82442810666fe1f5 Mon Sep 17 00:00:00 2001 From: Lars Date: Thu, 18 Dec 2025 16:59:37 +0100 Subject: [PATCH] retriever neu --- app/core/retriever.py | 115 ++++++++++++++++++++++++++++++------------ 1 file changed, 82 insertions(+), 33 deletions(-) diff --git a/app/core/retriever.py b/app/core/retriever.py index 1220c87..7db9472 100644 --- a/app/core/retriever.py +++ b/app/core/retriever.py @@ -3,7 +3,7 @@ FILE: app/core/retriever.py DESCRIPTION: Implementiert die Hybrid-Suche (Vektor + Graph-Expansion) und das Scoring-Modell (Explainability). WP-22 Update: Dynamic Edge Boosting, Lifecycle Scoring & Provenance Awareness. Enthält detaillierte Debug-Informationen für die mathematische Verifizierung. -VERSION: 0.6.10 (WP-22 Full, Debug & Stable) +VERSION: 0.6.11 (WP-22 Full, Debug & Stable) STATUS: Active DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.services.embeddings_client, app.core.graph_adapter LAST_ANALYSIS: 2025-12-18 @@ -46,7 +46,8 @@ logger = logging.getLogger(__name__) def _get_scoring_weights() -> Tuple[float, float, float]: """ Liefert die Basis-Gewichtung (semantic_weight, edge_weight, centrality_weight). - Prio: 1. retriever.yaml -> 2. Environment -> 3. Hardcoded Defaults + Priorität: 1. retriever.yaml -> 2. Environment/Settings -> 3. Hardcoded Defaults + """ settings = get_settings() sem = float(getattr(settings, "RETRIEVER_W_SEM", 1.0)) @@ -118,6 +119,7 @@ def _get_status_multiplier(payload: Dict[str, Any]) -> float: WP-22 A: Lifecycle-Scoring. - stable: 1.2 (Validiertes Wissen fördern) - draft: 0.5 (Entwürfe de-priorisieren) + """ status = str(payload.get("status", "active")).lower().strip() if status == "stable": @@ -137,6 +139,7 @@ def _compute_total_score( """ Die zentrale mathematische Scoring-Formel von WP-22. Score = (Similarity * StatusMult) * (1 + (Weight-1) + DynamicBoost) + """ _sem_w, edge_w_cfg, cent_w_cfg = _get_scoring_weights() status_mult = _get_status_multiplier(payload) @@ -156,8 +159,11 @@ def _compute_total_score( # 4. Final Merge total = base_val * (1.0 + (node_weight - 1.0) + dynamic_graph_impact) + # Floor-Schutz + final_score = max(0.001, float(total)) + return { - "total": max(0.001, float(total)), + "total": final_score, "edge_bonus": float(edge_bonus_raw), "cent_bonus": float(cent_bonus_raw), "status_multiplier": status_mult, @@ -168,6 +174,8 @@ def _compute_total_score( "cent_impact_final": cent_impact } + + # ============================================================================== # 3. EXPLANATION LAYER (DEBUG & VERIFIABILITY) # ============================================================================== @@ -180,7 +188,7 @@ def _build_explanation( target_note_id: Optional[str], applied_boosts: Optional[Dict[str, float]] = None ) -> Explanation: - """Erstellt ein detailliertes Explanation-Objekt mit WP-22 Metriken.""" + """Erstellt ein detailliertes Explanation-Objekt inkl. WP-22 Metriken.""" _, edge_w_cfg, cent_w_cfg = _get_scoring_weights() type_weight = float(payload.get("retriever_weight", 1.0)) @@ -189,7 +197,7 @@ def _build_explanation( note_type = payload.get("type", "unknown") base_val = scoring_debug["base_val"] - # 1. Score Breakdown + # 1. Score Breakdown Objekt breakdown = ScoreBreakdown( semantic_contribution=base_val, edge_contribution=base_val * scoring_debug["edge_impact_final"], @@ -205,7 +213,7 @@ def _build_explanation( reasons: List[Reason] = [] edges_dto: List[EdgeDTO] = [] - # 2. Reasons generieren + # 2. Gründe generieren if semantic_score > 0.70: reasons.append(Reason(kind="semantic", message="Textuelle Übereinstimmung.", score_impact=base_val)) @@ -217,7 +225,7 @@ def _build_explanation( txt = "Bonus" if status_mult > 1.0 else "Malus" reasons.append(Reason(kind="lifecycle", message=f"Status-{txt} ({payload.get('status')}).", score_impact=0.0)) - # 3. Kanten-Details (WP-22 B) + # 3. Kanten-Details (WP-22 B) - Beachtet eingehende UND ausgehende Kanten if subgraph and target_note_id and scoring_debug["edge_bonus"] > 0: raw_edges = [] if hasattr(subgraph, "get_incoming_edges"): @@ -226,7 +234,8 @@ def _build_explanation( raw_edges.extend(subgraph.get_outgoing_edges(target_note_id) or []) for edge in raw_edges: - src, tgt = edge.get("source"), edge.get("target") + src = edge.get("source") + tgt = edge.get("target") k = edge.get("kind", "edge") prov = edge.get("provenance", "rule") conf = float(edge.get("confidence", 1.0)) @@ -234,7 +243,7 @@ def _build_explanation( is_incoming = (tgt == target_note_id) direction = "in" if is_incoming else "out" - # neighbor_id Scope-Fix + # neighbor_id FIX: Variable sicher innerhalb der Schleife definieren neighbor_id = src if is_incoming else tgt edge_obj = EdgeDTO( @@ -244,18 +253,19 @@ def _build_explanation( ) edges_dto.append(edge_obj) + # Die 3 stärksten Signale als Gründe formulieren top_edges = sorted(edges_dto, key=lambda e: e.confidence, reverse=True) for e in top_edges[:3]: prov_txt = "Explizite" if e.provenance == "explicit" else "Heuristische" boost_txt = f" [Boost x{applied_boosts.get(e.kind)}]" if applied_boosts and e.kind in applied_boosts else "" - # Nachbar-ID innerhalb der Loop sicherstellen - target_name = e.source if e.direction == "in" else e.target - msg = f"{prov_txt} Kante '{e.kind}'{boost_txt} von/zu '{target_name}'." + # e.source/e.target sind durch e.direction eindeutig zugeordnet + peer_name = e.source if e.direction == "in" else e.target + msg = f"{prov_txt} Kante '{e.kind}'{boost_txt} von/zu '{peer_name}'." reasons.append(Reason(kind="edge", message=msg, score_impact=edge_w_cfg * e.confidence)) if scoring_debug["cent_bonus"] > 0.01: - reasons.append(Reason(kind="centrality", message="Knoten liegt zentral im Kontext.", score_impact=breakdown.centrality_contribution)) + reasons.append(Reason(kind="centrality", message="Knoten liegt zentral im aktuellen Kontext.", score_impact=breakdown.centrality_contribution)) return Explanation( breakdown=breakdown, @@ -266,13 +276,17 @@ def _build_explanation( def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]: - """Extrahiert Expansion-Tiefe und Kanten-Filter.""" + """Extrahiert Expansion-Tiefe und Kanten-Filter aus dem Request.""" expand = getattr(req, "expand", None) - if not expand: return 0, None + if not expand: + return 0, None + if isinstance(expand, dict): return int(expand.get("depth", 1)), expand.get("edge_types") + if hasattr(expand, "depth"): return int(getattr(expand, "depth", 1)), getattr(expand, "edge_types", None) + return 1, None @@ -284,26 +298,33 @@ def _build_hits_from_semantic( explain: bool = False, dynamic_edge_boosts: Dict[str, float] = None ) -> QueryResponse: - """Wandelt semantische Roh-Treffer in strukturierte QueryHits um.""" + """Wandelt semantische Roh-Treffer in strukturierte QueryHits um und berechnet WP-22 Scores.""" t0 = time.time() enriched = [] for pid, semantic_score, payload in hits: - edge_bonus, cent_bonus = 0.0, 0.0 + edge_bonus = 0.0 + cent_bonus = 0.0 target_note_id = payload.get("note_id") if subgraph is not None and target_note_id: try: edge_bonus = float(subgraph.edge_bonus(target_note_id)) cent_bonus = float(subgraph.centrality_bonus(target_note_id)) - except Exception: pass + except Exception: + pass + # Messbare Scoring-Daten berechnen debug_data = _compute_total_score( - semantic_score, payload, edge_bonus_raw=edge_bonus, - cent_bonus_raw=cent_bonus, dynamic_edge_boosts=dynamic_edge_boosts + semantic_score, + payload, + edge_bonus_raw=edge_bonus, + cent_bonus_raw=cent_bonus, + dynamic_edge_boosts=dynamic_edge_boosts ) enriched.append((pid, float(semantic_score), payload, debug_data)) + # Sortierung nach finalem Score enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True) limited_hits = enriched_sorted[: max(1, top_k)] @@ -313,24 +334,33 @@ def _build_hits_from_semantic( if explain: explanation_obj = _build_explanation( semantic_score=float(semantic_score), - payload=payload, scoring_debug=debug, - subgraph=subgraph, target_note_id=payload.get("note_id"), + payload=payload, + scoring_debug=debug, + subgraph=subgraph, + target_note_id=payload.get("note_id"), applied_boosts=dynamic_edge_boosts ) + text_content = payload.get("page_content") or payload.get("text") or payload.get("content") + results.append(QueryHit( - node_id=str(pid), + node_id=str(pid), note_id=payload.get("note_id", "unknown"), - semantic_score=float(semantic_score), + semantic_score=float(semantic_score), edge_bonus=debug["edge_bonus"], - centrality_bonus=debug["cent_bonus"], + centrality_bonus=debug["cent_bonus"], total_score=debug["total"], - source={"path": payload.get("path"), "text": payload.get("page_content") or payload.get("text")}, + source={ + "path": payload.get("path"), + "section": payload.get("section") or payload.get("section_title"), + "text": text_content + }, payload=payload, explanation=explanation_obj )) - return QueryResponse(results=results, used_mode=used_mode, latency_ms=int((time.time() - t0) * 1000)) + dt_ms = int((time.time() - t0) * 1000) + return QueryResponse(results=results, used_mode=used_mode, latency_ms=dt_ms) # ============================================================================== # 4. PUBLIC INTERFACE @@ -341,33 +371,52 @@ def hybrid_retrieve(req: QueryRequest) -> QueryResponse: client, prefix = _get_client_and_prefix() vector = list(req.query_vector) if req.query_vector else _get_query_vector(req) top_k = req.top_k or 10 + + # 1. Semantische Suche hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters) + # 2. Graph Expansion & Custom Weighting expand_depth, edge_types = _extract_expand_options(req) boost_edges = getattr(req, "boost_edges", {}) or {} subgraph: ga.Subgraph | None = None if expand_depth > 0 and hits: seed_ids = list({h[2].get("note_id") for h in hits if h[2].get("note_id")}) + if seed_ids: try: subgraph = ga.expand(client, prefix, seed_ids, depth=expand_depth, edge_types=edge_types) + + # WP-22: Transformation der Gewichte im RAM-Graphen vor Bonus-Berechnung if subgraph and hasattr(subgraph, "graph"): for u, v, data in subgraph.graph.edges(data=True): # Provenance Weighting (Concept 2.6) prov = data.get("provenance", "rule") prov_w = 1.0 if prov == "explicit" else (0.9 if prov == "smart" else 0.7) - # Intent Boost mapping + # Intent Boost Multiplikator k = data.get("kind") - intent_b = boost_edges.get(k, 1.0) - data["weight"] = data.get("weight", 1.0) * prov_w * intent_b - except Exception: subgraph = None + intent_multiplier = boost_edges.get(k, 1.0) + + # Finales Gewicht setzen + data["weight"] = data.get("weight", 1.0) * prov_w * intent_multiplier - return _build_hits_from_semantic(hits, top_k, "hybrid", subgraph, req.explain, boost_edges) + except Exception as e: + logger.error(f"Graph expansion failed: {e}") + subgraph = None + + # 3. Scoring & Result Generation + return _build_hits_from_semantic( + hits, + top_k, + "hybrid", + subgraph, + req.explain, + boost_edges + ) class Retriever: - """Asynchroner Wrapper für FastAPI-Integration.""" + """Wrapper-Klasse für FastAPI-Integration.""" async def search(self, request: QueryRequest) -> QueryResponse: return hybrid_retrieve(request) \ No newline at end of file