Hybrider Chat (mit und ohne LLM Einordung des Intents)

This commit is contained in:
Lars committed 2025-12-09 13:08:04 +01:00
1 parent 97985371ca
commit 03594424a1
4 files changed
+285 -139

No files matched your search

+68 -69
View File
@@ -1,10 +1,5 @@
"""
app/routers/chat.py — RAG Endpunkt (WP-06 Decision Engine - Full Config Refactor)
Zweck:
Verbindet Retrieval mit LLM-Generation.
WP-06: Implementiert Intent Detection und Strategic Retrieval.
Update: Konfiguration via decision_engine.yaml (Late Binding) mit 'Best Match' Logik.
app/routers/chat.py — RAG Endpunkt (WP-06 Hybrid Router)
"""
from fastapi import APIRouter, HTTPException, Depends
@@ -25,23 +20,15 @@ logger = logging.getLogger(__name__)
# --- Helper: Config Loader ---
# Cache für die Config (damit wir nicht bei jedem Request lesen)
_DECISION_CONFIG_CACHE = None
def _load_decision_config() -> Dict[str, Any]:
"""Lädt die Decision-Engine Konfiguration (Late Binding)."""
settings = get_settings()
path = Path(settings.DECISION_CONFIG_PATH)
# Default Fallback, falls YAML kaputt/weg
default_config = {
"strategies": {
"FACT": {"trigger_keywords": []},
"DECISION": {
"trigger_keywords": ["soll ich", "meinung"],
"inject_types": ["value", "principle"],
"prompt_template": "decision_template"
}
"FACT": {"trigger_keywords": []}
}
}
@@ -57,17 +44,14 @@ def _load_decision_config() -> Dict[str, Any]:
return default_config
def get_full_config() -> Dict[str, Any]:
"""Gibt die ganze Config zurück (für Intent Detection)."""
global _DECISION_CONFIG_CACHE
if _DECISION_CONFIG_CACHE is None:
_DECISION_CONFIG_CACHE = _load_decision_config()
return _DECISION_CONFIG_CACHE
def get_decision_strategy(intent: str) -> Dict[str, Any]:
"""Gibt die Strategie für einen spezifischen Intent zurück."""
config = get_full_config()
strategies = config.get("strategies", {})
# Fallback auf FACT, wenn Intent unbekannt
return strategies.get(intent, strategies.get("FACT", {}))
@@ -83,30 +67,17 @@ def get_retriever():
# --- Logic ---
def _build_enriched_context(hits: List[QueryHit]) -> str:
"""
Baut einen 'Rich Context' String.
Statt nur Text, injizieren wir Metadaten (Typ, Tags), damit das LLM
die semantische Rolle des Schnipsels versteht.
"""
context_parts = []
for i, hit in enumerate(hits, 1):
source = hit.source or {}
# 1. Content extrahieren
content = (
source.get("text") or
source.get("content") or
source.get("page_content") or
source.get("chunk_text") or
"[Kein Textinhalt verfügbar]"
source.get("text") or source.get("content") or
source.get("page_content") or source.get("chunk_text") or
"[Kein Text]"
)
# 2. Metadaten für "Context Intelligence"
title = hit.note_id or "Unbekannte Notiz"
title = hit.note_id or "Unbekannt"
note_type = source.get("type", "unknown").upper()
# 3. Formatierung
entry = (
f"### QUELLE {i}: {title}\n"
f"TYP: [{note_type}] (Score: {hit.total_score:.2f})\n"
@@ -118,38 +89,58 @@ def _build_enriched_context(hits: List[QueryHit]) -> str:
async def _classify_intent(query: str, llm: LLMService) -> str:
"""
WP-06: Intent Detection (Best Match / Longest Keyword Wins).
Prüft Keywords aus der YAML gegen die Query.
Wenn mehrere Strategien passen, gewinnt die mit dem längsten Keyword (Spezifität).
Hybrid Router:
1. Keyword Check (Best/Longest Match) -> FAST
2. LLM Fallback (wenn in config aktiv) -> SMART
"""
config = get_full_config()
strategies = config.get("strategies", {})
settings = config.get("settings", {})
query_lower = query.lower()
best_intent = "FACT"
best_intent = None
max_match_length = 0
# Iteriere über alle Strategien
# 1. FAST PATH: Keywords
for intent_name, strategy in strategies.items():
if intent_name == "FACT":
continue
if intent_name == "FACT": continue
keywords = strategy.get("trigger_keywords", [])
# Prüfe jedes Keyword
for k in keywords:
# Wenn Keyword im Text ist...
if k.lower() in query_lower:
# ... prüfen wir, ob es spezifischer (länger) ist als der bisherige Favorit
current_len = len(k)
if current_len > max_match_length:
max_match_length = current_len
if len(k) > max_match_length:
max_match_length = len(k)
best_intent = intent_name
# Wir brechen hier NICHT ab, sondern suchen weiter nach noch längeren Matches
if best_intent:
logger.info(f"Intent detected via KEYWORD: {best_intent}")
return best_intent
# 2. SLOW PATH: LLM Router
if settings.get("llm_fallback_enabled", False):
router_prompt_template = settings.get("llm_router_prompt", "")
if router_prompt_template:
prompt = router_prompt_template.replace("{query}", query)
logger.info("Keywords failed. Asking LLM for Intent...")
return best_intent
# Kurzer Raw Call
llm_decision = await llm.generate_raw_response(prompt)
# Cleaning
llm_decision = llm_decision.strip().upper()
if ":" in llm_decision:
llm_decision = llm_decision.split(":")[-1].strip()
# Validierung: Nur bekannte Intents zulassen
# Entferne Satzzeichen
llm_decision = ''.join(filter(str.isalnum, llm_decision))
if llm_decision in strategies:
logger.info(f"Intent detected via LLM: {llm_decision}")
return llm_decision
else:
logger.warning(f"LLM predicted unknown intent '{llm_decision}', falling back to FACT.")
return "FACT"
@router.post("/", response_model=ChatResponse)
async def chat_endpoint(
@@ -159,21 +150,20 @@ async def chat_endpoint(
):
start_time = time.time()
query_id = str(uuid.uuid4())
logger.info(f"Chat request [{query_id}]: {request.message[:50]}...")
try:
# 1. Intent Detection (Config-Driven & Best Match)
# 1. Intent Detection
intent = await _classify_intent(request.message, llm)
logger.info(f"[{query_id}] Detected Intent: {intent}")
logger.info(f"[{query_id}] Final Intent: {intent}")
# Lade Strategie aus Config (Late Binding)
# Strategy Load
strategy = get_decision_strategy(intent)
inject_types = strategy.get("inject_types", [])
prompt_key = strategy.get("prompt_template", "rag_template")
prepend_instr = strategy.get("prepend_instruction", "")
# 2. Primary Retrieval (Fakten)
# 2. Primary Retrieval
query_req = QueryRequest(
query=request.message,
mode="hybrid",
@@ -183,19 +173,19 @@ async def chat_endpoint(
retrieve_result = await retriever.search(query_req)
hits = retrieve_result.results
# 3. Strategic Retrieval (Konfigurierbar)
# 3. Strategic Retrieval
if inject_types:
logger.info(f"[{query_id}] Executing Strategic Retrieval for types: {inject_types}...")
strategy_req = QueryRequest(
query=request.message,
mode="hybrid",
top_k=3,
filters={"type": inject_types}, # Dynamische Liste aus YAML
filters={"type": inject_types},
explain=False
)
strategy_result = await retriever.search(strategy_req)
# Merge Results (Deduplication via node_id)
# Merge
existing_ids = {h.node_id for h in hits}
for strat_hit in strategy_result.results:
if strat_hit.node_id not in existing_ids:
@@ -207,20 +197,29 @@ async def chat_endpoint(
else:
context_str = _build_enriched_context(hits)
# 5. Generation Setup
# 5. Generation
# Wir laden das Template aus dem Service (da dort die prompts.yaml geladen ist)
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
system_prompt = llm.prompts.get("system_prompt", "")
# Injection der Instruktion (falls konfiguriert)
if prepend_instr:
context_str = f"{prepend_instr}\n\n{context_str}"
# Manuelles Bauen des finalen Prompts für volle Kontrolle
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
# Aufruf via Raw Response (da wir den Prompt schon fertig haben)
# Wir müssen den System-Prompt manuell mitgeben?
# generate_raw_response in llm_service unterstützt aktuell kein 'system'.
# -> Wir erweitern generate_raw_response oder nutzen einen Hack: System + Prompt.
# SAUBERER WEG: Wir bauen den Payload für Ollama hier manuell zusammen und rufen eine generische Methode.
# Da LLMService.generate_raw_response keine System-Msg nimmt, packen wir sie davor.
full_text_prompt = f"{system_prompt}\n\n{final_prompt}"
logger.info(f"[{query_id}] Sending to LLM (Intent: {intent}, Template: {prompt_key})...")
answer_text = await llm.generate_rag_response(
query=request.message,
context_str=context_str
)
answer_text = await llm.generate_raw_response(full_text_prompt)
# 6. Response
duration_ms = int((time.time() - start_time) * 1000)
return ChatResponse(