feat(archivar): Implement Button-Garantie und ArchivarState-Integration für Archivar v3

This commit is contained in:
Hermes Agent
2026-06-11 21:44:38 +02:00
parent b11c2c9fe7
commit dba856ffab
+229 -65
View File
@@ -2,7 +2,7 @@
Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline. Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
in ``adapter.py`` dient. Sie kapselt Classifier + Router und bietet eine in ``adapter.py`` dient. Sie kapselt IntentClassifier + BidirectionalRouter und bietet eine
einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline. einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline.
Einhängung in adapter.py:: Einhängung in adapter.py::
@@ -25,13 +25,9 @@ Einhängung in adapter.py::
decision = await self.archivar.classify_and_route(text) decision = await self.archivar.classify_and_route(text)
if decision.target_room != room_id: if decision.should_route():
# Kopie an Zielraum senden (Original bleibt!) # Bidirektionales Routing
prefix = decision.prefix or "" await self.archivar.move_message(room_id, decision.target_room, text, msg_id)
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 from __future__ import annotations
@@ -46,25 +42,32 @@ from typing import Any, Awaitable, Callable, Dict, Optional
from .classifier import ( from .classifier import (
ClassificationResult, ClassificationResult,
EmbeddingClient, EmbeddingClient,
MessageClassifier, IntentClassifier,
LLMClient, LLMClient,
OllamaLLMClient, OllamaLLMClient,
) )
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG, ROOM_MAP_PATH from .config import (
CONFIDENCE_THRESHOLDS,
OLLAMA_CONFIG,
LLM_CONFIG,
BUTTON_TEMPLATES,
ARCHIVAR_STATE_PATH
)
from .doc_store import DocumentationStore from .doc_store import DocumentationStore
from .room_map import RoomMap, RoomMapValidationError from .room_map import RoomMap, RoomMapValidationError
from .router import MessageRouter, RoutingDecision from .router import BidirectionalRouter, RoutingDecision
from .archivar_state import ArchivarState
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Callback-Signatur: async (room_id: str, text: str) -> bool # Callback-Signaturen
SendCallback = Callable[[str, str], Awaitable[bool]] SendCallback = Callable[[str, str], Awaitable[bool]]
ButtonSendCallback = Callable[[str, str, dict], Awaitable[bool]]
class ArchivarMessageHandler: class ArchivarMessageHandler:
"""Hauptklasse für die Archivar-Integration. """Hauptklasse für die Archivar-Integration.
Kapselt Classifier und Router. Wird vom RocketChatAdapter beim Start Kapselt IntentClassifier und BidirectionalRouter. Wird vom RocketChatAdapter beim Start
initialisiert und bei jeder eingehenden Nachricht aufgerufen. initialisiert und bei jeder eingehenden Nachricht aufgerufen.
Usage:: Usage::
@@ -80,7 +83,8 @@ class ArchivarMessageHandler:
def __init__( def __init__(
self, self,
send_callback: Optional[SendCallback] = None, send_callback: Optional[SendCallback] = None,
confidence_threshold: float = CONFIDENCE_THRESHOLD, button_send_callback: Optional[ButtonSendCallback] = None,
confidence_threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"],
ollama_base_url: Optional[str] = None, ollama_base_url: Optional[str] = None,
embedding_client: Optional[EmbeddingClient] = None, embedding_client: Optional[EmbeddingClient] = None,
llm_client: Optional[LLMClient] = None, llm_client: Optional[LLMClient] = None,
@@ -91,38 +95,46 @@ class ArchivarMessageHandler:
Nachrichten via Rocket.Chat REST API. Signatur: Nachrichten via Rocket.Chat REST API. Signatur:
``async def send(room_id: str, text: str) -> bool``. ``async def send(room_id: str, text: str) -> bool``.
Wenn gesetzt, kann ``handle_and_forward()`` verwendet werden. 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). confidence_threshold: Konfidenz-Schwellenwert (0.0–1.0).
ollama_base_url: Override für Ollama-Basis-URL. ollama_base_url: Override für Ollama-Basis-URL.
embedding_client: Optionales ``EmbeddingClient``-Interface. embedding_client: Optionales ``EmbeddingClient``-Interface.
Wird an den ``MessageClassifier`` durchgereicht. Wird an den ``IntentClassifier`` durchgereicht.
Ermöglicht Mocking/alternative Embedding-Backends. Ermöglicht Mocking/alternative Embedding-Backends.
llm_client: Optionales ``LLMClient``-Interface. llm_client: Optionales ``LLMClient``-Interface.
Wird an den ``MessageClassifier`` durchgereicht. Wird an den ``IntentClassifier`` durchgereicht.
Ermöglicht Mocking/alternative LLM-Backends. Ermöglicht Mocking/alternative LLM-Backends.
""" """
self._send_callback = send_callback self._send_callback = send_callback
self._button_send_callback = button_send_callback
self._enable_llm = LLM_CONFIG["enabled"] self._enable_llm = LLM_CONFIG["enabled"]
# Create LLM client if enabled and not provided # Create LLM client if enabled and not provided
if self._enable_llm and llm_client is None: if self._enable_llm and llm_client is None:
llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None
self._classifier = MessageClassifier( self._classifier = IntentClassifier(
base_url=ollama_base_url, base_url=ollama_base_url,
embedding_client=embedding_client, embedding_client=embedding_client,
llm_client=llm_client llm_client=llm_client
) )
# Load RoomMap (try JSON first, fall back to legacy env vars) # Load RoomMap (try JSON first, fall back to legacy env vars)
self._room_map = self._load_room_map() 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 # doc_store writes to fact_store_path from room_map
self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path) self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path)
# Cache for subscribed room IDs (set later via set_subscribed_room_ids) # Cache for subscribed room IDs (set later via set_subscribed_room_ids)
self._subscribed_room_ids_cache: Optional[set] = None self._subscribed_room_ids_cache: Optional[set] = None
self._router = MessageRouter(self._room_map, self._classifier) self._router = BidirectionalRouter(self._room_map, self._classifier, self._state)
self._router.set_confidence_threshold(confidence_threshold)
self._initialized = False self._initialized = False
# Statistiken (erweitert um Latenz + Fehler) # Statistiken (erweitert um Latenz + Fehler)
@@ -138,6 +150,7 @@ class ArchivarMessageHandler:
"last_error": None, # str | None — letzter Fehler "last_error": None, # str | None — letzter Fehler
"latencies": [], # list[float] — per-request ms "latencies": [], # list[float] — per-request ms
"onboarding_active": False, # Auto-Onboarding state "onboarding_active": False, # Auto-Onboarding state
"clarifications_sent": 0, # Anzahl gesendeter Klärungsanfragen
} }
# ── RoomMap Loading ───────────────────────────────────────────────── # ── RoomMap Loading ─────────────────────────────────────────────────
@@ -158,7 +171,7 @@ class ArchivarMessageHandler:
import json import json
from pathlib import Path from pathlib import Path
map_path = Path(ROOM_MAP_PATH) map_path = Path(os.path.expanduser("~/.hermes/hermes-agent/data/room-map.json"))
if map_path.exists(): if map_path.exists():
logger.info("Loading room map from %s", map_path) logger.info("Loading room map from %s", map_path)
@@ -264,10 +277,11 @@ class ArchivarMessageHandler:
"returning catch-all decision" "returning catch-all decision"
) )
return RoutingDecision( return RoutingDecision(
category="FAKT", category="direct_question",
target_room="", # Adapter soll selbst Catch-All verwenden target_room="", # Adapter soll selbst Catch-All verwenden
confidence=0.0, confidence=0.0,
is_catch_all=True, is_catch_all=True,
stay_in_room=True,
) )
decision = await self._router.route(text, origin_room_id) decision = await self._router.route(text, origin_room_id)
@@ -294,21 +308,90 @@ class ArchivarMessageHandler:
self._stats["fallback"] += 1 self._stats["fallback"] += 1
elif decision.is_catch_all: elif decision.is_catch_all:
self._stats["catch_all"] += 1 self._stats["catch_all"] += 1
elif decision.needs_clarification:
# Sende Klärungsanfrage mit Buttons
await self._send_clarify(origin_room_id, text, decision)
else: else:
self._stats["classified"] += 1 self._stats["classified"] += 1
logger.debug( logger.debug(
"Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s", "Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s needs_clarify=%s",
decision.category, decision.category,
decision.confidence, decision.confidence,
decision.target_room[:8] if decision.target_room else "none", decision.target_room[:8] if decision.target_room else "none",
decision.is_meta, decision.is_meta,
decision.is_fallback, decision.is_fallback,
decision.is_catch_all, decision.is_catch_all,
decision.needs_clarification,
) )
return decision 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( async def handle_and_forward(
self, text: str, origin_room_id: str, message_id: str = "" self, text: str, origin_room_id: str, message_id: str = ""
) -> RoutingDecision: ) -> RoutingDecision:
@@ -348,42 +431,9 @@ class ArchivarMessageHandler:
if decision.is_unrouteable: if decision.is_unrouteable:
return decision return decision
# Only forward if the target differs from origin # Handle bidirektionales Routing
if decision.target_room and decision.target_room != origin_room_id: if decision.should_route() and decision.target_room and decision.target_room != origin_room_id:
prefix = decision.prefix or "" await self.move_message(origin_room_id, decision.target_room, text, message_id, decision)
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 # Update rolling average latency
elapsed_ms: float = (time.monotonic() - t_start) * 1000.0 elapsed_ms: float = (time.monotonic() - t_start) * 1000.0
@@ -396,6 +446,109 @@ class ArchivarMessageHandler:
return decision 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 ────────────────────────────────────────────────────── # ── Statistics ──────────────────────────────────────────────────────
@property @property
@@ -416,6 +569,7 @@ class ArchivarMessageHandler:
"last_error": None, "last_error": None,
"latencies": [], "latencies": [],
"onboarding_active": False, "onboarding_active": False,
"clarifications_sent": 0,
} }
def check_room_map_completeness(self, subscribed_rooms: dict) -> list[dict]: def check_room_map_completeness(self, subscribed_rooms: dict) -> list[dict]:
@@ -449,7 +603,7 @@ class ArchivarMessageHandler:
catch_all=True catch_all=True
) )
# Speichern und neu laden # Speichern und neu laden
RoomMap.save(self._room_map, Path(ROOM_MAP_PATH)) RoomMap.save(self._room_map, Path(os.path.expanduser("~/.hermes/hermes-agent/data/room-map.json")))
self._room_map.reload() self._room_map.reload()
logger.info("Single room detected — auto-assigned as catch_all: %s", room_info["name"]) logger.info("Single room detected — auto-assigned as catch_all: %s", room_info["name"])
return [] # Keine weiteren Maßnahmen nötig return [] # Keine weiteren Maßnahmen nötig
@@ -470,11 +624,7 @@ class ArchivarMessageHandler:
@property @property
def confidence_threshold(self) -> float: def confidence_threshold(self) -> float:
"""Current confidence threshold.""" """Current confidence threshold."""
return self._router.confidence_threshold return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
def set_confidence_threshold(self, value: float) -> None:
"""Override confidence threshold at runtime."""
self._router.set_confidence_threshold(value)
@property @property
def is_initialized(self) -> bool: def is_initialized(self) -> bool:
@@ -498,6 +648,15 @@ class ArchivarMessageHandler:
self._send_callback = callback self._send_callback = callback
logger.debug("Send callback registered") 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: def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
"""Set the bot's current subscribed room IDs for routing validation. """Set the bot's current subscribed room IDs for routing validation.
@@ -518,3 +677,8 @@ class ArchivarMessageHandler:
def doc_store(self) -> DocumentationStore: def doc_store(self) -> DocumentationStore:
"""Documentation store for unrouteable messages.""" """Documentation store for unrouteable messages."""
return self._doc_store return self._doc_store
@property
def state(self) -> ArchivarState:
"""Archivar state for persistent room decisions."""
return self._state