mindnet/app/core/retriever.py

397 lines
14 KiB
Python
Raw Normal View History

2025-12-08 10:39:35 +01:00
"""
2025-12-15 15:40:39 +01:00
FILE: app/core/retriever.py
DESCRIPTION: Implementiert die Hybrid-Suche (Vektor + Graph-Expansion) und das Scoring-Modell (Explainability).
2025-12-18 11:50:52 +01:00
WP-22 Update: Dynamic Edge Boosting & Lifecycle Scoring.
2025-12-18 14:00:08 +01:00
VERSION: 0.6.5 (WP-22 Scoring Formula)
2025-12-15 15:40:39 +01:00
STATUS: Active
DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.services.embeddings_client, app.core.graph_adapter
2025-12-18 11:50:52 +01:00
LAST_ANALYSIS: 2025-12-18
2025-12-08 10:39:35 +01:00
"""
2025-10-07 11:30:53 +02:00
from __future__ import annotations
2025-12-02 17:31:49 +01:00
2025-12-04 15:43:32 +01:00
import os
2025-10-07 11:30:53 +02:00
import time
2025-12-04 15:43:32 +01:00
from functools import lru_cache
2025-12-07 16:32:02 +01:00
from typing import Any, Dict, List, Tuple, Iterable, Optional
2025-10-07 11:30:53 +02:00
from app.config import get_settings
2025-12-07 16:32:02 +01:00
from app.models.dto import (
QueryRequest,
QueryResponse,
QueryHit,
Explanation,
ScoreBreakdown,
Reason,
EdgeDTO
)
2025-12-02 17:37:06 +01:00
import app.core.qdrant as qdr
import app.core.qdrant_points as qp
import app.services.embeddings_client as ec
2025-12-03 12:03:37 +01:00
import app.core.graph_adapter as ga
2025-10-07 11:30:53 +02:00
2025-12-04 15:43:32 +01:00
try:
import yaml # type: ignore[import]
2025-12-08 10:39:35 +01:00
except Exception: # pragma: no cover
2025-12-04 15:43:32 +01:00
yaml = None # type: ignore[assignment]
@lru_cache
def _get_scoring_weights() -> Tuple[float, float, float]:
2025-12-08 10:39:35 +01:00
"""Liefert (semantic_weight, edge_weight, centrality_weight) für den Retriever."""
2025-12-04 15:43:32 +01:00
settings = get_settings()
sem = float(getattr(settings, "RETRIEVER_W_SEM", 1.0))
edge = float(getattr(settings, "RETRIEVER_W_EDGE", 0.0))
cent = float(getattr(settings, "RETRIEVER_W_CENT", 0.0))
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
if yaml is None:
return sem, edge, cent
try:
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
scoring = data.get("scoring", {}) or {}
sem = float(scoring.get("semantic_weight", sem))
edge = float(scoring.get("edge_weight", edge))
cent = float(scoring.get("centrality_weight", cent))
except Exception:
return sem, edge, cent
return sem, edge, cent
2025-10-07 11:30:53 +02:00
2025-12-02 17:31:49 +01:00
def _get_client_and_prefix() -> Tuple[Any, str]:
2025-12-08 10:39:35 +01:00
"""Liefert (QdrantClient, prefix)."""
2025-12-02 17:37:06 +01:00
cfg = qdr.QdrantConfig.from_env()
client = qdr.get_client(cfg)
2025-12-02 17:31:49 +01:00
return client, cfg.prefix
def _get_query_vector(req: QueryRequest) -> List[float]:
2025-12-08 10:39:35 +01:00
"""Liefert den Query-Vektor aus dem Request."""
2025-12-04 15:43:32 +01:00
if req.query_vector:
return list(req.query_vector)
2025-12-02 17:31:49 +01:00
2025-12-04 15:43:32 +01:00
if not req.query:
raise ValueError("QueryRequest benötigt entweder query oder query_vector")
2025-10-07 11:30:53 +02:00
2025-12-04 15:43:32 +01:00
settings = get_settings()
model_name = settings.MODEL_NAME
2025-12-04 15:55:39 +01:00
try:
2025-12-08 10:39:35 +01:00
return ec.embed_text(req.query, model_name=model_name)
2025-12-04 15:55:39 +01:00
except TypeError:
2025-12-08 10:39:35 +01:00
return ec.embed_text(req.query)
2025-10-07 11:30:53 +02:00
2025-12-02 17:31:49 +01:00
def _semantic_hits(
client: Any,
prefix: str,
vector: List[float],
top_k: int,
2025-12-04 15:43:32 +01:00
filters: Dict[str, Any] | None = None,
) -> List[Tuple[str, float, Dict[str, Any]]]:
2025-12-08 10:39:35 +01:00
"""Führt eine semantische Suche aus."""
2025-12-02 17:31:49 +01:00
flt = filters or None
2025-12-04 15:55:39 +01:00
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=flt)
2025-12-04 15:43:32 +01:00
results: List[Tuple[str, float, Dict[str, Any]]] = []
2025-12-04 15:55:39 +01:00
for pid, score, payload in raw_hits:
results.append((str(pid), float(score), dict(payload or {})))
2025-12-04 15:43:32 +01:00
return results
2025-12-02 17:31:49 +01:00
2025-12-18 13:56:45 +01:00
# --- WP-22 Helper: Lifecycle Multipliers (Teil A) ---
2025-12-18 11:50:52 +01:00
def _get_status_multiplier(payload: Dict[str, Any]) -> float:
"""
2025-12-18 14:00:08 +01:00
WP-22: stable (1.2), active/default (1.0), draft (0.5).
2025-12-18 11:50:52 +01:00
"""
2025-12-18 13:56:45 +01:00
status = str(payload.get("status", "active")).lower()
2025-12-18 11:50:52 +01:00
if status == "stable": return 1.2
2025-12-18 13:56:45 +01:00
if status == "draft": return 0.5
2025-12-18 11:50:52 +01:00
return 1.0
2025-12-02 17:31:49 +01:00
2025-12-18 14:00:08 +01:00
# --- WP-22: Dynamic Scoring Formula (Teil C) ---
2025-12-03 12:03:37 +01:00
def _compute_total_score(
semantic_score: float,
payload: Dict[str, Any],
2025-12-18 14:00:08 +01:00
edge_bonus_raw: float = 0.0,
cent_bonus_raw: float = 0.0,
2025-12-18 11:50:52 +01:00
dynamic_edge_boosts: Dict[str, float] = None
2025-12-03 12:03:37 +01:00
) -> Tuple[float, float, float]:
2025-12-18 11:50:52 +01:00
"""
2025-12-18 14:00:08 +01:00
WP-22 Mathematische Logik:
Score = BaseScore * (1 + ConfigWeight + DynamicBoost)
Hierbei gilt:
- BaseScore: semantic_similarity * status_multiplier
- ConfigWeight: retriever_weight (Type Boost)
- DynamicBoost: (edge_weight * edge_bonus) + (centrality_weight * centrality_bonus)
2025-12-18 11:50:52 +01:00
"""
2025-12-18 14:00:08 +01:00
# 1. Base Score (Semantik * Lifecycle)
2025-12-18 11:50:52 +01:00
status_mult = _get_status_multiplier(payload)
2025-12-18 14:00:08 +01:00
base_score = float(semantic_score) * status_mult
# 2. Config Weight (Static Type Boost)
config_weight = float(payload.get("retriever_weight", 1.0)) - 1.0 # 1.0 ist neutral
# 3. Dynamic Boost (Graph-Signale)
_sem_w, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
dynamic_boost = (edge_w_cfg * edge_bonus_raw) + (cent_w_cfg * cent_bonus_raw)
# Falls Intent-Boosts vorliegen, verstärken wir den Dynamic Boost
if dynamic_edge_boosts and (edge_bonus_raw > 0 or cent_bonus_raw > 0):
dynamic_boost *= 1.5
total = base_score * (1.0 + config_weight + dynamic_boost)
return float(total), float(edge_bonus_raw), float(cent_bonus_raw)
2025-12-03 12:03:37 +01:00
2025-12-07 16:32:02 +01:00
# --- WP-04b Explanation Logic ---
2025-12-03 12:03:37 +01:00
2025-12-07 16:32:02 +01:00
def _build_explanation(
semantic_score: float,
payload: Dict[str, Any],
edge_bonus: float,
cent_bonus: float,
subgraph: Optional[ga.Subgraph],
node_key: Optional[str]
) -> Explanation:
2025-12-18 13:56:45 +01:00
"""Erstellt ein Explanation-Objekt (WP-04b)."""
2025-12-09 18:11:25 +01:00
_, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
2025-12-07 16:32:02 +01:00
2025-12-18 14:00:08 +01:00
type_weight = float(payload.get("retriever_weight", 1.0))
2025-12-18 11:50:52 +01:00
status_mult = _get_status_multiplier(payload)
2025-12-07 16:32:02 +01:00
note_type = payload.get("type", "unknown")
2025-12-18 14:00:08 +01:00
# Breakdown für Explanation (Muss die Scoring Formel spiegeln)
config_w_impact = type_weight - 1.0
dynamic_b_impact = (edge_w_cfg * edge_bonus) + (cent_w_cfg * cent_bonus)
base_val = semantic_score * status_mult
2025-12-07 16:32:02 +01:00
breakdown = ScoreBreakdown(
2025-12-18 14:00:08 +01:00
semantic_contribution=base_val,
edge_contribution=base_val * dynamic_b_impact,
centrality_contribution=0.0, # In dynamic_b_impact enthalten
2025-12-07 16:32:02 +01:00
raw_semantic=semantic_score,
raw_edge_bonus=edge_bonus,
raw_centrality=cent_bonus,
node_weight=type_weight
)
reasons: List[Reason] = []
edges_dto: List[EdgeDTO] = []
if semantic_score > 0.85:
2025-12-08 10:39:35 +01:00
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
2025-12-07 16:57:01 +01:00
elif semantic_score > 0.70:
2025-12-08 10:39:35 +01:00
reasons.append(Reason(kind="semantic", message="Gute textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
2025-12-07 16:32:02 +01:00
2025-12-07 16:57:01 +01:00
if type_weight != 1.0:
msg = "Bevorzugt" if type_weight > 1.0 else "Leicht abgewertet"
2025-12-18 14:00:08 +01:00
reasons.append(Reason(kind="type", message=f"{msg} aufgrund des Typs '{note_type}'.", score_impact=base_val * config_w_impact))
2025-12-07 16:32:02 +01:00
2025-12-18 11:50:52 +01:00
if status_mult != 1.0:
msg = "Status-Bonus" if status_mult > 1.0 else "Status-Malus"
2025-12-18 13:56:45 +01:00
reasons.append(Reason(kind="lifecycle", message=f"{msg} ({payload.get('status', 'unknown')}).", score_impact=0.0))
2025-12-18 11:50:52 +01:00
2025-12-07 16:32:02 +01:00
if subgraph and node_key and edge_bonus > 0:
2025-12-07 16:57:01 +01:00
if hasattr(subgraph, "get_outgoing_edges"):
outgoing = subgraph.get_outgoing_edges(node_key)
for edge in outgoing:
target = edge.get("target", "Unknown")
kind = edge.get("kind", "edge")
weight = edge.get("weight", 0.0)
if weight > 0.05:
2025-12-08 10:39:35 +01:00
edges_dto.append(EdgeDTO(id=f"{node_key}->{target}:{kind}", kind=kind, source=node_key, target=target, weight=weight, direction="out"))
2025-12-07 16:57:01 +01:00
2025-12-07 16:32:02 +01:00
if hasattr(subgraph, "get_incoming_edges"):
incoming = subgraph.get_incoming_edges(node_key)
2025-12-07 16:57:01 +01:00
for edge in incoming:
2025-12-07 16:32:02 +01:00
src = edge.get("source", "Unknown")
kind = edge.get("kind", "edge")
weight = edge.get("weight", 0.0)
2025-12-07 16:57:01 +01:00
if weight > 0.05:
2025-12-08 10:39:35 +01:00
edges_dto.append(EdgeDTO(id=f"{src}->{node_key}:{kind}", kind=kind, source=src, target=node_key, weight=weight, direction="in"))
2025-12-07 16:57:01 +01:00
all_edges = sorted(edges_dto, key=lambda e: e.weight, reverse=True)
for top_edge in all_edges[:3]:
2025-12-09 18:11:25 +01:00
impact = edge_w_cfg * top_edge.weight
2025-12-08 10:39:35 +01:00
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
2025-12-07 16:57:01 +01:00
if cent_bonus > 0.01:
2025-12-18 14:00:08 +01:00
reasons.append(Reason(kind="centrality", message="Knoten liegt zentral im Kontext.", score_impact=cent_w_cfg * cent_bonus))
2025-12-07 16:32:02 +01:00
2025-12-08 10:39:35 +01:00
return Explanation(breakdown=breakdown, reasons=reasons, related_edges=edges_dto if edges_dto else None)
2025-12-07 16:32:02 +01:00
def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]:
2025-12-18 14:00:08 +01:00
"""Extrahiert depth und edge_types für die Expansion."""
2025-12-03 12:03:37 +01:00
expand = getattr(req, "expand", None)
if not expand:
return 0, None
depth = 1
2025-12-04 15:55:39 +01:00
edge_types: List[str] | None = None
2025-12-03 12:03:37 +01:00
if hasattr(expand, "depth") or hasattr(expand, "edge_types"):
2025-12-04 15:43:32 +01:00
depth = int(getattr(expand, "depth", 1) or 1)
types_val = getattr(expand, "edge_types", None)
if types_val:
edge_types = list(types_val)
return depth, edge_types
if isinstance(expand, dict):
if "depth" in expand:
depth = int(expand.get("depth") or 1)
if "edge_types" in expand and expand["edge_types"] is not None:
edge_types = list(expand["edge_types"])
return depth, edge_types
return 0, None
2025-12-03 10:39:11 +01:00
2025-12-02 17:31:49 +01:00
def _build_hits_from_semantic(
2025-12-04 15:43:32 +01:00
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
2025-12-02 17:31:49 +01:00
top_k: int,
used_mode: str,
2025-12-04 15:43:32 +01:00
subgraph: ga.Subgraph | None = None,
2025-12-08 10:39:35 +01:00
explain: bool = False,
2025-12-18 11:50:52 +01:00
dynamic_edge_boosts: Dict[str, float] = None
2025-12-02 17:31:49 +01:00
) -> QueryResponse:
2025-12-18 14:00:08 +01:00
"""Baut strukturierte QueryHits basierend auf Hybrid-Scoring."""
2025-12-02 17:31:49 +01:00
t0 = time.time()
2025-12-03 10:39:11 +01:00
enriched: List[Tuple[str, float, Dict[str, Any], float, float, float]] = []
2025-12-04 15:43:32 +01:00
2025-12-03 10:39:11 +01:00
for pid, semantic_score, payload in hits:
2025-12-03 12:03:37 +01:00
edge_bonus = 0.0
cent_bonus = 0.0
2025-12-07 16:32:02 +01:00
node_key = payload.get("chunk_id") or payload.get("note_id")
if subgraph is not None and node_key:
try:
edge_bonus = float(subgraph.edge_bonus(node_key))
except Exception:
edge_bonus = 0.0
try:
cent_bonus = float(subgraph.centrality_bonus(node_key))
except Exception:
cent_bonus = 0.0
2025-12-03 12:03:37 +01:00
2025-12-18 14:00:08 +01:00
total, eb, cb = _compute_total_score(
2025-12-18 11:50:52 +01:00
semantic_score,
payload,
2025-12-18 14:00:08 +01:00
edge_bonus_raw=edge_bonus,
cent_bonus_raw=cent_bonus,
2025-12-18 11:50:52 +01:00
dynamic_edge_boosts=dynamic_edge_boosts
)
2025-12-18 14:00:08 +01:00
enriched.append((pid, float(semantic_score), payload, total, eb, cb))
2025-12-03 10:39:11 +01:00
enriched_sorted = sorted(enriched, key=lambda h: h[3], reverse=True)
limited = enriched_sorted[: max(1, top_k)]
2025-10-07 11:30:53 +02:00
results: List[QueryHit] = []
2025-12-18 14:00:08 +01:00
for pid, semantic_score, payload, total, eb, cb in limited:
2025-12-07 16:32:02 +01:00
explanation_obj = None
if explain:
explanation_obj = _build_explanation(
semantic_score=float(semantic_score),
payload=payload,
2025-12-18 14:00:08 +01:00
edge_bonus=eb,
cent_bonus=cb,
2025-12-07 16:32:02 +01:00
subgraph=subgraph,
2025-12-08 10:39:35 +01:00
node_key=payload.get("chunk_id") or payload.get("note_id")
2025-12-07 16:32:02 +01:00
)
2025-12-02 17:31:49 +01:00
2025-12-08 11:06:29 +01:00
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
2025-12-08 10:39:35 +01:00
results.append(QueryHit(
node_id=str(pid),
2025-12-18 13:56:45 +01:00
note_id=payload.get("note_id", "unknown"),
2025-12-08 10:39:35 +01:00
semantic_score=float(semantic_score),
2025-12-18 14:00:08 +01:00
edge_bonus=eb,
centrality_bonus=cb,
2025-12-08 10:39:35 +01:00
total_score=total,
paths=None,
2025-12-08 11:06:29 +01:00
source={
"path": payload.get("path"),
"section": payload.get("section") or payload.get("section_title"),
2025-12-09 18:11:25 +01:00
"text": text_content
2025-12-08 11:06:29 +01:00
},
2025-12-09 18:11:25 +01:00
payload=payload,
2025-12-08 10:39:35 +01:00
explanation=explanation_obj
))
2025-12-02 17:31:49 +01:00
2025-10-07 11:30:53 +02:00
dt = int((time.time() - t0) * 1000)
2025-12-02 17:31:49 +01:00
return QueryResponse(results=results, used_mode=used_mode, latency_ms=dt)
2025-10-07 11:30:53 +02:00
2025-12-02 17:31:49 +01:00
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
2025-12-18 13:56:45 +01:00
"""Reiner semantischer Retriever (WP-02)."""
2025-12-02 17:31:49 +01:00
client, prefix = _get_client_and_prefix()
2025-12-04 15:43:32 +01:00
vector = _get_query_vector(req)
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
2025-12-02 17:31:49 +01:00
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
2025-12-08 10:39:35 +01:00
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="semantic", subgraph=None, explain=req.explain)
2025-10-07 11:30:53 +02:00
2025-12-02 17:31:49 +01:00
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
2025-12-18 13:56:45 +01:00
"""Hybrid-Retriever: semantische Suche + optionale Edge-Expansion (WP-04a)."""
2025-12-02 17:31:49 +01:00
client, prefix = _get_client_and_prefix()
2025-12-18 13:21:53 +01:00
if req.query_vector:
vector = list(req.query_vector)
else:
vector = _get_query_vector(req)
2025-12-04 15:43:32 +01:00
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
2025-12-02 17:31:49 +01:00
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
2025-12-03 12:03:37 +01:00
depth, edge_types = _extract_expand_options(req)
2025-12-18 13:21:53 +01:00
2025-12-18 14:00:08 +01:00
# WP-22: Dynamic Boosts aus dem Request (vom Router)
2025-12-18 11:50:52 +01:00
boost_edges = getattr(req, "boost_edges", {})
2025-12-04 15:43:32 +01:00
subgraph: ga.Subgraph | None = None
if depth and depth > 0:
2025-12-03 12:03:37 +01:00
seed_ids: List[str] = []
2025-12-04 15:55:39 +01:00
for _pid, _score, payload in hits:
2025-12-18 13:56:45 +01:00
key = payload.get("note_id")
2025-12-03 12:03:37 +01:00
if key and key not in seed_ids:
seed_ids.append(key)
if seed_ids:
try:
2025-12-18 13:56:45 +01:00
# Subgraph laden
2025-12-03 12:03:37 +01:00
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=edge_types)
2025-12-18 11:50:52 +01:00
2025-12-18 13:56:45 +01:00
# --- WP-22: Kanten-Boosts im RAM-Graphen anwenden ---
# Dies manipuliert die Gewichte im Graphen, bevor der 'edge_bonus' berechnet wird.
2025-12-18 11:50:52 +01:00
if boost_edges and subgraph and hasattr(subgraph, "graph"):
for u, v, data in subgraph.graph.edges(data=True):
k = data.get("kind")
if k in boost_edges:
2025-12-18 13:56:45 +01:00
# Gewicht multiplizieren (z.B. caused_by * 3.0)
2025-12-18 11:50:52 +01:00
data["weight"] = data.get("weight", 1.0) * boost_edges[k]
2025-12-03 12:03:37 +01:00
except Exception:
subgraph = None
2025-12-18 11:50:52 +01:00
return _build_hits_from_semantic(
hits,
top_k=top_k,
used_mode="hybrid",
subgraph=subgraph,
explain=req.explain,
dynamic_edge_boosts=boost_edges
)
2025-12-08 10:39:35 +01:00
class Retriever:
2025-12-18 13:21:53 +01:00
"""
2025-12-18 13:56:45 +01:00
Wrapper-Klasse für Suchoperationen.
2025-12-18 13:21:53 +01:00
"""
def __init__(self):
pass
2025-12-08 10:39:35 +01:00
async def search(self, request: QueryRequest) -> QueryResponse:
return hybrid_retrieve(request)