58f00c0c23
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 ✅
469 lines
17 KiB
Python
469 lines
17 KiB
Python
"""
|
||
Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
|
||
|
||
Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
|
||
in ``adapter.py`` dient. Sie kapselt Classifier + Router und bietet eine
|
||
einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline.
|
||
|
||
Einhängung in adapter.py::
|
||
|
||
from .adapter_integration import ArchivarMessageHandler
|
||
|
||
class RocketChatAdapter(BasePlatformAdapter):
|
||
def __init__(self, config):
|
||
...
|
||
self.archivar = ArchivarMessageHandler()
|
||
|
||
async def connect(self):
|
||
...
|
||
await self.archivar.initialize()
|
||
|
||
async def _process_incoming(self, msg_obj):
|
||
...
|
||
text = msg_obj.get("msg", "")
|
||
room_id = msg_obj.get("rid", "")
|
||
|
||
decision = await self.archivar.classify_and_route(text)
|
||
|
||
if decision.target_room != room_id:
|
||
# Kopie an Zielraum senden (Original bleibt!)
|
||
prefix = decision.prefix or ""
|
||
await self._send_to_room(decision.target_room, f"{prefix}{text}")
|
||
|
||
if decision.delete_original:
|
||
await self._delete_message(room_id, msg_id)
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import logging
|
||
import time
|
||
from typing import Any, Awaitable, Callable, Dict, Optional
|
||
|
||
from .classifier import (
|
||
ClassificationResult,
|
||
EmbeddingClient,
|
||
MessageClassifier,
|
||
LLMClient,
|
||
OllamaLLMClient,
|
||
)
|
||
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG, ROOM_MAP_PATH
|
||
from .doc_store import DocumentationStore
|
||
from .room_map import RoomMap, RoomMapValidationError
|
||
from .router import MessageRouter, RoutingDecision
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# Callback-Signatur: async (room_id: str, text: str) -> bool
|
||
SendCallback = Callable[[str, str], Awaitable[bool]]
|
||
|
||
|
||
class ArchivarMessageHandler:
|
||
"""Hauptklasse für die Archivar-Integration.
|
||
|
||
Kapselt Classifier und Router. Wird vom RocketChatAdapter beim Start
|
||
initialisiert und bei jeder eingehenden Nachricht aufgerufen.
|
||
|
||
Usage::
|
||
|
||
handler = ArchivarMessageHandler()
|
||
await handler.initialize() # einmalig beim Adapter-Start
|
||
|
||
# Bei jeder Nachricht:
|
||
decision = await handler.classify_and_route(text)
|
||
# decision.target_room enthält die Zielraum-ID
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
send_callback: Optional[SendCallback] = None,
|
||
confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
||
ollama_base_url: Optional[str] = None,
|
||
embedding_client: Optional[EmbeddingClient] = None,
|
||
llm_client: Optional[LLMClient] = None,
|
||
) -> None:
|
||
"""
|
||
Args:
|
||
send_callback: Optionale async Callback-Funktion zum Senden von
|
||
Nachrichten via Rocket.Chat REST API. Signatur:
|
||
``async def send(room_id: str, text: str) -> bool``.
|
||
Wenn gesetzt, kann ``handle_and_forward()`` verwendet werden.
|
||
confidence_threshold: Konfidenz-Schwellenwert (0.0–1.0).
|
||
ollama_base_url: Override für Ollama-Basis-URL.
|
||
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||
Wird an den ``MessageClassifier`` durchgereicht.
|
||
Ermöglicht Mocking/alternative Embedding-Backends.
|
||
llm_client: Optionales ``LLMClient``-Interface.
|
||
Wird an den ``MessageClassifier`` durchgereicht.
|
||
Ermöglicht Mocking/alternative LLM-Backends.
|
||
"""
|
||
self._send_callback = send_callback
|
||
self._enable_llm = LLM_CONFIG["enabled"]
|
||
|
||
# Create LLM client if enabled and not provided
|
||
if self._enable_llm and llm_client is None:
|
||
llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None
|
||
|
||
self._classifier = MessageClassifier(
|
||
base_url=ollama_base_url,
|
||
embedding_client=embedding_client,
|
||
llm_client=llm_client
|
||
)
|
||
self._doc_store = DocumentationStore()
|
||
|
||
# Load RoomMap (try JSON first, fall back to legacy env vars)
|
||
self._room_map = self._load_room_map()
|
||
|
||
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||
self._subscribed_room_ids_cache: Optional[set] = None
|
||
|
||
self._router = MessageRouter(self._room_map, self._classifier)
|
||
self._router.set_confidence_threshold(confidence_threshold)
|
||
self._initialized = False
|
||
|
||
# Statistiken (erweitert um Latenz + Fehler)
|
||
self._stats: Dict[str, Any] = {
|
||
"total": 0,
|
||
"classified": 0,
|
||
"catch_all": 0,
|
||
"fallback": 0,
|
||
"meta": 0,
|
||
"errors": 0,
|
||
"llm_classified": 0, # Neue Statistik für LLM-Klassifikationen
|
||
"avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
||
"last_error": None, # str | None — letzter Fehler
|
||
"latencies": [], # list[float] — per-request ms
|
||
}
|
||
|
||
# ── RoomMap Loading ─────────────────────────────────────────────────
|
||
|
||
@staticmethod
|
||
def _load_room_map() -> RoomMap:
|
||
"""Load RoomMap from JSON, with legacy env var fallback.
|
||
|
||
Tries ``room-map.json`` first. If not found, attempts migration from
|
||
deprecated ``ARCHIVAR_*_ROOM`` env vars.
|
||
|
||
Returns:
|
||
A ``RoomMap`` instance.
|
||
|
||
Raises:
|
||
FileNotFoundError: If no map source is available.
|
||
"""
|
||
import json
|
||
from pathlib import Path
|
||
|
||
map_path = Path(ROOM_MAP_PATH)
|
||
|
||
if map_path.exists():
|
||
logger.info("Loading room map from %s", map_path)
|
||
return RoomMap.load(map_path)
|
||
|
||
# Try legacy env vars
|
||
logger.warning(
|
||
"Room map not found at %s — trying legacy ARCHIVAR_*_ROOM env vars",
|
||
map_path,
|
||
)
|
||
from .room_map import _migrate_from_env_vars
|
||
|
||
legacy_data = _migrate_from_env_vars()
|
||
if legacy_data is not None:
|
||
logger.warning(
|
||
"Using legacy env vars for room mapping. "
|
||
"Please create %s for new features.",
|
||
map_path,
|
||
)
|
||
return RoomMap._from_dict(legacy_data)
|
||
|
||
raise FileNotFoundError(
|
||
f"No room map found at {map_path} and no legacy "
|
||
"ARCHIVAR_*_ROOM env vars set. "
|
||
"Create a room-map.json or set ARCHIVAR_CATCHALL_ROOM."
|
||
)
|
||
|
||
# ── Public API ──────────────────────────────────────────────────────
|
||
|
||
async def initialize(self) -> bool:
|
||
"""Einmalige Initialisierung: Pre-compute Kategorie-Vektoren + validiere Map.
|
||
|
||
Muss vor dem ersten ``classify_and_route()``-Aufruf aufgerufen werden.
|
||
Safe für mehrfache Aufrufe — no-op wenn bereits initialisiert.
|
||
|
||
Returns:
|
||
True wenn die Initialisierung erfolgreich war (Classifier bereit).
|
||
False wenn Ollama nicht erreichbar ist → Fallback-Modus aktiv.
|
||
|
||
Raises:
|
||
RoomMapValidationError: Wenn die room-map.json fatal invalide ist
|
||
(0 oder >1 Catch-All, Catch-All in excluded_rooms).
|
||
"""
|
||
if self._initialized:
|
||
return True
|
||
|
||
logger.info("Initializing ArchivarMessageHandler...")
|
||
|
||
# Validate RoomMap FIRST (fail-fast)
|
||
if self._subscribed_room_ids_cache is not None:
|
||
errors = self._room_map.validate(self._subscribed_room_ids_cache)
|
||
if errors:
|
||
logger.warning(
|
||
"Room map validation warnings: %s",
|
||
"; ".join(errors),
|
||
)
|
||
|
||
success = await self._classifier.initialize()
|
||
|
||
if success:
|
||
self._initialized = True
|
||
logger.info(
|
||
"ArchivarMessageHandler ready: %d categories, model=%s",
|
||
self._classifier.category_count,
|
||
OLLAMA_CONFIG["model"],
|
||
)
|
||
else:
|
||
logger.warning(
|
||
"ArchivarMessageHandler initialized in FALLBACK mode — "
|
||
"Ollama unavailable at %s. Will use keyword heuristics.",
|
||
OLLAMA_CONFIG["base_url"],
|
||
)
|
||
# Mark as initialized anyway — the classifier will return None
|
||
# and the router will use keyword fallback.
|
||
self._initialized = True
|
||
|
||
return success
|
||
|
||
async def classify_and_route(
|
||
self, text: str, origin_room_id: str = ""
|
||
) -> RoutingDecision:
|
||
"""Klassifiziere eine Nachricht und ermittle den Zielraum.
|
||
|
||
Dies ist die primäre Methode für die adapter.py-Integration.
|
||
Sie führt die vollständige Klassifikation + Routing-Logik aus
|
||
und gibt eine ``RoutingDecision`` zurück.
|
||
|
||
Der Adapter entscheidet dann selbst über:
|
||
- Weiterleitung der Kopie an den Zielraum
|
||
- Löschen des Originals (bei Meta-Fragen)
|
||
- Hinzufügen von Präfix-Text ([FALLBACK], [META-FRAGE])
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||
|
||
Returns:
|
||
RoutingDecision mit Kategorie, Zielraum, Konfidenz und Metadaten.
|
||
"""
|
||
if not self._initialized:
|
||
logger.warning(
|
||
"classify_and_route() called before initialize() — "
|
||
"returning catch-all decision"
|
||
)
|
||
return RoutingDecision(
|
||
category="FAKT",
|
||
target_room="", # Adapter soll selbst Catch-All verwenden
|
||
confidence=0.0,
|
||
is_catch_all=True,
|
||
)
|
||
|
||
decision = await self._router.route(text, origin_room_id)
|
||
|
||
# Update stats
|
||
self._stats["total"] += 1
|
||
if decision.is_meta:
|
||
self._stats["meta"] += 1
|
||
elif decision.is_unrouteable:
|
||
self._stats["classified"] += 1
|
||
# Store in documentation store — message is classified but
|
||
# the target room is not in our subscription list
|
||
stored = self._doc_store.store(
|
||
text=text,
|
||
category=decision.category,
|
||
confidence=decision.confidence,
|
||
reason=decision.unrouteable_reason,
|
||
)
|
||
logger.info(
|
||
"Unrouteable [%s] stored in doc_store: %s",
|
||
decision.category, stored,
|
||
)
|
||
elif decision.is_fallback:
|
||
self._stats["fallback"] += 1
|
||
elif decision.is_catch_all:
|
||
self._stats["catch_all"] += 1
|
||
else:
|
||
self._stats["classified"] += 1
|
||
|
||
logger.debug(
|
||
"Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s",
|
||
decision.category,
|
||
decision.confidence,
|
||
decision.target_room[:8] if decision.target_room else "none",
|
||
decision.is_meta,
|
||
decision.is_fallback,
|
||
decision.is_catch_all,
|
||
)
|
||
|
||
return decision
|
||
|
||
async def handle_and_forward(
|
||
self, text: str, origin_room_id: str, message_id: str = ""
|
||
) -> RoutingDecision:
|
||
"""Klassifiziere UND leite die Nachricht weiter (All-in-One).
|
||
|
||
Convenience-Methode für Adapter, die die Logik nicht selbst
|
||
implementieren wollen. Benötigt ``send_callback`` im Konstruktor.
|
||
|
||
Ablauf:
|
||
1. classify_and_route(text)
|
||
2. Wenn target_room != origin_room: Kopie an target_room senden
|
||
3. Bei Meta-Fragen: delete_original=True im Decision setzen
|
||
|
||
Args:
|
||
text: Nachrichtentext.
|
||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||
message_id: Rocket.Chat Nachrichten-ID (für Lösch-Operationen).
|
||
|
||
Returns:
|
||
RoutingDecision — der Adapter kann zusätzlich löschen/präfixen.
|
||
|
||
Raises:
|
||
RuntimeError: Wenn kein send_callback gesetzt wurde.
|
||
"""
|
||
if not self._send_callback:
|
||
raise RuntimeError(
|
||
"handle_and_forward() requires a send_callback. "
|
||
"Pass send_callback to ArchivarMessageHandler() constructor, "
|
||
"or use classify_and_route() + manual forwarding."
|
||
)
|
||
|
||
t_start: float = time.monotonic()
|
||
|
||
decision = await self.classify_and_route(text)
|
||
|
||
# If unrouteable, don't try to forward — message is already in doc_store
|
||
if decision.is_unrouteable:
|
||
return decision
|
||
|
||
# Only forward if the target differs from origin
|
||
if decision.target_room and decision.target_room != origin_room_id:
|
||
prefix = decision.prefix or ""
|
||
forwarded_text = f"{prefix}{text}" if prefix else text
|
||
|
||
try:
|
||
success = await self._send_callback(
|
||
decision.target_room, forwarded_text
|
||
)
|
||
if success:
|
||
logger.info(
|
||
"Forwarded [%s] to room %s (conf=%.3f)",
|
||
decision.category,
|
||
decision.target_room[:8],
|
||
decision.confidence,
|
||
)
|
||
else:
|
||
logger.error(
|
||
"Failed to forward [%s] to room %s",
|
||
decision.category,
|
||
decision.target_room[:8],
|
||
)
|
||
self._stats["errors"] += 1
|
||
self._stats["last_error"] = (
|
||
f"Send callback returned False for room "
|
||
f"{decision.target_room[:8]}"
|
||
)
|
||
except Exception as e:
|
||
logger.error(
|
||
"Exception forwarding [%s] to room %s: %s",
|
||
decision.category,
|
||
decision.target_room[:8],
|
||
e,
|
||
)
|
||
self._stats["errors"] += 1
|
||
self._stats["last_error"] = str(e)
|
||
|
||
# Update rolling average latency
|
||
elapsed_ms: float = (time.monotonic() - t_start) * 1000.0
|
||
self._stats["latencies"].append(elapsed_ms)
|
||
n: int = len(self._stats["latencies"])
|
||
if n > 0:
|
||
self._stats["avg_latency_ms"] = (
|
||
sum(self._stats["latencies"]) / n
|
||
)
|
||
|
||
return decision
|
||
|
||
# ── Statistics ──────────────────────────────────────────────────────
|
||
|
||
@property
|
||
def stats(self) -> Dict[str, int]:
|
||
"""Read-only copy of classification statistics."""
|
||
return dict(self._stats)
|
||
|
||
def reset_stats(self) -> None:
|
||
"""Reset statistics counters."""
|
||
self._stats = {
|
||
"total": 0,
|
||
"classified": 0,
|
||
"catch_all": 0,
|
||
"fallback": 0,
|
||
"meta": 0,
|
||
"errors": 0,
|
||
"avg_latency_ms": 0.0,
|
||
"last_error": None,
|
||
"latencies": [],
|
||
}
|
||
|
||
# ── Configuration ───────────────────────────────────────────────────
|
||
|
||
@property
|
||
def confidence_threshold(self) -> float:
|
||
"""Current confidence threshold."""
|
||
return self._router.confidence_threshold
|
||
|
||
def set_confidence_threshold(self, value: float) -> None:
|
||
"""Override confidence threshold at runtime."""
|
||
self._router.set_confidence_threshold(value)
|
||
|
||
@property
|
||
def is_initialized(self) -> bool:
|
||
"""True if handler is ready for classification."""
|
||
return self._initialized
|
||
|
||
@property
|
||
def classifier_ready(self) -> bool:
|
||
"""True if the embedding classifier is operational (not just fallback)."""
|
||
return self._classifier.is_initialized
|
||
|
||
def set_send_callback(self, callback: SendCallback) -> None:
|
||
"""Set or replace the send callback after construction.
|
||
|
||
Ermöglicht ``handle_and_forward()``-Nutzung auch wenn der Callback
|
||
erst nach der Konstruktion verfügbar ist (z.B. nach REST-Login).
|
||
|
||
Args:
|
||
callback: Async function ``(room_id, text) -> bool``.
|
||
"""
|
||
self._send_callback = callback
|
||
logger.debug("Send callback registered")
|
||
|
||
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||
"""Set the bot's current subscribed room IDs for routing validation.
|
||
|
||
When set, the router will ONLY forward messages to rooms in this list.
|
||
Messages targeting unsubscribed rooms are stored in the
|
||
DocumentationStore instead.
|
||
|
||
Call this after adapter.connect() when the subscription list is ready.
|
||
|
||
Args:
|
||
room_ids: List of Rocket.Chat room IDs the bot is currently
|
||
subscribed to. Pass None to disable validation.
|
||
"""
|
||
self._subscribed_room_ids_cache = set(room_ids) if room_ids else None
|
||
self._router.set_subscribed_room_ids(room_ids)
|
||
|
||
@property
|
||
def doc_store(self) -> DocumentationStore:
|
||
"""Documentation store for unrouteable messages."""
|
||
return self._doc_store
|