2025-10-07 11:30:53 +02:00
|
|
|
|
from __future__ import annotations
|
2025-12-02 17:31:49 +01:00
|
|
|
|
|
2025-10-07 11:30:53 +02:00
|
|
|
|
import time
|
2025-12-03 12:03:37 +01:00
|
|
|
|
from typing import Any, Dict, List, Tuple, Iterable
|
2025-10-07 11:30:53 +02:00
|
|
|
|
|
|
|
|
|
|
from app.config import get_settings
|
2025-12-02 17:31:49 +01:00
|
|
|
|
from app.models.dto import QueryRequest, QueryResponse, QueryHit
|
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-02 17:31:49 +01:00
|
|
|
|
def _get_client_and_prefix() -> Tuple[Any, str]:
|
2025-12-03 12:03:37 +01:00
|
|
|
|
"""Liefert (QdrantClient, prefix) basierend auf QdrantConfig.from_env()."""
|
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-03 12:03:37 +01:00
|
|
|
|
"""
|
|
|
|
|
|
Liefert den Query-Vektor aus dem Request.
|
|
|
|
|
|
|
|
|
|
|
|
- Falls req.query_vector gesetzt ist, wird dieser unverändert genutzt.
|
|
|
|
|
|
- Falls req.query (Text) gesetzt ist, wird ec.embed_text(req.query) aufgerufen.
|
|
|
|
|
|
- Andernfalls: ValueError.
|
|
|
|
|
|
"""
|
2025-12-02 17:31:49 +01:00
|
|
|
|
if req.query_vector is not None:
|
|
|
|
|
|
if not isinstance(req.query_vector, list):
|
|
|
|
|
|
raise ValueError("query_vector muss eine Liste von floats sein")
|
2025-10-07 13:34:53 +02:00
|
|
|
|
return req.query_vector
|
2025-12-02 17:31:49 +01:00
|
|
|
|
|
2025-10-07 13:34:53 +02:00
|
|
|
|
if req.query:
|
2025-12-02 17:37:06 +01:00
|
|
|
|
return ec.embed_text(req.query)
|
2025-10-07 11:30:53 +02:00
|
|
|
|
|
2025-12-02 17:31:49 +01:00
|
|
|
|
raise ValueError("Weder query_vector noch query gesetzt – mindestens eines ist erforderlich")
|
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,
|
|
|
|
|
|
filters: Dict | None,
|
2025-12-02 17:37:06 +01:00
|
|
|
|
):
|
2025-12-03 12:03:37 +01:00
|
|
|
|
"""Kapselt den Aufruf von qp.search_chunks_by_vector."""
|
2025-12-02 17:31:49 +01:00
|
|
|
|
flt = filters or None
|
2025-12-02 17:37:06 +01:00
|
|
|
|
hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=flt)
|
2025-12-02 17:31:49 +01:00
|
|
|
|
return hits
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-12-03 10:39:11 +01:00
|
|
|
|
def _resolve_top_k(req: QueryRequest) -> int:
|
2025-12-03 12:03:37 +01:00
|
|
|
|
"""Ermittelt ein sinnvolles top_k."""
|
2025-12-03 10:39:11 +01:00
|
|
|
|
if isinstance(req.top_k, int) and req.top_k > 0:
|
|
|
|
|
|
return req.top_k
|
|
|
|
|
|
s = get_settings()
|
|
|
|
|
|
return max(1, int(getattr(s, "RETRIEVER_TOP_K", 10)))
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-12-03 12:03:37 +01:00
|
|
|
|
def _compute_total_score(
|
|
|
|
|
|
semantic_score: float,
|
|
|
|
|
|
payload: Dict[str, Any],
|
|
|
|
|
|
edge_bonus: float = 0.0,
|
|
|
|
|
|
cent_bonus: float = 0.0,
|
|
|
|
|
|
) -> Tuple[float, float, float]:
|
|
|
|
|
|
"""Berechnet total_score auf Basis von semantic_score, retriever_weight und Graph-Boni.
|
2025-12-03 10:39:11 +01:00
|
|
|
|
|
2025-12-03 12:03:37 +01:00
|
|
|
|
Aktuelle Formel (Step 3):
|
|
|
|
|
|
total_score = semantic_score * max(retriever_weight, 0.0) + edge_bonus + cent_bonus
|
2025-12-03 10:39:11 +01:00
|
|
|
|
|
|
|
|
|
|
retriever_weight stammt aus dem Chunk-Payload und ist bereits aus types.yaml
|
2025-12-03 12:03:37 +01:00
|
|
|
|
abgeleitet. Falls nicht gesetzt oder nicht interpretierbar, wird 1.0 angenommen.
|
2025-12-03 10:39:11 +01:00
|
|
|
|
"""
|
|
|
|
|
|
raw_weight = payload.get("retriever_weight", 1.0)
|
|
|
|
|
|
try:
|
|
|
|
|
|
weight = float(raw_weight)
|
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
|
weight = 1.0
|
|
|
|
|
|
if weight < 0.0:
|
|
|
|
|
|
weight = 0.0
|
|
|
|
|
|
|
|
|
|
|
|
total = float(semantic_score) * weight + edge_bonus + cent_bonus
|
2025-12-03 12:03:37 +01:00
|
|
|
|
return total, float(edge_bonus), float(cent_bonus)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]:
|
|
|
|
|
|
"""Extrahiert depth und edge_types aus req.expand, falls vorhanden.
|
|
|
|
|
|
|
|
|
|
|
|
- Falls expand nicht gesetzt ist: depth=0, edge_types=None (keine Expansion).
|
|
|
|
|
|
- Unterstützt sowohl Pydantic-Modelle als auch plain dicts.
|
|
|
|
|
|
"""
|
|
|
|
|
|
expand = getattr(req, "expand", None)
|
|
|
|
|
|
if not expand:
|
|
|
|
|
|
return 0, None
|
|
|
|
|
|
|
|
|
|
|
|
depth = 1
|
|
|
|
|
|
edge_types = None
|
|
|
|
|
|
|
|
|
|
|
|
# Pydantic-Modell oder Objekt mit Attributen
|
|
|
|
|
|
if hasattr(expand, "depth") or hasattr(expand, "edge_types"):
|
|
|
|
|
|
try:
|
|
|
|
|
|
depth_val = getattr(expand, "depth", 1) or 1
|
|
|
|
|
|
depth = int(depth_val)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
depth = 1
|
|
|
|
|
|
edge_types = getattr(expand, "edge_types", None)
|
|
|
|
|
|
# plain dict aus FastAPI/Pydantic
|
|
|
|
|
|
elif isinstance(expand, dict):
|
|
|
|
|
|
try:
|
|
|
|
|
|
depth_val = expand.get("depth", 1) or 1
|
|
|
|
|
|
depth = int(depth_val)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
depth = 1
|
|
|
|
|
|
edge_types = expand.get("edge_types")
|
|
|
|
|
|
|
|
|
|
|
|
if depth < 0:
|
|
|
|
|
|
depth = 0
|
|
|
|
|
|
|
|
|
|
|
|
if edge_types is not None and not isinstance(edge_types, list):
|
|
|
|
|
|
try:
|
|
|
|
|
|
edge_types = list(edge_types)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
edge_types = None
|
|
|
|
|
|
|
|
|
|
|
|
return depth, edge_types
|
2025-12-03 10:39:11 +01:00
|
|
|
|
|
|
|
|
|
|
|
2025-12-02 17:31:49 +01:00
|
|
|
|
def _build_hits_from_semantic(
|
|
|
|
|
|
hits: List[Tuple[str, float, Dict[str, Any]]],
|
|
|
|
|
|
top_k: int,
|
|
|
|
|
|
used_mode: str,
|
2025-12-03 12:03:37 +01:00
|
|
|
|
subgraph: Any | None = None,
|
2025-12-02 17:31:49 +01:00
|
|
|
|
) -> QueryResponse:
|
2025-12-03 10:39:11 +01:00
|
|
|
|
"""Formt rohe Treffer in QueryResponse um und wendet das Scoring an."""
|
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]] = []
|
|
|
|
|
|
for pid, semantic_score, payload in hits:
|
2025-12-03 12:03:37 +01:00
|
|
|
|
# Graph-Scores, falls Subgraph und stabiler Key vorhanden
|
|
|
|
|
|
edge_bonus = 0.0
|
|
|
|
|
|
cent_bonus = 0.0
|
|
|
|
|
|
if subgraph is not None:
|
|
|
|
|
|
node_key = payload.get("chunk_id") or payload.get("note_id")
|
|
|
|
|
|
if 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
|
|
|
|
|
|
|
|
|
|
|
|
total, edge_bonus, cent_bonus = _compute_total_score(
|
|
|
|
|
|
semantic_score,
|
|
|
|
|
|
payload,
|
|
|
|
|
|
edge_bonus=edge_bonus,
|
|
|
|
|
|
cent_bonus=cent_bonus,
|
|
|
|
|
|
)
|
2025-12-03 10:39:11 +01:00
|
|
|
|
enriched.append((pid, float(semantic_score), payload, total, edge_bonus, cent_bonus))
|
|
|
|
|
|
|
|
|
|
|
|
# Sortierung nach total_score absteigend
|
|
|
|
|
|
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-03 10:39:11 +01:00
|
|
|
|
for pid, semantic_score, payload, total, edge_bonus, cent_bonus in limited:
|
2025-12-02 17:31:49 +01:00
|
|
|
|
note_id = payload.get("note_id")
|
|
|
|
|
|
path = payload.get("path")
|
|
|
|
|
|
section = payload.get("section_title")
|
|
|
|
|
|
|
|
|
|
|
|
results.append(
|
|
|
|
|
|
QueryHit(
|
|
|
|
|
|
node_id=str(pid),
|
|
|
|
|
|
note_id=note_id,
|
|
|
|
|
|
semantic_score=float(semantic_score),
|
|
|
|
|
|
edge_bonus=edge_bonus,
|
|
|
|
|
|
centrality_bonus=cent_bonus,
|
|
|
|
|
|
total_score=total,
|
2025-12-03 10:39:11 +01:00
|
|
|
|
paths=None,
|
|
|
|
|
|
source={
|
|
|
|
|
|
"path": path,
|
|
|
|
|
|
"section": section,
|
|
|
|
|
|
},
|
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-03 12:03:37 +01:00
|
|
|
|
"""Reiner semantischer Retriever (ohne Edge-Expansion)."""
|
2025-12-02 17:31:49 +01:00
|
|
|
|
top_k = _resolve_top_k(req)
|
|
|
|
|
|
vector = _get_query_vector(req)
|
|
|
|
|
|
client, prefix = _get_client_and_prefix()
|
|
|
|
|
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
2025-12-03 12:03:37 +01:00
|
|
|
|
# semantic mode: keine Edge-Expansion
|
|
|
|
|
|
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="semantic", subgraph=None)
|
2025-10-07 11:30:53 +02:00
|
|
|
|
|
|
|
|
|
|
|
2025-12-02 17:31:49 +01:00
|
|
|
|
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
2025-12-03 12:03:37 +01:00
|
|
|
|
"""Hybrid-Retriever mit optionaler Edge-Expansion.
|
|
|
|
|
|
|
|
|
|
|
|
Schritt 3:
|
|
|
|
|
|
- Basis sind die semantischen Chunk-Treffer (wie im Semantic-Modus)
|
|
|
|
|
|
- Zusätzlich wird, falls req.expand gesetzt ist und depth > 0,
|
|
|
|
|
|
ein lokaler Subgraph über ga.expand aufgebaut und zur Score-Berechnung verwendet.
|
|
|
|
|
|
"""
|
2025-12-02 17:31:49 +01:00
|
|
|
|
top_k = _resolve_top_k(req)
|
|
|
|
|
|
vector = _get_query_vector(req)
|
|
|
|
|
|
client, prefix = _get_client_and_prefix()
|
|
|
|
|
|
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)
|
|
|
|
|
|
subgraph = None
|
|
|
|
|
|
if depth > 0:
|
|
|
|
|
|
# Seeds: stabile IDs aus dem Payload (chunk_id bevorzugt, sonst note_id)
|
|
|
|
|
|
seed_ids: List[str] = []
|
|
|
|
|
|
for _, _score, payload in hits:
|
|
|
|
|
|
key = payload.get("chunk_id") or payload.get("note_id")
|
|
|
|
|
|
if key and key not in seed_ids:
|
|
|
|
|
|
seed_ids.append(key)
|
|
|
|
|
|
|
|
|
|
|
|
if seed_ids:
|
|
|
|
|
|
try:
|
|
|
|
|
|
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=edge_types)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
# Edge-Expansion ist optional: bei Fehlern weiter ohne Graph-Boni
|
|
|
|
|
|
subgraph = None
|
|
|
|
|
|
|
|
|
|
|
|
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="hybrid", subgraph=subgraph)
|