Files
Hermes_rocket.chat_Plugin/plugin/archivar/router.py
T
Hermes Agent 58f00c0c23 feat(archivar): Phase 1-3 — RoomMap + thematischer Router
Phase 1 (Datenmodell):
- plugin/archivar/room_map.py: RoomMap, RoomEntry, RoomMapValidationError
- room-map.schema.json: JSON-Schema für room-map.json
- room-map.json: Echte Raum-IDs (RC, BAT, LAN-Doku, DM Andreas)
- config.py: LLM_ROOM_PROMPT, ROOM_MAP_PATH, deprecated-Marker

Phase 2 (Router-Umbau):
- router.py: MessageRouter nutzt RoomMap statt ROOM_MAPPING Env-Vars
  - Neue Methode _llm_room_lookup() fragt LLM: 'In welchen Raum?'
  - Keyword-Match aus RoomEntry.keywords (vor Embedding)
  - Excluded rooms check via RoomMap.is_excluded()
  - origin_room_id Parameter für Multi-Agent-Raum-Ausschluss

Phase 3 (Integration):
- adapter_integration.py: _load_room_map() mit Env-Var-Fallback
  - validate() beim Gateway-Start
  - classify_and_route() reicht origin_room_id durch
- classifier.py: _llm_raw_sync() für Room-Prompts (nicht Kategorien)

12/12 Unit-Tests bestanden ✅
2026-06-05 22:06:32 +02:00

479 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Routing-Logik für klassifizierte Nachrichten.
Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle
und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie
und Meta-Fragen-Erkennung.
"""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from .classifier import ClassificationResult, MessageClassifier
from .config import (
CONFIDENCE_THRESHOLD,
FALLBACK_KEYWORDS,
OLLAMA_CONFIG,
LLM_ROOM_PROMPT,
ROOM_MAP_PATH,
)
from .room_map import RoomMap, RoomEntry
logger = logging.getLogger(__name__)
# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem
# Hinweis in der Kopie versehen.
_META_PATTERNS: List[re.Pattern] = [
re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)",
re.IGNORECASE),
re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)",
re.IGNORECASE),
re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)",
re.IGNORECASE),
re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar",
re.IGNORECASE),
re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)",
re.IGNORECASE),
re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)",
re.IGNORECASE),
re.compile(r"(?:who|which room|where).*(?:message|routed|sent)",
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
class RoutingDecision:
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
category: str
"""Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'."""
target_room: str
"""Rocket.Chat Raum-ID des Zielraums."""
confidence: float
"""Konfidenz der Klassifikation (0.0–1.0)."""
is_catch_all: bool = False
"""True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging."""
is_fallback: bool = False
"""True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
is_meta: bool = False
"""True, wenn die Nachricht als Meta-Frage erkannt wurde."""
is_unrouteable: bool = False
"""True, wenn der Zielraum nicht in den subscribed rooms des Bots ist
und die Nachricht stattdessen im DocumentationStore abgelegt wird."""
unrouteable_reason: str = ""
"""Grund, warum kein Routing möglich war (nur bei is_unrouteable=True)."""
prefix: str = ""
"""Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK])."""
delete_original: bool = False
"""True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
project: Optional[str] = None
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
matched_room_name: Optional[str] = None
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
all_scores: Dict[str, float] = field(default_factory=dict)
"""Alle Kategorie-Scores für Debugging/Logging."""
class MessageRouter:
"""Thematischer Router: Nachricht → Zielraum.
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
``RoomMap`` abgelöst.
Usage::
room_map = RoomMap.load()
classifier = MessageClassifier()
await classifier.initialize()
router = MessageRouter(room_map, classifier)
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
decision = await router.route("Wie konfiguriere ich das Plugin?", "6a1f...")
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
# decision.matched_room_name → "#Rocketchat-Plugin"
"""
def __init__(
self,
room_map: RoomMap,
classifier: MessageClassifier,
) -> None:
"""
Args:
room_map: A loaded and validated ``RoomMap`` instance.
classifier: An (initialized) ``MessageClassifier``.
"""
self._room_map = room_map
self._classifier = classifier
self._confidence_threshold = CONFIDENCE_THRESHOLD
self._subscribed_room_ids: Optional[set] = None
# ── Public API ──────────────────────────────────────────────────────
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
"""Klassifiziere und route eine Nachricht.
Der vollständige Routing-Flow:
1. origin_room_id in excluded_rooms? → IGNORE (silent)
2. Keyword-Match in RoomEntry.keywords → Zielraum
3. Keyword-Override-Match → Override-Raum (höchste Prio)
4. Embedding-Klassifikation via Classifier
5. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
6. Kein Treffer → catch_all_room
Args:
text: Der Nachrichtentext.
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
Returns:
RoutingDecision mit Zielraum, Kategorie und Metadaten.
"""
if not text or not text.strip():
return RoutingDecision(
category="FAKT",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0,
is_catch_all=True,
)
text = text.strip()
# ── Schritt 0: Excluded rooms check ──────────────────────────
if origin_room_id and self._room_map.is_excluded(origin_room_id):
logger.debug(
"Message from excluded room %s — ignoring", origin_room_id[:8]
)
return RoutingDecision(
category="FAKT",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=0.0,
is_catch_all=True,
)
# ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
if self._is_meta_question(text):
logger.info("Meta-question detected: %.80s...", text)
return RoutingDecision(
category="FRAGE",
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
confidence=1.0,
is_meta=True,
delete_original=True,
prefix="[META-FRAGE] ",
)
# ── Schritt 1.5: Keyword-Match (aus RoomMap) ──────────────────
matched_room = self._room_map.find_room_by_keywords(text)
if matched_room is not None:
logger.debug(
"Keyword match: '%s' → %s", text[:80], matched_room.name
)
return RoutingDecision(
category="FRAGE",
target_room=matched_room.room_id,
confidence=0.95,
matched_room_name=matched_room.name,
)
# ── Schritt 2: Embedding-basierte Klassifikation ───────────────
result: Optional[ClassificationResult] = None
if self._classifier.is_initialized:
result = await self._classifier.classify(text)
# ── Schritt 3: Fallback bei Classifier-Versagen ────────────────
if result is None:
logger.info(
"Classifier unavailable — using keyword fallback for: %.80s...",
text,
)
category, is_fallback = self._keyword_classify(text)
return RoutingDecision(
category=category,
target_room=self._resolve_room(category),
confidence=0.0,
is_fallback=is_fallback,
prefix="[FALLBACK] " if is_fallback else "",
)
# ── Schritt 4: Konfidenz-Prüfung ───────────────────────────────
if not result.is_confident(self._confidence_threshold):
logger.debug(
"Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all",
result.confidence, self._confidence_threshold, result.category,
)
return RoutingDecision(
category=result.category,
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
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,
all_scores=result.all_scores,
)
decision.is_unrouteable = True
decision.unrouteable_reason = (
"FAKT messages are documentation, not communication — "
"stored in doc_store, never forwarded to chat rooms"
)
logger.info("FAKT → doc_store: %.80s...", text)
return decision
# ── Schritt 6: LLM-Room-Lookup (für FRAGE) ────────────────────
if result.category == "FRAGE":
llm_room = self._llm_room_lookup(text)
if llm_room is not None:
target_room = llm_room.room_id
matched_name = llm_room.name
else:
target_room = self._resolve_room("FRAGE")
matched_name = None
decision = RoutingDecision(
category="FRAGE",
target_room=target_room,
confidence=result.confidence,
all_scores=result.all_scores,
matched_room_name=matched_name,
)
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 ──────────────────────────────────
self._check_unrouteable(decision)
return decision
def _check_unrouteable(self, decision: RoutingDecision) -> None:
"""Validate target_room against subscribed IDs.
If the target room is not in the bot's subscription list, mark the
decision as unrouteable so the caller can store the message in the
DocumentationStore instead of forwarding it.
"""
reason = self._validate_target_room(decision.category, decision.target_room)
if reason:
decision.is_unrouteable = True
decision.unrouteable_reason = reason
logger.warning(
"Unrouteable [%s]: %s", decision.category, reason
)
# ── Room Resolution ────────────────────────────────────────────────
def _resolve_room(self, category: str) -> str:
"""Resolve the target room ID for a category.
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
ALARM routes to catch_all_room. FRAGE uses the catch_all as fallback.
"""
catch_all = self._room_map.catch_all_room
if catch_all is None:
logger.error("No catch_all room configured — cannot route category '%s'", category)
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
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT
für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein
(``ARCHIVAR_ENABLE_LLM=1``).
Args:
text: Der Nachrichtentext.
Returns:
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
"""
# Build room list for LLM prompt
room_list_parts = []
for room in self._room_map.rooms.values():
if room.catch_all:
continue
room_list_parts.append(
f"- {room.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})"
)
room_list_parts.append(
f"- CATCH_ALL: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}"
)
room_list = "\n".join(room_list_parts)
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
# Try LLM classification (raw mode — expects room name, not category)
llm_result = self._classifier._llm_raw_sync(prompt)
if llm_result is None:
return None
# Parse LLM response — could be a room name or "CATCH_ALL"
response = llm_result.strip()
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
return None
# Try to match response to a room name
response_lower = response.lower()
for room in self._room_map.rooms.values():
if response_lower == room.name.lower():
return room
if response_lower in room.name.lower():
return room
logger.debug("LLM returned unknown room: %s", response)
return None
# ── Route Validation ─────────────────────────────────────────────
# ── Meta-Question Detection ────────────────────────────────────────
@staticmethod
def _is_meta_question(text: str) -> bool:
"""Check if a message is a meta-question about the Archivar system.
Meta-questions ask about the classification/routing system itself.
They should NOT be forwarded as regular questions.
"""
for pattern in _META_PATTERNS:
if pattern.search(text):
return True
return False
# ── Fallback: Keyword-Heuristik ────────────────────────────────────
@staticmethod
def _keyword_classify(text: str) -> Tuple[str, bool]:
"""Classify using keyword heuristics when Ollama is unavailable.
Returns:
(category, is_fallback) — is_fallback is always True here.
"""
text_lower = text.lower()
# Check ALARM keywords first (highest priority)
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
if kw in text_lower:
return "ALARM", True
# Check FRAGE keywords
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
if kw in text_lower:
return "FRAGE", True
# Default: FAKT
return "FAKT", True
# ── Configuration ──────────────────────────────────────────────────
@property
def confidence_threshold(self) -> float:
"""Current confidence threshold."""
return self._confidence_threshold
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:
"""Set the bot's current subscribed room IDs for validation.
When set, the router will ONLY route to rooms that are in this list.
Messages targeting unsubscribed rooms are marked as ``is_unrouteable``
and should be stored in the DocumentationStore instead.
Args:
room_ids: List of Rocket.Chat room IDs the bot is subscribed to.
Pass None or empty list to disable validation.
"""
if room_ids:
self._subscribed_room_ids = set(room_ids)
logger.debug(
"Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids)
)
else:
self._subscribed_room_ids = None
def _validate_target_room(self, category: str, room_id: str) -> str:
"""Validate target room against subscribed IDs.
Returns:
Empty string if valid. Human-readable reason if blocked.
"""
if not room_id:
return f"no room configured for category '{category}'"
if self._subscribed_room_ids is None:
return "" # validation disabled
if room_id not in self._subscribed_room_ids:
return (
f"target room {room_id[:8]}... for category '{category}' "
f"is not in bot's subscription list "
f"({len(self._subscribed_room_ids)} subscribed rooms)"
)
return ""