Files
Hermes_rocket.chat_Plugin/plugin/archivar/adapter_integration.py
T

684 lines
26 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.
"""
Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
in ``adapter.py`` dient. Sie kapselt IntentClassifier + BidirectionalRouter 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.should_route():
# Bidirektionales Routing
await self.archivar.move_message(room_id, decision.target_room, text, msg_id)
"""
from __future__ import annotations
import asyncio
import logging
import os
import time
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, Optional
from .classifier import (
ClassificationResult,
EmbeddingClient,
IntentClassifier,
LLMClient,
OllamaLLMClient,
)
from .config import (
CONFIDENCE_THRESHOLDS,
OLLAMA_CONFIG,
LLM_CONFIG,
BUTTON_TEMPLATES,
ARCHIVAR_STATE_PATH
)
from .doc_store import DocumentationStore
from .room_map import RoomMap, RoomMapValidationError
from .router import BidirectionalRouter, RoutingDecision
from .archivar_state import ArchivarState
logger = logging.getLogger(__name__)
# Callback-Signaturen
SendCallback = Callable[[str, str], Awaitable[bool]]
ButtonSendCallback = Callable[[str, str, dict], Awaitable[bool]]
class ArchivarMessageHandler:
"""Hauptklasse für die Archivar-Integration.
Kapselt IntentClassifier und BidirectionalRouter. 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,
button_send_callback: Optional[ButtonSendCallback] = None,
confidence_threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"],
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.
button_send_callback: Optionale async Callback-Funktion zum Senden von
Nachrichten mit Buttons via Rocket.Chat REST API. Signatur:
``async def send_with_buttons(room_id: str, text: str, buttons: dict) -> bool``.
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 ``IntentClassifier`` durchgereicht.
Ermöglicht Mocking/alternative Embedding-Backends.
llm_client: Optionales ``LLMClient``-Interface.
Wird an den ``IntentClassifier`` durchgereicht.
Ermöglicht Mocking/alternative LLM-Backends.
"""
self._send_callback = send_callback
self._button_send_callback = button_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 = IntentClassifier(
base_url=ollama_base_url,
embedding_client=embedding_client,
llm_client=llm_client
)
# Load RoomMap (try JSON first, fall back to legacy env vars)
self._room_map = self._load_room_map()
# Load ArchivarState (Persistenz-Layer)
self._state = ArchivarState(ARCHIVAR_STATE_PATH)
self._state.load()
# doc_store writes to fact_store_path from room_map
self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path)
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
self._subscribed_room_ids_cache: Optional[set] = None
self._router = BidirectionalRouter(self._room_map, self._classifier, self._state)
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
"onboarding_active": False, # Auto-Onboarding state
"clarifications_sent": 0, # Anzahl gesendeter Klärungsanfragen
}
# ── 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(os.path.expanduser("~/.hermes/hermes-agent/data/room-map.json"))
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="direct_question",
target_room="", # Adapter soll selbst Catch-All verwenden
confidence=0.0,
is_catch_all=True,
stay_in_room=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
elif decision.needs_clarification:
# Sende Klärungsanfrage mit Buttons
await self._send_clarify(origin_room_id, text, decision)
else:
self._stats["classified"] += 1
logger.debug(
"Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s needs_clarify=%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,
decision.needs_clarification,
)
return decision
async def _send_clarify(self, room_id: str, text: str, decision: RoutingDecision) -> bool:
"""Sende eine Klärungsanfrage mit nativen Rocket.Chat Action-Buttons.
Button-Garantie: REST-Pfad first, Text-Fallback nur bei Fehler.
Args:
room_id: Zielraum-ID
text: Originalnachricht
decision: Routing-Entscheidung
Returns:
True wenn erfolgreich gesendet, False bei Fehler
"""
try:
# Hole Button-Template
template = BUTTON_TEMPLATES.get("clarify_intent", {})
if not template:
logger.error("No clarify_intent button template found")
return False
message_text = template.get("text", "Bitte klären Sie die Absicht dieser Nachricht:")
buttons = template.get("actions", [])
# REST-Pfad Vorrang (Button-Garantie)
if self._button_send_callback:
try:
success = await self._button_send_callback(room_id, message_text, {"actions": buttons})
if success:
self._stats["clarifications_sent"] += 1
logger.info("Sent clarification with buttons to room %s", room_id[:8])
return True
else:
logger.warning("Button send callback returned False for room %s", room_id[:8])
except Exception as e:
logger.warning("Button send failed: %s - falling back to text", e)
# Text-Fallback nur bei HTTP-Fehler
fallback_text = f"{message_text}\n\nOptionen:\n"
for i, action in enumerate(buttons, 1):
fallback_text += f"{i}. {action['text']} ({action['type']})\n"
if self._send_callback:
try:
success = await self._send_callback(room_id, fallback_text)
if success:
self._stats["clarifications_sent"] += 1
logger.warning("Sent clarification with TEXT fallback to room %s", room_id[:8])
return True
else:
logger.error("Text fallback send failed for room %s", room_id[:8])
except Exception as e:
logger.error("Text fallback send exception: %s", e)
# Beide Methoden fehlgeschlagen
logger.error("Failed to send clarification to room %s (no working method)", room_id[:8])
self._stats["errors"] += 1
self._stats["last_error"] = f"Failed to send clarification to room {room_id[:8]}"
return False
except Exception as e:
logger.error("Exception in _send_clarify: %s", e)
self._stats["errors"] += 1
self._stats["last_error"] = str(e)
return False
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
# Handle bidirektionales Routing
if decision.should_route() and decision.target_room and decision.target_room != origin_room_id:
await self.move_message(origin_room_id, decision.target_room, text, message_id, decision)
# 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
async def move_message(
self,
source_room: str,
target_room: str,
message: str,
message_id: str,
decision: RoutingDecision
) -> bool:
"""Verschiebe eine Nachricht bidirektional zwischen Räumen.
Implementiert den vollständigen bidirektionalen Routing-Flow:
1. Quellkanal-Post: "📋 Bearbeite ich in #ziel — [Link]"
2. Vollständige Nachricht + Kontext im Zielkanal
3. Agent-Antwort im Zielkanal
4. Nach Abschluss: Summary zurück in Quellkanal
Args:
source_room: ID des Ursprungsraums
target_room: ID des Zielraums
message: Die zu verschiebende Nachricht
message_id: ID der Originalnachricht
decision: Routing-Entscheidung
Returns:
True wenn erfolgreich, False bei Fehler
"""
try:
if not self._send_callback:
logger.error("No send callback available for bidirectional routing")
return False
# 1. Quellkanal-Post: "📋 Bearbeite ich in #ziel — [Link]"
if decision.source_room_notification:
try:
await self._send_callback(source_room, decision.source_room_notification)
except Exception as e:
logger.warning("Failed to send source room notification: %s", e)
# 2. Vollständige Nachricht + Kontext im Zielkanal
try:
await self._send_callback(target_room, message)
except Exception as e:
logger.error("Failed to send message to target room: %s", e)
return False
# 3. Agent-Antwort im Zielkanal (wird vom Adapter behandelt)
# 4. Nach Abschluss: Summary zurück in Quellkanal
# (Wird vom Adapter nach der Antwort gesendet)
logger.info(
"Bidirectional move completed: %s → %s",
source_room[:8], target_room[:8]
)
return True
except Exception as e:
logger.error("Exception in move_message: %s", e)
self._stats["errors"] += 1
self._stats["last_error"] = str(e)
return False
async def handle_clarification_response(
self,
room_id: str,
user_id: str,
intent_type: str
) -> bool:
"""Behandle eine Benutzerantwort auf eine Klärungsanfrage.
Speichert die Benutzerentscheidung im Persistenz-Layer.
Args:
room_id: Raum-ID
user_id: Benutzer-ID
intent_type: Gewählter Intent-Typ ("direct_question", "smalltalk", "work_order")
Returns:
True wenn erfolgreich gespeichert, False bei Fehler
"""
try:
# Speichere die Entscheidung im Persistenz-Layer
# Für "always" oder "never_route" speichern wir eine persistente Entscheidung
if intent_type in ("direct_question", "smalltalk"):
# Diese Nachrichten sollen immer im Raum bleiben
success = self._state.set_room_state(room_id, "always", user_id)
if success:
logger.info("Set room %s to always stay for user %s", room_id[:8], user_id[:8])
return success
elif intent_type == "work_order":
# Für work_orders verwenden wir den Standard-Routing-Algorithmus
# Keine persistente Entscheidung nötig
return True
else:
logger.warning("Unknown intent type for clarification: %s", intent_type)
return False
except Exception as e:
logger.error("Exception in handle_clarification_response: %s", e)
self._stats["errors"] += 1
self._stats["last_error"] = str(e)
return False
# ── 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": [],
"onboarding_active": False,
"clarifications_sent": 0,
}
def check_room_map_completeness(self, subscribed_rooms: dict) -> list[dict]:
"""Vergleicht subscribed rooms mit room-map.json.
Args:
subscribed_rooms: Mapping von room_id → {"name": str, "type": str} (vom Adapter)
Returns:
Liste fehlender Räume: [{"room_id": "...", "name": "#Raum"}]
Leere Liste = Map vollständig.
"""
# Filter: Nur Räume mit type in ("c", "p") berücksichtigen
relevant_rooms = {
rid: info for rid, info in subscribed_rooms.items()
if info.get("type") in ("c", "p")
}
# Single-Room-Regel: Wenn nur 1 relevanter Raum existiert und dieser
# nicht in der Map ist → automatisch als catch_all eintragen
if len(relevant_rooms) == 1:
single_room_id = list(relevant_rooms.keys())[0]
if single_room_id not in self._room_map.rooms:
# Automatisch als catch_all eintragen
room_info = relevant_rooms[single_room_id]
self._room_map.add_or_update_room(
room_id=single_room_id,
name=room_info["name"],
theme="Automatisch zugewiesener Catch-All-Raum",
keywords=[],
catch_all=True
)
# Speichern und neu laden
RoomMap.save(self._room_map, Path(os.path.expanduser("~/.hermes/hermes-agent/data/room-map.json")))
self._room_map.reload()
logger.info("Single room detected — auto-assigned as catch_all: %s", room_info["name"])
return [] # Keine weiteren Maßnahmen nötig
# Normale Prüfung: Welche relevanten Räume fehlen in der Map?
missing = []
for room_id, room_info in relevant_rooms.items():
if room_id not in self._room_map.rooms:
missing.append({
"room_id": room_id,
"name": room_info["name"]
})
return missing
# ── Configuration ───────────────────────────────────────────────────
@property
def confidence_threshold(self) -> float:
"""Current confidence threshold."""
return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
@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_button_send_callback(self, callback: ButtonSendCallback) -> None:
"""Set or replace the button send callback after construction.
Args:
callback: Async function ``(room_id, text, buttons) -> bool``.
"""
self._button_send_callback = callback
logger.debug("Button 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
@property
def state(self) -> ArchivarState:
"""Archivar state for persistent room decisions."""
return self._state