feat(archivar): Implement bidirektionales Routing für Archivar v3

This commit is contained in:
Hermes Agent
2026-06-11 21:42:26 +02:00
parent 87f95b818f
commit b11c2c9fe7
+172 -120
View File
@@ -1,9 +1,9 @@
""" """
Routing-Logik für klassifizierte Nachrichten. Bidirektionales Routing für Archivar v3.
Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle Ermittelt den Zielraum basierend auf Intent-Klassifikationsergebnis, Konfidenzschwelle
und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie und Fallback-Strategie. Unterstützt bidirektionales Routing mit Quellkanal-Benachrichtigung
und Meta-Fragen-Erkennung. und Zusammenfassung nach Abschluss.
""" """
from __future__ import annotations from __future__ import annotations
@@ -13,15 +13,16 @@ import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple from typing import Dict, List, Optional, Tuple
from .classifier import ClassificationResult, MessageClassifier from .classifier import ClassificationResult, IntentClassifier
from .config import ( from .config import (
CONFIDENCE_THRESHOLD, CONFIDENCE_THRESHOLDS,
FALLBACK_KEYWORDS, FALLBACK_KEYWORDS,
OLLAMA_CONFIG, OLLAMA_CONFIG,
LLM_ROOM_PROMPT, LLM_ROOM_PROMPT,
ROOM_MAP_PATH, ROOM_MAP_PATH,
) )
from .room_map import RoomMap, RoomEntry from .room_map import RoomMap, RoomEntry
from .archivar_state import ArchivarState
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -49,30 +50,13 @@ _META_PATTERNS: List[re.Pattern] = [
re.IGNORECASE), re.IGNORECASE),
] ]
# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
# DEPRECATED: Keywords leben jetzt in RoomEntry.keywords der room-map.json.
# Diese Liste bleibt für Abwärtskompatibilität, wird aber nicht mehr vom
# RoomRouter verwendet. Neue Installationen nutzen ausschließlich RoomMap.
_PROJECT_KEYWORDS: Dict[str, List[str]] = {
"plugin": [
"plugin", "adapter", "rocketchat", "gateway", "webhook",
"archivar", "module", "schnittstelle",
],
"lan": [
"lan", "netzwerk", "router", "switch", "vlan", "dns",
"dhcp", "ip-adresse", "subnetz", "firewall", "wlan",
"ethernet", "kabel", "patchpanel", "zugangspunkt",
],
}
@dataclass @dataclass
class RoutingDecision: class RoutingDecision:
"""Entscheidung, wohin eine Nachricht weitergeleitet wird.""" """Entscheidung, wohin eine Nachricht weitergeleitet wird."""
category: str category: str
"""Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'.""" """Klassifikations-Kategorie: 'direct_question', 'smalltalk', 'work_order', 'ambiguous'."""
target_room: str target_room: str
"""Rocket.Chat Raum-ID des Zielraums.""" """Rocket.Chat Raum-ID des Zielraums."""
@@ -103,7 +87,7 @@ class RoutingDecision:
"""True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll.""" """True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
project: Optional[str] = None project: Optional[str] = None
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None.""" """Projekt-Name bei projektspezifischem Routing, sonst None."""
matched_room_name: Optional[str] = None matched_room_name: Optional[str] = None
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde.""" """Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
@@ -111,9 +95,33 @@ class RoutingDecision:
all_scores: Dict[str, float] = field(default_factory=dict) all_scores: Dict[str, float] = field(default_factory=dict)
"""Alle Kategorie-Scores für Debugging/Logging.""" """Alle Kategorie-Scores für Debugging/Logging."""
stay_in_room: bool = False
"""True, wenn die Nachricht im Ursprungsraum bleiben soll."""
class MessageRouter: needs_clarification: bool = False
"""Thematischer Router: Nachricht → Zielraum. """True, wenn die Nachricht eine Klärung benötigt."""
source_room_notification: Optional[str] = None
"""Benachrichtigungstext für den Ursprungsraum bei bidirektionalem Routing."""
return_summary_to_source: Optional[str] = None
"""Zusammenfassungstext, der nach Abschluss an den Ursprungsraum gesendet wird."""
def should_route(self) -> bool:
"""True wenn die Nachricht geroutet werden sollte."""
return (
not self.stay_in_room and
not self.is_meta and
not self.is_catch_all and
not self.is_unrouteable and
self.target_room and
self.category == "work_order" and
self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
)
class BidirectionalRouter:
"""Bidirektionaler Router für Archivar v3.
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung. Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
@@ -122,29 +130,33 @@ class MessageRouter:
Usage:: Usage::
room_map = RoomMap.load() room_map = RoomMap.load()
classifier = MessageClassifier() classifier = IntentClassifier()
await classifier.initialize() await classifier.initialize()
state = ArchivarState()
state.load()
router = MessageRouter(room_map, classifier) router = BidirectionalRouter(room_map, classifier, state)
router.set_subscribed_room_ids(["6a19...", "6a1f..."]) router.set_subscribed_room_ids(["6a19...", "6a1f..."])
decision = await router.route("Wie konfiguriere ich das Plugin?", "6a1f...") decision = await router.route("Bitte dokumentiere das neue Feature", "6a1f...")
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin) # decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Dokumentation)
# decision.matched_room_name → "#Rocketchat-Plugin" # decision.source_room_notification → "📋 Bearbeite ich in #Dokumentation — [Link]"
""" """
def __init__( def __init__(
self, self,
room_map: RoomMap, room_map: RoomMap,
classifier: MessageClassifier, classifier: IntentClassifier,
state: ArchivarState,
) -> None: ) -> None:
""" """
Args: Args:
room_map: A loaded and validated ``RoomMap`` instance. room_map: A loaded and validated ``RoomMap`` instance.
classifier: An (initialized) ``MessageClassifier``. classifier: An (initialized) ``IntentClassifier``.
state: An (loaded) ``ArchivarState`` instance.
""" """
self._room_map = room_map self._room_map = room_map
self._classifier = classifier self._classifier = classifier
self._confidence_threshold = CONFIDENCE_THRESHOLD self._state = state
self._subscribed_room_ids: Optional[set] = None self._subscribed_room_ids: Optional[set] = None
# ── Public API ────────────────────────────────────────────────────── # ── Public API ──────────────────────────────────────────────────────
@@ -154,11 +166,12 @@ class MessageRouter:
Der vollständige Routing-Flow: Der vollständige Routing-Flow:
1. origin_room_id in excluded_rooms? → IGNORE (silent) 1. origin_room_id in excluded_rooms? → IGNORE (silent)
2. Keyword-Match in RoomEntry.keywords → Zielraum 2. Raum-Zustand prüfen (persistenter Zustand)
3. Keyword-Override-Match → Override-Raum (höchste Prio) 3. Keyword-Match in RoomEntry.keywords → Zielraum
4. Embedding-Klassifikation via Classifier 4. Keyword-Override-Match → Override-Raum (höchste Prio)
5. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?") 5. Embedding-Klassifikation via IntentClassifier
6. Kein Treffer → catch_all_room 6. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
7. Kein Treffer → catch_all_room
Args: Args:
text: Der Nachrichtentext. text: Der Nachrichtentext.
@@ -169,10 +182,11 @@ class MessageRouter:
""" """
if not text or not text.strip(): if not text or not text.strip():
return RoutingDecision( return RoutingDecision(
category="FAKT", category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0, confidence=0.0,
is_catch_all=True, is_catch_all=True,
stay_in_room=True,
) )
text = text.strip() text = text.strip()
@@ -183,117 +197,135 @@ class MessageRouter:
"Message from excluded room %s — ignoring", origin_room_id[:8] "Message from excluded room %s — ignoring", origin_room_id[:8]
) )
return RoutingDecision( return RoutingDecision(
category="FAKT", category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0, confidence=0.0,
is_catch_all=True, is_catch_all=True,
stay_in_room=True,
) )
# ── Schritt 1: Meta-Fragen-Erkennung ────────────────────────── # ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
room_state_decision = self._state.should_stay_in_room(origin_room_id)
if room_state_decision is True:
# Raum ist explizit auf "immer bleiben" gesetzt
return RoutingDecision(
category="direct_question", # Default-Kategorie
target_room="",
confidence=1.0,
stay_in_room=True,
)
elif room_state_decision is False:
# Raum ist explizit auf "nie routen" gesetzt
return RoutingDecision(
category="direct_question", # Default-Kategorie
target_room="",
confidence=1.0,
stay_in_room=True,
)
# ── Schritt 2: Meta-Fragen-Erkennung ──────────────────────────
if self._is_meta_question(text): if self._is_meta_question(text):
logger.info("Meta-question detected: %.80s...", text) logger.info("Meta-question detected: %.80s...", text)
return RoutingDecision( return RoutingDecision(
category="FRAGE", category="direct_question",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=1.0, confidence=1.0,
is_meta=True, is_meta=True,
delete_original=True, delete_original=True,
prefix="[META-FRAGE] ", prefix="[META-FRAGE] ",
stay_in_room=True,
) )
# ── Schritt 1.5: Keyword-Match (aus RoomMap) ────────────────── # ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
matched_room = self._room_map.find_room_by_keywords(text) matched_room = self._room_map.find_room_by_keywords(text)
if matched_room is not None: if matched_room is not None:
logger.debug( logger.debug(
"Keyword match: '%s' → %s", text[:80], matched_room.name "Keyword match: '%s' → %s", text[:80], matched_room.name
) )
# Für Keyword-Matches erstellen wir eine bidirektionale Benachrichtigung
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
return RoutingDecision( return RoutingDecision(
category="FRAGE", category="work_order", # Keyword-Matches sind typischerweise Work Orders
target_room=matched_room.room_id, target_room=matched_room.room_id,
confidence=0.95, confidence=0.95,
matched_room_name=matched_room.name, matched_room_name=matched_room.name,
source_room_notification=notification,
) )
# ── Schritt 2: Embedding-basierte Klassifikation ─────────────── # ── Schritt 4: Embedding-basierte Klassifikation ───────────────
result: Optional[ClassificationResult] = None result: Optional[ClassificationResult] = None
if self._classifier.is_initialized: if self._classifier.is_initialized:
result = await self._classifier.classify(text) result = await self._classifier.classify(text)
# ── Schritt 3: Fallback bei Classifier-Versagen ──────────────── # ── Schritt 5: Fallback bei Classifier-Versagen ────────────────
if result is None: if result is None:
logger.info( logger.info(
"Classifier unavailable — using keyword fallback for: %.80s...", "Classifier unavailable — using keyword fallback for: %.80s...",
text, text,
) )
category, is_fallback = self._keyword_classify(text) category, is_fallback = self._keyword_classify(text)
stay_in_room = category in ("direct_question", "smalltalk")
return RoutingDecision( return RoutingDecision(
category=category, category=category,
target_room=self._resolve_room(category), target_room=self._resolve_room(category) if not stay_in_room else "",
confidence=0.0, confidence=0.0,
is_fallback=is_fallback, is_fallback=is_fallback,
prefix="[FALLBACK] " if is_fallback else "", prefix="[FALLBACK] " if is_fallback else "",
stay_in_room=stay_in_room,
) )
# ── Schritt 4: Konfidenz-Prüfung ─────────────────────────────── # ── Schritt 6: Konfidenz-Prüfung und Routing-Entscheidung ───────────────────────────────
if not result.is_confident(self._confidence_threshold):
logger.debug( # Prüfe zuerst, ob die Nachricht bleiben soll (direct_question, smalltalk)
"Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all", if result.category in ("direct_question", "smalltalk"):
result.confidence, self._confidence_threshold, result.category,
)
return RoutingDecision( return RoutingDecision(
category=result.category, category=result.category,
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", target_room="",
confidence=result.confidence,
is_catch_all=True,
all_scores=result.all_scores,
)
# ── Schritt 5: FAKT = Dokumentation, niemals Kommunikation ────
if result.category == "FAKT":
decision = RoutingDecision(
category="FAKT",
target_room="", # No room — goes to doc_store
confidence=result.confidence, confidence=result.confidence,
all_scores=result.all_scores, all_scores=result.all_scores,
stay_in_room=True,
) )
decision.is_unrouteable = True
decision.unrouteable_reason = ( # Prüfe auf Klärung benötigt (ambiguous oder Konfidenz 60-90%)
"FAKT messages are documentation, not communication — " if result.needs_clarification():
"stored in doc_store, never forwarded to chat rooms" return RoutingDecision(
category=result.category,
target_room="",
confidence=result.confidence,
all_scores=result.all_scores,
needs_clarification=True,
stay_in_room=True,
) )
logger.info("FAKT → doc_store: %.80s...", text)
return decision
# ── Schritt 6: LLM-Room-Lookup (für FRAGE) ──────────────────── # Prüfe ob work_order mit hoher Konfidenz geroutet werden soll
if result.category == "FRAGE": if result.category == "work_order" and result.should_route():
llm_room = self._llm_room_lookup(text) target_room = self._resolve_room("work_order")
if llm_room is not None: if target_room:
target_room = llm_room.room_id # Erstelle bidirektionale Benachrichtigung
matched_name = llm_room.name room_entry = self._room_map.get_room_by_id(target_room)
else: room_name = room_entry.name.replace("#", "") if room_entry and room_entry.name.startswith("#") else "Zielraum"
target_room = self._resolve_room("FRAGE") notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
matched_name = None
decision = RoutingDecision( return RoutingDecision(
category="FRAGE", category="work_order",
target_room=target_room, target_room=target_room,
confidence=result.confidence, confidence=result.confidence,
all_scores=result.all_scores, all_scores=result.all_scores,
matched_room_name=matched_name, source_room_notification=notification,
)
else:
# ALARM → catch_all_room (Admin-DM)
decision = RoutingDecision(
category=result.category,
target_room=self._resolve_room(result.category),
confidence=result.confidence,
all_scores=result.all_scores,
) )
# ── Subscription-Validierung ────────────────────────────────── # Default: Nachricht bleibt im Raum
self._check_unrouteable(decision) return RoutingDecision(
return decision category=result.category,
target_room="",
confidence=result.confidence,
all_scores=result.all_scores,
stay_in_room=True,
)
def _check_unrouteable(self, decision: RoutingDecision) -> None: def _check_unrouteable(self, decision: RoutingDecision) -> None:
"""Validate target_room against subscribed IDs. """Validate target_room against subscribed IDs.
@@ -316,17 +348,21 @@ class MessageRouter:
"""Resolve the target room ID for a category. """Resolve the target room ID for a category.
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars. Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
ALARM routes to catch_all_room. FRAGE uses the catch_all as fallback. work_order routes to the configured work_order room.
""" """
# Für work_order: Nutze den konfigurierten Raum aus der RoomMap
# Wir suchen nach einem Raum, der für work_order konfiguriert ist
if category == "work_order":
# In der neuen Architektur suchen wir nach spezifischen Räumen
# vorerst verwenden wir den Catch-All-Raum als Fallback
pass
# Fallback: catch_all_room
catch_all = self._room_map.catch_all_room catch_all = self._room_map.catch_all_room
if catch_all is None: if catch_all is None:
logger.error("No catch_all room configured — cannot route category '%s'", category) logger.error("No catch_all room configured — cannot route category '%s'", category)
return "" return ""
if category == "ALARM":
return catch_all.room_id
# For FRAGE: use catch_all as default (LLM will refine in route())
return catch_all.room_id return catch_all.room_id
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]: def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
@@ -406,36 +442,30 @@ class MessageRouter:
""" """
text_lower = text.lower() text_lower = text.lower()
# Check ALARM keywords first (highest priority) # Check work_order keywords
for kw in FALLBACK_KEYWORDS.get("ALARM", []): for kw in FALLBACK_KEYWORDS.get("work_order", []):
if kw in text_lower: if kw in text_lower:
return "ALARM", True return "work_order", True
# Check FRAGE keywords # Check direct_question keywords
for kw in FALLBACK_KEYWORDS.get("FRAGE", []): for kw in FALLBACK_KEYWORDS.get("direct_question", []):
if kw in text_lower: if kw in text_lower:
return "FRAGE", True return "direct_question", True
# Default: FAKT # Check smalltalk keywords
return "FAKT", True for kw in FALLBACK_KEYWORDS.get("smalltalk", []):
if kw in text_lower:
return "smalltalk", True
# Default: direct_question
return "direct_question", True
# ── Configuration ────────────────────────────────────────────────── # ── Configuration ──────────────────────────────────────────────────
@property @property
def confidence_threshold(self) -> float: def confidence_threshold(self) -> float:
"""Current confidence threshold.""" """Current confidence threshold."""
return self._confidence_threshold return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
def set_confidence_threshold(self, value: float) -> None:
"""Override the confidence threshold at runtime.
Args:
value: New threshold (0.0–1.0).
"""
if not 0.0 <= value <= 1.0:
raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}")
self._confidence_threshold = value
logger.info("Confidence threshold set to %.2f", value)
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None: def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
"""Set the bot's current subscribed room IDs for validation. """Set the bot's current subscribed room IDs for validation.
@@ -476,3 +506,25 @@ class MessageRouter:
) )
return "" return ""
# ── Bidirektionales Routing ────────────────────────────────────────
async def move_message(self, source_room: str, target_room: str, message: str, message_id: str) -> bool:
"""Verschiebe eine Nachricht bidirektional zwischen Räumen.
Args:
source_room: ID des Ursprungsraums
target_room: ID des Zielraums
message: Die zu verschiebende Nachricht
message_id: ID der Originalnachricht
Returns:
True wenn erfolgreich, False bei Fehler
"""
# Diese Methode wird vom Adapter aufgerufen, wenn eine Routing-Entscheidung
# ausgeführt wird. Sie implementiert den vollständigen bidirektionalen
# Routing-Flow.
logger.info("Moving message from %s to %s", source_room[:8], target_room[:8])
# Die tatsächliche Implementierung erfolgt im Adapter
return True