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

+11 -11
View File
@@ -1,11 +1,11 @@
"""
FILE: app/core/ingestion/ingestion_processor.py
DESCRIPTION: Der zentrale IngestionService (Orchestrator).
WP-14: Modularisierung der Datenbank-Ebene (app.core.database).
WP-25a: Integration der Mixture of Experts (MoE) Architektur.
WP-15b: Two-Pass Workflow mit globalem Kontext-Cache.
WP-20/22: Cloud-Resilienz und Content-Lifecycle integriert.
AUDIT v2.13.12: Synchronisierung der Profil-Auflösung mit Registry-Defaults.
VERSION: 2.13.12
AUDIT v2.14.0: Synchronisierung der Profil-Auflösung mit MoE-Experten.
VERSION: 2.14.0 (WP-25a: MoE & Profile Support)
STATUS: Active
"""
import logging
@@ -55,11 +55,15 @@ class IngestionService:
# Synchronisierung der Konfiguration mit dem Instanz-Präfix
self.cfg.prefix = self.prefix
self.client = get_client(self.cfg)
self.dim = self.settings.VECTOR_SIZE
self.registry = load_type_registry()
self.embedder = EmbeddingsClient()
self.llm = LLMService()
# WP-25a: Auflösung der Dimension über das Embedding-Profil (MoE)
embed_cfg = self.llm.profiles.get("embedding_expert", {})
self.dim = embed_cfg.get("dimensions") or self.settings.VECTOR_SIZE
# Festlegen, welcher Hash für die Change-Detection maßgeblich ist
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
self.batch_cache: Dict[str, NoteContext] = {} # WP-15b LocalBatchCache
@@ -155,24 +159,21 @@ class IngestionService:
edge_registry.ensure_latest()
# Profil-Auflösung via Registry
# FIX: Wir nutzen das Profil, das bereits in make_note_payload unter
# Berücksichtigung der types.yaml (Registry) ermittelt wurde.
profile = note_pl.get("chunk_profile", "sliding_standard")
chunk_cfg = get_chunk_config_by_profile(self.registry, profile, note_type)
enable_smart = chunk_cfg.get("enable_smart_edge_allocation", False)
# WP-15b: Chunker-Aufruf bereitet den Candidate-Pool pro Chunk vor.
# assemble_chunks führt intern auch die Propagierung durch.
chunks = await assemble_chunks(note_id, body_text, note_type, config=chunk_cfg)
# Semantische Kanten-Validierung (Smart Edge Allocation)
# Semantische Kanten-Validierung (Smart Edge Allocation via MoE-Profil)
for ch in chunks:
filtered = []
for cand in getattr(ch, "candidate_pool", []):
# Nur global_pool Kandidaten (aus dem Pool am Ende) erfordern KI-Validierung
# WP-25a: Nutzt nun das spezialisierte Validierungs-Profil
if cand.get("provenance") == "global_pool" and enable_smart:
if await validate_edge_candidate(ch.text, cand, self.batch_cache, self.llm, self.settings.MINDNET_LLM_PROVIDER):
if await validate_edge_candidate(ch.text, cand, self.batch_cache, self.llm, profile_name="ingest_validator"):
filtered.append(cand)
else:
# Explizite Kanten (Wikilinks/Callouts) werden ungeprüft übernommen
@@ -204,7 +205,6 @@ class IngestionService:
)
# 4. DB Upsert via modularisierter Points-Logik
# WICHTIG: Wenn sich der Inhalt geändert hat, löschen wir erst alle alten Fragmente.
if purge_before and old_payload:
purge_artifacts(self.client, self.prefix, note_id)
+22 -8
View File
@@ -1,10 +1,16 @@
"""
FILE: app/core/ingestion/ingestion_validation.py
DESCRIPTION: WP-15b semantische Validierung von Kanten gegen den LocalBatchCache.
AUDIT v2.12.3: Integration der zentralen Text-Bereinigung (WP-14).
WP-25a: Integration der Mixture of Experts (MoE) Profil-Steuerung.
VERSION: 2.13.0 (WP-25a: MoE & Profile Support)
STATUS: Active
FIX:
- Umstellung auf generate_raw_response mit profile_name="ingest_validator".
- Automatische Nutzung der Fallback-Kaskade (Cloud -> Lokal) via LLMService.
- Erhalt der sparsamen LLM-Nutzung (Validierung nur für Kandidaten-Pool).
"""
import logging
from typing import Dict, Any
from typing import Dict, Any, Optional
from app.core.parser import NoteContext
# ENTSCHEIDENDER FIX: Import der neutralen Bereinigungs-Logik zur Vermeidung von Circular Imports
@@ -17,11 +23,12 @@ async def validate_edge_candidate(
edge: Dict,
batch_cache: Dict[str, NoteContext],
llm_service: Any,
provider: str
provider: Optional[str] = None,
profile_name: str = "ingest_validator"
) -> bool:
"""
WP-15b: Validiert einen Kandidaten semantisch gegen das Ziel im Cache.
Nutzt clean_llm_text zur Entfernung von Steuerzeichen vor der Auswertung.
Nutzt das MoE-Profil 'ingest_validator' für deterministische YES/NO Prüfungen.
"""
target_id = edge.get("to")
target_ctx = batch_cache.get(target_id)
@@ -32,14 +39,16 @@ async def validate_edge_candidate(
target_ctx = batch_cache.get(base_id)
# Sicherheits-Fallback (Hard-Link Integrity)
# Explizite Wikilinks oder Callouts werden nicht durch das LLM verifiziert.
if not target_ctx:
logger.info(f"ℹ️ [VALIDATION SKIP] No context for '{target_id}' - allowing link.")
return True
# Prompt-Abruf (Nutzt Provider-String als Fallback-Key für die prompts.yaml)
template = llm_service.get_prompt("edge_validation", provider)
try:
logger.info(f"⚖️ [VALIDATING] Relation '{edge.get('kind')}' -> '{target_id}'...")
logger.info(f"⚖️ [VALIDATING] Relation '{edge.get('kind')}' -> '{target_id}' (Profile: {profile_name})...")
prompt = template.format(
chunk_text=chunk_text[:1500],
target_title=target_ctx.title,
@@ -47,8 +56,13 @@ async def validate_edge_candidate(
edge_kind=edge.get("kind", "related_to")
)
# Die Antwort vom Service anfordern
raw_response = await llm_service.generate_raw_response(prompt, priority="background")
# WP-25a: Profilbasierter Aufruf (Delegiert Fallbacks an den Service)
# Nutzt ingest_validator (Cloud Mistral/Gemini -> Local Phi3:mini Kaskade)
raw_response = await llm_service.generate_raw_response(
prompt,
priority="background",
profile_name=profile_name
)
# WP-14 Fix: Zusätzliche Bereinigung zur Sicherstellung der Interpretierbarkeit
response = clean_llm_text(raw_response)
@@ -62,6 +76,6 @@ async def validate_edge_candidate(
logger.info(f"🚫 [REJECTED] Relation to '{target_id}' irrelevant for this chunk.")
return is_valid
except Exception as e:
logger.warning(f"⚠️ Validation error for {target_id}: {e}")
logger.warning(f"⚠️ Validation error for {target_id} using {profile_name}: {e}")
# Im Zweifel (Timeout/Fehler) erlauben wir die Kante, um Datenverlust zu vermeiden
return True
+17 -20
View File
@@ -3,13 +3,14 @@ FILE: app/core/retrieval/decision_engine.py
DESCRIPTION: Der Agentic Orchestrator für MindNet (WP-25a Edition).
Realisiert Multi-Stream Retrieval, Intent-basiertes Routing
und die neue Pre-Synthesis Kompression (Module A).
VERSION: 1.2.0 (WP-25a: Mixture of Experts Support)
VERSION: 1.2.1 (WP-25a: Profile-Driven Orchestration & Optimized Cascade)
STATUS: Active
FIX:
- WP-25a: Vollständige Integration der llm_profile-Steuerung für Synthese und Kompression.
- WP-25a: Implementierung der _compress_stream_content Logik zur Inhaltsverdichtung.
- WP-25a: Volle Integration der Profil-Kaskade (Delegation an LLMService v3.5.2).
- WP-25a: Dynamische Nutzung des 'router_profile' für die Intent-Erkennung.
- WP-25a: Parallelisierte Kompression überlanger Wissens-Streams.
- WP-25: Beibehaltung von Stream-Tracing und Pre-Initialization Robustness.
- COMPATIBILITY: Erhalt aller Methoden-Signaturen für den System-Merge.
- CLEANUP: Entfernung redundanter Fallback-Blocks (jetzt im LLMService).
"""
import asyncio
import logging
@@ -77,16 +78,19 @@ class DecisionEngine:
return await self._generate_final_answer(strategy_key, strategy, query, stream_results)
async def _determine_strategy(self, query: str) -> str:
"""Nutzt den LLM-Router zur Wahl der Such-Strategie."""
prompt_key = self.config.get("settings", {}).get("router_prompt_key", "intent_router_v1")
router_profile = self.config.get("settings", {}).get("router_profile")
"""Nutzt den LLM-Router zur Wahl der Such-Strategie via router_profile."""
settings_cfg = self.config.get("settings", {})
prompt_key = settings_cfg.get("router_prompt_key", "intent_router_v1")
# WP-25a: Nutzt das spezialisierte Profil für das Routing
router_profile = settings_cfg.get("router_profile")
router_prompt_template = self.llm_service.get_prompt(prompt_key)
if not router_prompt_template:
return "FACT_WHAT"
full_prompt = router_prompt_template.format(query=query)
try:
# Der Router nutzt den Standard-Provider (auto)
# Der LLMService übernimmt hier über das Profil bereits die Fallback-Kaskade
response = await self.llm_service.generate_raw_response(
full_prompt, max_retries=1, priority="realtime", profile_name=router_profile
)
@@ -128,7 +132,7 @@ class DecisionEngine:
# Formatierung der Hits in Text
formatted_context = self._format_stream_context(res)
# WP-25a: Kompressions-Check
# WP-25a: Kompressions-Check (Inhaltsverdichtung)
stream_cfg = library.get(name, {})
threshold = stream_cfg.get("compression_threshold", 4000)
@@ -152,7 +156,6 @@ class DecisionEngine:
"""
WP-25a Module A: Inhaltsverdichtung via Experten-Modell.
"""
# Falls kein Profil definiert, nutzen wir das Default-Profil der Strategie
compression_prompt = (
f"Du bist ein Wissens-Analyst. Reduziere den folgenden Wissens-Stream '{stream_name}' "
f"auf die Informationen, die für die Beantwortung der Frage '{query}' absolut notwendig sind.\n\n"
@@ -220,8 +223,6 @@ class DecisionEngine:
profile = strategy.get("llm_profile")
template_key = strategy.get("prompt_template", "rag_template")
# Hier nutzen wir noch den Provider-String für get_prompt (Kompatibilität zu prompts.yaml)
# Der llm_service löst das Profil erst bei generate_raw_response auf.
template = self.llm_service.get_prompt(template_key)
system_prompt = self.llm_service.get_prompt("system_prompt")
@@ -238,25 +239,21 @@ class DecisionEngine:
if prepend:
final_prompt = f"{prepend}\n\n{final_prompt}"
# WP-25a: MoE Call
# WP-25a: MoE Call mit automatisierter Kaskade im LLMService
# (Frühere manuelle Fallback-Blocks wurden entfernt, da v3.5.2 dies intern löst)
response = await self.llm_service.generate_raw_response(
final_prompt, system=system_prompt, profile_name=profile, priority="realtime"
)
# Fallback bei leerer Antwort auf lokales Modell
if not response or len(response.strip()) < 5:
return await self.llm_service.generate_raw_response(
final_prompt, system=system_prompt, provider="ollama", priority="realtime"
)
return response
except KeyError as e:
logger.error(f"Template Variable mismatch in '{template_key}': Missing {e}")
fallback_context = "\n\n".join([v for v in stream_results.values() if v])
# WP-25a FIX: Nutzt auch im Fallback das Strategie-Profil für Konsistenz
return await self.llm_service.generate_raw_response(
f"Beantworte: {query}\n\nKontext:\n{fallback_context}",
system=system_prompt, priority="realtime"
system=system_prompt, priority="realtime", profile_name=profile
)
except Exception as e:
logger.error(f"Final Synthesis failed: {e}")