Update Decision Engine and related components for WP-25a: Bump version to 1.2.0, enhance multi-stream retrieval with pre-synthesis compression, and integrate Mixture of Experts (MoE) profile support. Refactor chat interface to utilize new compression logic and llm_profiles for improved synthesis. Maintain compatibility with existing methods and ensure robust error handling across services.

This commit is contained in:
Lars committed 2026-01-02 07:04:43 +01:00
1 parent 3d2f3d12d9
commit d0eae8e43c
5 files changed
+299 -200

No files matched your search

+44 -26
View File
@@ -1,14 +1,15 @@
"""
FILE: app/routers/chat.py
DESCRIPTION: Haupt-Chat-Interface (WP-25 Agentic Edition).
DESCRIPTION: Haupt-Chat-Interface (WP-25a Agentic Edition).
Kombiniert die spezialisierte Interview-Logik und Keyword-Erkennung
mit der neuen Multi-Stream Orchestrierung der DecisionEngine.
VERSION: 3.0.2
mit der neuen MoE-Orchestrierung und Pre-Synthesis Kompression.
VERSION: 3.0.3 (WP-25a: MoE & Compression Support - Full Release)
STATUS: Active
FIX:
- 100% Wiederherstellung der v2.7.8 Logik (Interview, Schema-Resolution, Keywords).
- Integration der DecisionEngine für paralleles RAG-Retrieval.
- Erhalt der Ollama Context-Throttling Parameter (WP-20).
- 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.
"""
@@ -19,6 +20,7 @@ import uuid
import logging
import yaml
import os
import asyncio
from pathlib import Path
from app.config import get_settings
@@ -29,7 +31,7 @@ from app.services.feedback_service import log_search
router = APIRouter()
logger = logging.getLogger(__name__)
# --- EBENE 1: CONFIG LOADER & CACHING (Restauriert aus v2.7.8) ---
# --- EBENE 1: CONFIG LOADER & CACHING (Restauriert aus v3.0.2) ---
_DECISION_CONFIG_CACHE = None
_TYPES_CONFIG_CACHE = None
@@ -77,10 +79,7 @@ def get_decision_strategy(intent: str) -> Dict[str, Any]:
# --- EBENE 2: SPEZIAL-LOGIK (INTERVIEW & DETECTION) ---
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
"""
WP-07: Identifiziert den gewünschten Notiz-Typ (Keyword-basiert).
100% identisch mit v2.7.8 zur Sicherstellung des Interview-Workflows.
"""
"""WP-07: Identifiziert den gewünschten Notiz-Typ (Keyword-basiert)."""
message_lower = message.lower()
types_cfg = get_types_config()
types_def = types_cfg.get("types", {})
@@ -117,10 +116,7 @@ def _is_question(query: str) -> bool:
return any(q.startswith(s + " ") for s in starters)
async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
"""
WP-25 Hybrid Router:
Nutzt erst Keyword-Fast-Paths (Router) und delegiert dann an die DecisionEngine.
"""
"""Hybrid Router: Keyword-Fast-Paths & DecisionEngine LLM Router."""
config = get_full_config()
strategies = config.get("strategies", {})
query_lower = query.lower()
@@ -171,7 +167,7 @@ async def chat_endpoint(
start_time = time.time()
query_id = str(uuid.uuid4())
settings = get_settings()
logger.info(f"🚀 [WP-25] Chat request [{query_id}]: {request.message[:50]}...")
logger.info(f"🚀 [WP-25a] Chat request [{query_id}]: {request.message[:50]}...")
try:
# 1. Intent Detection
@@ -184,13 +180,14 @@ async def chat_endpoint(
sources_hits = []
answer_text = ""
# 2. INTERVIEW MODE (Kompatibilität zu v2.7.8)
# 2. INTERVIEW MODE (Kompatibilität zu v3.0.2)
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)
if not fields_list:
configured_schemas = strategy.get("schemas", {})
fallback = configured_schemas.get(target_type, configured_schemas.get("default", {}))
@@ -203,17 +200,19 @@ async def chat_endpoint(
.replace("{target_type}", target_type) \
.replace("{schema_fields}", fields_str)
# WP-25a: Nutzt spezialisiertes Kompressions-Profil für Interviews
answer_text = await llm.generate_raw_response(
final_prompt, system=llm.get_prompt("system_prompt"),
priority="realtime", provider=strategy.get("preferred_provider"), max_retries=0
priority="realtime", profile_name="compression_fast", max_retries=0
)
sources_hits = []
# 3. RAG MODE (WP-25 Multi-Stream)
# 3. RAG MODE (WP-25a Multi-Stream + Pre-Synthesis)
else:
stream_keys = strategy.get("use_streams", [])
library = engine.config.get("streams_library", {})
# Phase A: Retrieval
tasks = []
active_streams = []
for key in stream_keys:
@@ -222,25 +221,44 @@ async def chat_endpoint(
active_streams.append(key)
tasks.append(engine._run_single_stream(key, stream_cfg, request.message))
import asyncio
responses = await asyncio.gather(*tasks, return_exceptions=True)
raw_stream_map = {}
formatted_context_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
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-20 Stability Fix: Throttling
if provider == "ollama" and len(context_text) > max_chars:
context_text = context_text[:max_chars] + "\n[...]"
# WP-25a: Automatisierte Kompression
stream_cfg = library.get(name, {})
threshold = stream_cfg.get("compression_threshold", 4000)
formatted_context_map[name] = context_text
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())
# Inhalte parallel finalisieren
final_contexts = await asyncio.gather(*formatted_context_tasks)
formatted_context_map = dict(zip(active_streams, final_contexts))
# Phase C: MoE Synthese
answer_text = await engine._generate_final_answer(
intent, strategy, request.message, formatted_context_map
)
@@ -252,7 +270,7 @@ async def chat_endpoint(
try:
log_search(
query_id=query_id, query_text=request.message, results=sources_hits,
mode=f"wp25_{intent.lower()}", metadata={"strategy": intent, "source": intent_source}
mode=f"wp25a_{intent.lower()}", metadata={"strategy": intent, "source": intent_source}
)
except: pass