Update components for WP-25b: Implement Lazy-Prompt-Orchestration across ingestion, decision engine, chat interface, and LLM service. Enhance prompt management with hierarchical model support and streamline response generation by removing manual formatting. Bump versions to reflect new features and optimizations.
This commit is contained in:
1 parent
d41da670fc
commit
7026fc4fed
6 files changed
+589
-203
No files matched your search
@@ -1,13 +1,13 @@
|
||||
"""
|
||||
FILE: app/core/ingestion/ingestion_validation.py
|
||||
DESCRIPTION: WP-15b semantische Validierung von Kanten gegen den LocalBatchCache.
|
||||
WP-25a: Integration der Mixture of Experts (MoE) Profil-Steuerung.
|
||||
VERSION: 2.13.0 (WP-25a: MoE & Profile Support)
|
||||
WP-25b: Umstellung auf Lazy-Prompt-Orchestration (prompt_key + variables).
|
||||
VERSION: 2.14.0 (WP-25b: Lazy Prompt Integration)
|
||||
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).
|
||||
- WP-25b: Entfernung manueller Prompt-Formatierung zur Unterstützung modell-spezifischer Prompts.
|
||||
- WP-25b: Umstellung auf generate_raw_response mit prompt_key="edge_validation".
|
||||
- WP-25a: Voller Erhalt der MoE-Profilsteuerung und Fallback-Kaskade via LLMService.
|
||||
"""
|
||||
import logging
|
||||
from typing import Dict, Any, Optional
|
||||
@@ -27,8 +27,8 @@ async def validate_edge_candidate(
|
||||
profile_name: str = "ingest_validator"
|
||||
) -> bool:
|
||||
"""
|
||||
WP-15b: Validiert einen Kandidaten semantisch gegen das Ziel im Cache.
|
||||
Nutzt das MoE-Profil 'ingest_validator' für deterministische YES/NO Prüfungen.
|
||||
WP-15b/25b: Validiert einen Kandidaten semantisch gegen das Ziel im Cache.
|
||||
Nutzt Lazy-Prompt-Loading zur Unterstützung modell-spezifischer Validierungs-Templates.
|
||||
"""
|
||||
target_id = edge.get("to")
|
||||
target_ctx = batch_cache.get(target_id)
|
||||
@@ -44,27 +44,25 @@ async def validate_edge_candidate(
|
||||
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}' (Profile: {profile_name})...")
|
||||
prompt = template.format(
|
||||
chunk_text=chunk_text[:1500],
|
||||
target_title=target_ctx.title,
|
||||
target_summary=target_ctx.summary,
|
||||
edge_kind=edge.get("kind", "related_to")
|
||||
)
|
||||
|
||||
# WP-25a: Profilbasierter Aufruf (Delegiert Fallbacks an den Service)
|
||||
# Nutzt ingest_validator (Cloud Mistral/Gemini -> Local Phi3:mini Kaskade)
|
||||
# WP-25b: Lazy-Prompt Aufruf.
|
||||
# Wir übergeben keine formatierte Nachricht mehr, sondern Key und Daten-Dict.
|
||||
# Das manuelle 'template = llm_service.get_prompt(...)' entfällt hier.
|
||||
raw_response = await llm_service.generate_raw_response(
|
||||
prompt,
|
||||
prompt_key="edge_validation",
|
||||
variables={
|
||||
"chunk_text": chunk_text[:1500],
|
||||
"target_title": target_ctx.title,
|
||||
"target_summary": target_ctx.summary,
|
||||
"edge_kind": edge.get("kind", "related_to")
|
||||
},
|
||||
priority="background",
|
||||
profile_name=profile_name
|
||||
)
|
||||
|
||||
# WP-14 Fix: Zusätzliche Bereinigung zur Sicherstellung der Interpretierbarkeit
|
||||
# WP-14 Fix: Bereinigung zur Sicherstellung der Interpretierbarkeit
|
||||
response = clean_llm_text(raw_response)
|
||||
|
||||
# Semantische Prüfung des Ergebnisses
|
||||
@@ -75,6 +73,7 @@ async def validate_edge_candidate(
|
||||
else:
|
||||
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} using {profile_name}: {e}")
|
||||
# Im Zweifel (Timeout/Fehler) erlauben wir die Kante, um Datenverlust zu vermeiden
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
"""
|
||||
FILE: app/core/retrieval/decision_engine.py
|
||||
DESCRIPTION: Der Agentic Orchestrator für MindNet (WP-25a Edition).
|
||||
DESCRIPTION: Der Agentic Orchestrator für MindNet (WP-25b Edition).
|
||||
Realisiert Multi-Stream Retrieval, Intent-basiertes Routing
|
||||
und die neue Pre-Synthesis Kompression (Module A).
|
||||
VERSION: 1.2.1 (WP-25a: Profile-Driven Orchestration & Optimized Cascade)
|
||||
und die neue Lazy-Prompt Orchestrierung (Module A & B).
|
||||
VERSION: 1.3.0 (WP-25b: Lazy Prompt Orchestration)
|
||||
STATUS: Active
|
||||
FIX:
|
||||
- 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-25b: Umstellung auf Lazy-Loading (Übergabe von prompt_key + variables).
|
||||
- WP-25b: Entfernung lokaler String-Formatierung zur Ermöglichung modell-spezifischer Prompts.
|
||||
- WP-25a: Volle Integration der Profil-Kaskade via LLMService v3.5.5.
|
||||
- WP-25: Beibehaltung von Stream-Tracing und Pre-Initialization Robustness.
|
||||
- CLEANUP: Entfernung redundanter Fallback-Blocks (jetzt im LLMService).
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
@@ -70,29 +69,27 @@ class DecisionEngine:
|
||||
if not strategy:
|
||||
return "Entschuldigung, meine Wissensbasis ist aktuell nicht konfiguriert."
|
||||
|
||||
# 2. Multi-Stream Retrieval & Pre-Synthesis (Parallel Tasks)
|
||||
# WP-25a: Diese Methode übernimmt nun auch die Kompression.
|
||||
# 2. Multi-Stream Retrieval & Pre-Synthesis (Parallel Tasks inkl. Kompression)
|
||||
stream_results = await self._execute_parallel_streams(strategy, query)
|
||||
|
||||
# 3. Finale Synthese
|
||||
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 via router_profile."""
|
||||
"""WP-25b: Nutzt den LLM-Router via Lazy-Loading prompt_key."""
|
||||
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 LLMService übernimmt hier über das Profil bereits die Fallback-Kaskade
|
||||
# WP-25b: Keine manuelle Formatierung mehr. Wir übergeben nur Key und Variablen.
|
||||
# Der LLMService wählt den passenden Prompt für das router_profile Modell.
|
||||
response = await self.llm_service.generate_raw_response(
|
||||
full_prompt, max_retries=1, priority="realtime", profile_name=router_profile
|
||||
prompt_key=prompt_key,
|
||||
variables={"query": query},
|
||||
max_retries=1,
|
||||
priority="realtime",
|
||||
profile_name=router_profile
|
||||
)
|
||||
return str(response).strip().upper()
|
||||
except Exception as e:
|
||||
@@ -102,7 +99,7 @@ class DecisionEngine:
|
||||
async def _execute_parallel_streams(self, strategy: Dict, query: str) -> Dict[str, str]:
|
||||
"""
|
||||
Führt Such-Streams aus und komprimiert überlange Ergebnisse (Pre-Synthesis).
|
||||
WP-25a: MoE-Profile werden für die Kompression berücksichtigt.
|
||||
WP-25b: Unterstützt Lazy-Compression über Experten-Profile.
|
||||
"""
|
||||
stream_keys = strategy.get("use_streams", [])
|
||||
library = self.config.get("streams_library", {})
|
||||
@@ -116,7 +113,7 @@ class DecisionEngine:
|
||||
active_streams.append(key)
|
||||
retrieval_tasks.append(self._run_single_stream(key, stream_cfg, query))
|
||||
|
||||
# Ergebnisse sammeln (Exceptions werden als Objekte zurückgegeben)
|
||||
# Ergebnisse sammeln
|
||||
retrieval_results = await asyncio.gather(*retrieval_tasks, return_exceptions=True)
|
||||
|
||||
# Phase 2: Formatierung und optionale Kompression
|
||||
@@ -137,38 +134,32 @@ class DecisionEngine:
|
||||
threshold = stream_cfg.get("compression_threshold", 4000)
|
||||
|
||||
if len(formatted_context) > threshold:
|
||||
logger.info(f"⚙️ [WP-25a] Compressing stream '{name}' ({len(formatted_context)} chars)...")
|
||||
logger.info(f"⚙️ [WP-25b] Triggering Lazy-Compression for stream '{name}'...")
|
||||
comp_profile = stream_cfg.get("compression_profile")
|
||||
final_stream_tasks.append(
|
||||
self._compress_stream_content(name, formatted_context, query, comp_profile)
|
||||
)
|
||||
else:
|
||||
# Direkt-Übernahme als Coroutine für gather()
|
||||
async def _direct(c=formatted_context): return c
|
||||
final_stream_tasks.append(_direct())
|
||||
|
||||
# Finale Inhalte (evtl. komprimiert) parallel fertigstellen
|
||||
# Finale Inhalte parallel fertigstellen
|
||||
final_contents = await asyncio.gather(*final_stream_tasks)
|
||||
|
||||
return dict(zip(active_streams, final_contents))
|
||||
|
||||
async def _compress_stream_content(self, stream_name: str, content: str, query: str, profile: Optional[str]) -> str:
|
||||
"""
|
||||
WP-25a Module A: Inhaltsverdichtung via Experten-Modell.
|
||||
"""
|
||||
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"
|
||||
f"BEIBEHALTEN: Harte Fakten, Projektnamen, konkrete Werte und Quellenangaben.\n"
|
||||
f"ENTFERNEN: Redundante Einleitungen, Füllwörter und irrelevante Details.\n\n"
|
||||
f"STREAM-INHALT:\n{content}\n\n"
|
||||
f"KOMPRIMIERTE ANALYSE:"
|
||||
)
|
||||
|
||||
"""WP-25b Module A: Inhaltsverdichtung via Lazy-Loading 'compression_template'."""
|
||||
try:
|
||||
# WP-25b: Wir übergeben den Auftrag an den LLMService.
|
||||
# Das Modell-spezifische Template wird erst beim Call aufgelöst.
|
||||
summary = await self.llm_service.generate_raw_response(
|
||||
compression_prompt,
|
||||
profile_name=profile, # WP-25a: MoE Support
|
||||
prompt_key="compression_template",
|
||||
variables={
|
||||
"stream_name": stream_name,
|
||||
"content": content,
|
||||
"query": query
|
||||
},
|
||||
profile_name=profile,
|
||||
priority="background",
|
||||
max_retries=1
|
||||
)
|
||||
@@ -191,24 +182,19 @@ class DecisionEngine:
|
||||
)
|
||||
|
||||
response = await self.retriever.search(request)
|
||||
|
||||
# WP-25: STREAM-TRACING
|
||||
for hit in response.results:
|
||||
hit.stream_origin = name
|
||||
|
||||
return response
|
||||
|
||||
def _format_stream_context(self, response: QueryResponse) -> str:
|
||||
"""Wandelt QueryHits in einen formatierten Kontext-String um."""
|
||||
if not response.results:
|
||||
return "Keine spezifischen Informationen in diesem Stream gefunden."
|
||||
|
||||
lines = []
|
||||
for i, hit in enumerate(response.results, 1):
|
||||
source = hit.source.get("path", "Unbekannt")
|
||||
content = hit.source.get("text", "").strip()
|
||||
lines.append(f"[{i}] QUELLE: {source}\nINHALT: {content}")
|
||||
|
||||
return "\n\n".join(lines)
|
||||
|
||||
async def _generate_final_answer(
|
||||
@@ -218,12 +204,9 @@ class DecisionEngine:
|
||||
query: str,
|
||||
stream_results: Dict[str, str]
|
||||
) -> str:
|
||||
"""Führt die finale Synthese basierend auf dem Strategie-Profil durch."""
|
||||
# WP-25a: Nutzt das llm_profile der Strategie
|
||||
"""WP-25b: Finale Synthese via Lazy-Prompt 'rag_template'."""
|
||||
profile = strategy.get("llm_profile")
|
||||
template_key = strategy.get("prompt_template", "rag_template")
|
||||
|
||||
template = self.llm_service.get_prompt(template_key)
|
||||
system_prompt = self.llm_service.get_prompt("system_prompt")
|
||||
|
||||
# WP-25 ROBUSTNESS: Pre-Initialization
|
||||
@@ -232,28 +215,15 @@ class DecisionEngine:
|
||||
template_vars.update(stream_results)
|
||||
template_vars["query"] = query
|
||||
|
||||
prepend = strategy.get("prepend_instruction", "")
|
||||
|
||||
# WP-25b: Wir reichen die Variablen direkt an den Service weiter.
|
||||
# Formatierung erfolgt erst nach Profil-Auflösung (Gemini vs. Llama vs. Phi3).
|
||||
try:
|
||||
final_prompt = template.format(**template_vars)
|
||||
if prepend:
|
||||
final_prompt = f"{prepend}\n\n{final_prompt}"
|
||||
|
||||
# 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"
|
||||
)
|
||||
|
||||
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", profile_name=profile
|
||||
prompt_key=template_key,
|
||||
variables=template_vars,
|
||||
system=system_prompt,
|
||||
profile_name=profile,
|
||||
priority="realtime"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Final Synthesis failed: {e}")
|
||||
|
||||
Reference in new issue
Block a user