Update FastAPI application and related services for WP-25a: Enhance lifespan management with Mixture of Experts (MoE) integrity checks, improve logging and error handling in LLMService, and integrate profile-driven orchestration across components. Bump versions for main application, ingestion services, and LLM profiles to reflect new features and optimizations.

This commit is contained in:
Lars committed 2026-01-02 08:57:29 +01:00
1 parent 9a98093e70
commit 9b906bbabf
9 files changed
+408 -195

No files matched your search

+31 -58
View File
@@ -3,14 +3,13 @@ FILE: app/routers/chat.py
DESCRIPTION: Haupt-Chat-Interface (WP-25a Agentic Edition).
Kombiniert die spezialisierte Interview-Logik und Keyword-Erkennung
mit der neuen MoE-Orchestrierung und Pre-Synthesis Kompression.
VERSION: 3.0.3 (WP-25a: MoE & Compression Support - Full Release)
VERSION: 3.0.4 (WP-25a: Optimized MoE & Cascade Delegation)
STATUS: Active
FIX:
- 100% Wiederherstellung der v3.0.2 Logik (Interview Fallbacks, Schema-Resolution).
- WP-25a: Integration der Stream-Kompression (Module A) in den RAG-Workflow.
- WP-25a: Unterstützung der llm_profiles für spezialisierte Synthese (Module B).
- Erhalt der Ollama Context-Throttling Parameter (WP-20) als finaler Schutz.
- Beibehaltung der No-Retry Logik (max_retries=0) für Chat-Stabilität.
- WP-25a: Delegation der Fallback-Kaskade an den LLMService (v3.5.2).
- WP-25a: Nutzung der zentralisierten Stream-Kompression der DecisionEngine (v1.2.1).
- WP-25a: Konsistente Nutzung von MoE-Profilen für Interview- und RAG-Modus.
- 100% Erhalt der v3.0.2 Logik (Interview, Schema-Resolution, FastPaths).
"""
from fastapi import APIRouter, HTTPException, Depends
@@ -31,13 +30,13 @@ from app.services.feedback_service import log_search
router = APIRouter()
logger = logging.getLogger(__name__)
# --- EBENE 1: CONFIG LOADER & CACHING (Restauriert aus v3.0.2) ---
# --- EBENE 1: CONFIG LOADER & CACHING (WP-25 Standard) ---
_DECISION_CONFIG_CACHE = None
_TYPES_CONFIG_CACHE = None
def _load_decision_config() -> Dict[str, Any]:
"""Lädt die Strategie-Konfiguration (Kompatibilität zu WP-25)."""
"""Lädt die Strategie-Konfiguration."""
settings = get_settings()
path = Path(settings.DECISION_CONFIG_PATH)
try:
@@ -49,7 +48,7 @@ def _load_decision_config() -> Dict[str, Any]:
return {"strategies": {}}
def _load_types_config() -> Dict[str, Any]:
"""Lädt die types.yaml für die Typerkennung im Interview-Modus."""
"""Lädt die types.yaml für die Typerkennung."""
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
try:
if os.path.exists(path):
@@ -109,7 +108,7 @@ def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str
return "default"
def _is_question(query: str) -> bool:
"""Prüft, ob der Input eine Frage ist (W-Fragen Erkennung)."""
"""Prüft, ob der Input eine Frage ist."""
q = query.strip().lower()
if "?" in q: return True
starters = ["wer", "wie", "was", "wo", "wann", "warum", "weshalb", "wozu", "welche", "bist du"]
@@ -136,17 +135,18 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
if kw.lower() in query_lower:
return "INTERVIEW", "Keyword (Interview)"
# 3. SLOW PATH: DecisionEngine LLM Router
# 3. SLOW PATH: DecisionEngine LLM Router (MoE-gesteuert)
intent = await llm.decision_engine._determine_strategy(query)
return intent, "DecisionEngine (LLM)"
# --- EBENE 3: RETRIEVAL AGGREGATION ---
def _collect_all_hits(stream_responses: Dict[str, Any]) -> List[QueryHit]:
"""Sammelt und dedupliziert Treffer aus allen parallelen Streams."""
"""Sammelt deduplizierte Treffer aus allen Streams für das Tracing."""
all_hits = []
seen_node_ids = set()
for _, response in stream_responses.items():
# In v3.0.4 sammeln wir die hits aus den QueryResponse Objekten
if hasattr(response, 'results'):
for hit in response.results:
if hit.node_id not in seen_node_ids:
@@ -180,14 +180,14 @@ async def chat_endpoint(
sources_hits = []
answer_text = ""
# 2. INTERVIEW MODE (Kompatibilität zu v3.0.2)
# 2. INTERVIEW MODE (Bitgenaue WP-07 Logik)
if intent == "INTERVIEW":
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
types_cfg = get_types_config()
type_def = types_cfg.get("types", {}).get(target_type, {})
fields_list = type_def.get("schema", [])
# WP-07: RESTAURIERTE FALLBACK LOGIK (v3.0.2)
# WP-07: Restaurierte Fallback Logik
if not fields_list:
configured_schemas = strategy.get("schemas", {})
fallback = configured_schemas.get(target_type, configured_schemas.get("default", {}))
@@ -200,73 +200,46 @@ async def chat_endpoint(
.replace("{target_type}", target_type) \
.replace("{schema_fields}", fields_str)
# WP-25a: Nutzt spezialisiertes Kompressions-Profil für Interviews
# WP-25a: MoE Call (Kaskade erfolgt intern im LLMService)
answer_text = await llm.generate_raw_response(
final_prompt, system=llm.get_prompt("system_prompt"),
priority="realtime", profile_name="compression_fast", max_retries=0
)
sources_hits = []
# 3. RAG MODE (WP-25a Multi-Stream + Pre-Synthesis)
# 3. RAG MODE (Optimierte MoE Orchestrierung)
else:
# Phase A & B: Retrieval & Kompression (Delegation an Engine v1.2.1)
# Diese Methode gibt bereits die (evtl. komprimierten) Kontext-Strings zurück.
formatted_context_map = await engine._execute_parallel_streams(strategy, request.message)
# Erfassung der Quellen für das Tracing
raw_stream_map = {}
stream_keys = strategy.get("use_streams", [])
library = engine.config.get("streams_library", {})
# Phase A: Retrieval
tasks = []
retrieval_tasks = []
active_streams = []
for key in stream_keys:
stream_cfg = library.get(key)
if stream_cfg:
if key in library:
active_streams.append(key)
tasks.append(engine._run_single_stream(key, stream_cfg, request.message))
responses = await asyncio.gather(*tasks, return_exceptions=True)
retrieval_tasks.append(engine._run_single_stream(key, library[key], request.message))
raw_stream_map = {}
formatted_context_tasks = []
max_chars = getattr(settings, "MAX_OLLAMA_CHARS", 10000)
provider = strategy.get("preferred_provider") or settings.MINDNET_LLM_PROVIDER
# Phase B: Pre-Synthesis & Throttling
responses = await asyncio.gather(*retrieval_tasks, return_exceptions=True)
for name, res in zip(active_streams, responses):
if not isinstance(res, Exception):
raw_stream_map[name] = res
context_text = engine._format_stream_context(res)
# WP-25a: Automatisierte Kompression
stream_cfg = library.get(name, {})
threshold = stream_cfg.get("compression_threshold", 4000)
if len(context_text) > threshold:
profile = stream_cfg.get("compression_profile")
formatted_context_tasks.append(
engine._compress_stream_content(name, context_text, request.message, profile)
)
else:
# WP-20: Restaurierter Throttling-Schutz als Fallback
if provider == "ollama" and len(context_text) > max_chars:
context_text = context_text[:max_chars] + "\n[...]"
async def _ident(c=context_text): return c
formatted_context_tasks.append(_ident())
else:
async def _err(): return "[Stream Error]"
formatted_context_tasks.append(_err())
sources_hits = _collect_all_hits(raw_stream_map)
# Inhalte parallel finalisieren
final_contexts = await asyncio.gather(*formatted_context_tasks)
formatted_context_map = dict(zip(active_streams, final_contexts))
# Phase C: MoE Synthese
# Phase C: Finale MoE Synthese
answer_text = await engine._generate_final_answer(
intent, strategy, request.message, formatted_context_map
)
sources_hits = _collect_all_hits(raw_stream_map)
duration_ms = int((time.time() - start_time) * 1000)
# Logging
# Logging (WP-15)
try:
log_search(
query_id=query_id, query_text=request.message, results=sources_hits,
@@ -281,4 +254,4 @@ async def chat_endpoint(
except Exception as e:
logger.error(f"❌ Chat Endpoint Failure: {e}", exc_info=True)
raise HTTPException(status_code=500, detail="Fehler bei der Verarbeitung.")
raise HTTPException(status_code=500, detail="Fehler bei der Verarbeitung der Anfrage.")