feat: Archivar delivery + install.sh v2.2 — full function set
- Add archivar/ submodule to plugin/ (5 files, relative imports) - Update adapter.py with relative Archivar import from .archivar.adapter_integration - install.sh: fix --non-interactive env-var reading (Z.316-318, Bug #7) - install.sh: recursive file copy (was 4 flat files, now entire plugin/ tree incl. submodules) - install.sh: Ollama presence check + nomic-embed-text pull - install.sh: write OLLAMA_BASE_URL to rocketchat.env - install.sh: add new message keys (collama_check, nomic_pull, nomic_ok, nomic_fail, copied) Closes: Archivar delivery gap (2026-06-03) Reviewed-by: Bernd (Advisor)
This commit is contained in:
+57
-6
@@ -42,6 +42,13 @@ load_lang() {
|
||||
[copying]="📁 Copying plugin files…"
|
||||
[env_written]="🔑 Credentials written to %s"
|
||||
[config_updated]="⚙️ config.yaml updated"
|
||||
[copied]="📁 Copied %d plugin files"
|
||||
[ollama_check]="🔍 Checking Ollama..."
|
||||
[ollama_missing]="⚠️ Ollama not found. Install: curl -fsSL https://ollama.com/install.sh | sh"
|
||||
[nomic_pull]="📥 Pulling nomic-embed-text (274 MB)..."
|
||||
[nomic_ok]="✅ nomic-embed-text ready"
|
||||
[nomic_fail]="⚠️ nomic-embed-text pull failed — Archivar will use fallback mode"
|
||||
[ollama_ok]="✅ Ollama ready"
|
||||
[service_installed]="⚡ Gateway service installed"
|
||||
[restarting]="🔄 Restarting gateway…"
|
||||
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
||||
@@ -78,6 +85,13 @@ load_lang() {
|
||||
[copying]="📁 Kopiere Plugin-Dateien…"
|
||||
[env_written]="🔑 Zugangsdaten gespeichert in %s"
|
||||
[config_updated]="⚙️ config.yaml aktualisiert"
|
||||
[copied]="📁 %d Plugin-Dateien kopiert"
|
||||
[ollama_check]="🔍 Prüfe Ollama..."
|
||||
[ollama_missing]="⚠️ Ollama nicht gefunden. Installation: curl -fsSL https://ollama.com/install.sh | sh"
|
||||
[nomic_pull]="📥 Lade nomic-embed-text herunter (274 MB)..."
|
||||
[nomic_ok]="✅ nomic-embed-text bereit"
|
||||
[nomic_fail]="⚠️ nomic-embed-text Download fehlgeschlagen — Archivar nutzt Fallback-Modus"
|
||||
[ollama_ok]="✅ Ollama bereit"
|
||||
[service_installed]="⚡ Gateway-Service installiert"
|
||||
[restarting]="🔄 Starte Gateway neu…"
|
||||
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
||||
@@ -314,8 +328,11 @@ fi
|
||||
|
||||
# ─── Non-interactive mode ─────────────────────────────────
|
||||
if $NONINTERACTIVE; then
|
||||
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}"
|
||||
RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
|
||||
# Read from environment variables (NOT local — respect what install.sh caller exports)
|
||||
RC_URL="${RC_URL:-${ROCKETCHAT_BASE_URL:-}}"
|
||||
RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}"
|
||||
RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}"
|
||||
RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-${ROCKETCHAT_ROOM_NAME:-}}"
|
||||
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
||||
msg env_required; exit 1
|
||||
fi
|
||||
@@ -357,16 +374,50 @@ EOF
|
||||
chmod 600 "$ENV_FILE"
|
||||
msg env_written "$ENV_FILE"
|
||||
|
||||
# ─── Ollama Check ─────────────────────────────────────────
|
||||
OLLAMA_BASE_URL="${OLLAMA_BASE_URL:-http://localhost:11434}"
|
||||
msg ollama_check
|
||||
if command -v ollama >/dev/null 2>&1; then
|
||||
msg ollama_ok
|
||||
# nomic-embed-text laden falls nicht vorhanden
|
||||
if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then
|
||||
msg nomic_pull
|
||||
if ollama pull nomic-embed-text 2>/dev/null; then
|
||||
msg nomic_ok
|
||||
else
|
||||
msg nomic_fail
|
||||
fi
|
||||
else
|
||||
msg nomic_ok
|
||||
fi
|
||||
else
|
||||
msg ollama_missing
|
||||
fi
|
||||
|
||||
# OLLAMA_BASE_URL in rocketchat.env ergänzen
|
||||
if ! grep -q 'OLLAMA_BASE_URL' "$ENV_FILE" 2>/dev/null; then
|
||||
echo "export OLLAMA_BASE_URL=\"${OLLAMA_BASE_URL}\"" >> "$ENV_FILE"
|
||||
fi
|
||||
|
||||
# ─── Copy plugin files ────────────────────────────────────
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
||||
mkdir -p "$PLUGIN_DST"
|
||||
|
||||
for f in plugin.yaml __init__.py adapter.py tools.py; do
|
||||
if [ -f "$SCRIPT_DIR/plugin/$f" ]; then
|
||||
cp "$SCRIPT_DIR/plugin/$f" "$PLUGIN_DST/$f"
|
||||
fi
|
||||
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||
if [ -d "$SCRIPT_DIR/plugin" ]; then
|
||||
# Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören
|
||||
# Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur)
|
||||
find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' \
|
||||
| while read -r src; do
|
||||
rel="${src#$SCRIPT_DIR/plugin/}"
|
||||
dst="$PLUGIN_DST/$rel"
|
||||
mkdir -p "$(dirname "$dst")"
|
||||
cp "$src" "$dst"
|
||||
done
|
||||
copied_count=$(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||
msg copied "$copied_count"
|
||||
fi
|
||||
|
||||
# ─── Patch config.yaml ────────────────────────────────────
|
||||
CONFIG="$HOME/.hermes/config.yaml"
|
||||
|
||||
+501
-758
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,30 @@
|
||||
1|"""
|
||||
2|Archivar-Modul: Klassifikation und Routing von Nachrichten im Rocket.Chat Plugin.
|
||||
3|
|
||||
4|Bietet embedding-basierte Klassifikation (nomic-embed-text via Ollama)
|
||||
5|für die Kategorien FAKT, FRAGE, ALARM und leitet Nachrichtenkopien an
|
||||
6|konfigurierte Zielräume weiter.
|
||||
7|
|
||||
8|Architektur: Siehe /home/bernd/Archivar_Architecture.md
|
||||
9|"""
|
||||
10|
|
||||
11|from .classifier import MessageClassifier, ClassificationResult, EmbeddingClient, OllamaEmbeddingClient
|
||||
12|from .config import ROOM_MAPPING, CATCH_ALL_ROOM, CATEGORY_TEXTS, OLLAMA_CONFIG, CONFIDENCE_THRESHOLD
|
||||
13|from .router import MessageRouter, RoutingDecision
|
||||
14|from .adapter_integration import ArchivarMessageHandler
|
||||
15|
|
||||
16|__all__ = [
|
||||
17| "MessageClassifier",
|
||||
18| "ClassificationResult",
|
||||
19| "EmbeddingClient",
|
||||
20| "OllamaEmbeddingClient",
|
||||
21| "ROOM_MAPPING",
|
||||
22| "CATCH_ALL_ROOM",
|
||||
23| "CATEGORY_TEXTS",
|
||||
24| "OLLAMA_CONFIG",
|
||||
25| "CONFIDENCE_THRESHOLD",
|
||||
26| "MessageRouter",
|
||||
27| "RoutingDecision",
|
||||
28| "ArchivarMessageHandler",
|
||||
29|]
|
||||
30|
|
||||
@@ -0,0 +1,342 @@
|
||||
1|"""
|
||||
2|Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
|
||||
3|
|
||||
4|Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
|
||||
5|in ``adapter.py`` dient. Sie kapselt Classifier + Router und bietet eine
|
||||
6|einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline.
|
||||
7|
|
||||
8|Einhängung in adapter.py::
|
||||
9|
|
||||
10| from .adapter_integration import ArchivarMessageHandler
|
||||
11|
|
||||
12| class RocketChatAdapter(BasePlatformAdapter):
|
||||
13| def __init__(self, config):
|
||||
14| ...
|
||||
15| self.archivar = ArchivarMessageHandler()
|
||||
16|
|
||||
17| async def connect(self):
|
||||
18| ...
|
||||
19| await self.archivar.initialize()
|
||||
20|
|
||||
21| async def _process_incoming(self, msg_obj):
|
||||
22| ...
|
||||
23| text = msg_obj.get("msg", "")
|
||||
24| room_id = msg_obj.get("rid", "")
|
||||
25|
|
||||
26| decision = await self.archivar.classify_and_route(text)
|
||||
27|
|
||||
28| if decision.target_room != room_id:
|
||||
29| # Kopie an Zielraum senden (Original bleibt!)
|
||||
30| prefix = decision.prefix or ""
|
||||
31| await self._send_to_room(decision.target_room, f"{prefix}{text}")
|
||||
32|
|
||||
33| if decision.delete_original:
|
||||
34| await self._delete_message(room_id, msg_id)
|
||||
35|"""
|
||||
36|
|
||||
37|from __future__ import annotations
|
||||
38|
|
||||
39|import asyncio
|
||||
40|import logging
|
||||
41|import time
|
||||
42|from typing import Any, Awaitable, Callable, Dict, Optional
|
||||
43|
|
||||
44|from .classifier import (
|
||||
45| ClassificationResult,
|
||||
46| EmbeddingClient,
|
||||
47| MessageClassifier,
|
||||
48|)
|
||||
49|from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG
|
||||
50|from .router import MessageRouter, RoutingDecision
|
||||
51|
|
||||
52|logger = logging.getLogger(__name__)
|
||||
53|
|
||||
54|# Callback-Signatur: async (room_id: str, text: str) -> bool
|
||||
55|SendCallback = Callable[[str, str], Awaitable[bool]]
|
||||
56|
|
||||
57|
|
||||
58|class ArchivarMessageHandler:
|
||||
59| """Hauptklasse für die Archivar-Integration.
|
||||
60|
|
||||
61| Kapselt Classifier und Router. Wird vom RocketChatAdapter beim Start
|
||||
62| initialisiert und bei jeder eingehenden Nachricht aufgerufen.
|
||||
63|
|
||||
64| Usage::
|
||||
65|
|
||||
66| handler = ArchivarMessageHandler()
|
||||
67| await handler.initialize() # einmalig beim Adapter-Start
|
||||
68|
|
||||
69| # Bei jeder Nachricht:
|
||||
70| decision = await handler.classify_and_route(text)
|
||||
71| # decision.target_room enthält die Zielraum-ID
|
||||
72| """
|
||||
73|
|
||||
74| def __init__(
|
||||
75| self,
|
||||
76| send_callback: Optional[SendCallback] = None,
|
||||
77| confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
||||
78| ollama_base_url: Optional[str] = None,
|
||||
79| embedding_client: Optional[EmbeddingClient] = None,
|
||||
80| ) -> None:
|
||||
81| """
|
||||
82| Args:
|
||||
83| send_callback: Optionale async Callback-Funktion zum Senden von
|
||||
84| Nachrichten via Rocket.Chat REST API. Signatur:
|
||||
85| ``async def send(room_id: str, text: str) -> bool``.
|
||||
86| Wenn gesetzt, kann ``handle_and_forward()`` verwendet werden.
|
||||
87| confidence_threshold: Konfidenz-Schwellenwert (0.0–1.0).
|
||||
88| ollama_base_url: Override für Ollama-Basis-URL.
|
||||
89| embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||
90| Wird an den ``MessageClassifier`` durchgereicht.
|
||||
91| Ermöglicht Mocking/alternative Embedding-Backends.
|
||||
92| """
|
||||
93| self._send_callback = send_callback
|
||||
94| self._classifier = MessageClassifier(
|
||||
95| base_url=ollama_base_url, embedding_client=embedding_client
|
||||
96| )
|
||||
97| self._router = MessageRouter(self._classifier)
|
||||
98| self._router.set_confidence_threshold(confidence_threshold)
|
||||
99| self._initialized = False
|
||||
100|
|
||||
101| # Statistiken (erweitert um Latenz + Fehler)
|
||||
102| self._stats: Dict[str, Any] = {
|
||||
103| "total": 0,
|
||||
104| "classified": 0,
|
||||
105| "catch_all": 0,
|
||||
106| "fallback": 0,
|
||||
107| "meta": 0,
|
||||
108| "errors": 0,
|
||||
109| "avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
||||
110| "last_error": None, # str | None — letzter Fehler
|
||||
111| "latencies": [], # list[float] — per-request ms
|
||||
112| }
|
||||
113|
|
||||
114| # ── Public API ──────────────────────────────────────────────────────
|
||||
115|
|
||||
116| async def initialize(self) -> bool:
|
||||
117| """Einmalige Initialisierung: Pre-compute Kategorie-Vektoren.
|
||||
118|
|
||||
119| Muss vor dem ersten ``classify_and_route()``-Aufruf aufgerufen werden.
|
||||
120| Safe für mehrfache Aufrufe — no-op wenn bereits initialisiert.
|
||||
121|
|
||||
122| Returns:
|
||||
123| True wenn die Initialisierung erfolgreich war (Classifier bereit).
|
||||
124| False wenn Ollama nicht erreichbar ist → Fallback-Modus aktiv.
|
||||
125| """
|
||||
126| if self._initialized:
|
||||
127| return True
|
||||
128|
|
||||
129| logger.info("Initializing ArchivarMessageHandler...")
|
||||
130| success = await self._classifier.initialize()
|
||||
131|
|
||||
132| if success:
|
||||
133| self._initialized = True
|
||||
134| logger.info(
|
||||
135| "ArchivarMessageHandler ready: %d categories, model=%s",
|
||||
136| self._classifier.category_count,
|
||||
137| OLLAMA_CONFIG["model"],
|
||||
138| )
|
||||
139| else:
|
||||
140| logger.warning(
|
||||
141| "ArchivarMessageHandler initialized in FALLBACK mode — "
|
||||
142| "Ollama unavailable at %s. Will use keyword heuristics.",
|
||||
143| OLLAMA_CONFIG["base_url"],
|
||||
144| )
|
||||
145| # Mark as initialized anyway — the classifier will return None
|
||||
146| # and the router will use keyword fallback.
|
||||
147| self._initialized = True
|
||||
148|
|
||||
149| return success
|
||||
150|
|
||||
151| async def classify_and_route(self, text: str) -> RoutingDecision:
|
||||
152| """Klassifiziere eine Nachricht und ermittle den Zielraum.
|
||||
153|
|
||||
154| Dies ist die primäre Methode für die adapter.py-Integration.
|
||||
155| Sie führt die vollständige Klassifikation + Routing-Logik aus
|
||||
156| und gibt eine ``RoutingDecision`` zurück.
|
||||
157|
|
||||
158| Der Adapter entscheidet dann selbst über:
|
||||
159| - Weiterleitung der Kopie an den Zielraum
|
||||
160| - Löschen des Originals (bei Meta-Fragen)
|
||||
161| - Hinzufügen von Präfix-Text ([FALLBACK], [META-FRAGE])
|
||||
162|
|
||||
163| Args:
|
||||
164| text: Der Nachrichtentext.
|
||||
165|
|
||||
166| Returns:
|
||||
167| RoutingDecision mit Kategorie, Zielraum, Konfidenz und Metadaten.
|
||||
168| """
|
||||
169| if not self._initialized:
|
||||
170| logger.warning(
|
||||
171| "classify_and_route() called before initialize() — "
|
||||
172| "returning catch-all decision"
|
||||
173| )
|
||||
174| return RoutingDecision(
|
||||
175| category="FAKT",
|
||||
176| target_room="", # Adapter soll selbst Catch-All verwenden
|
||||
177| confidence=0.0,
|
||||
178| is_catch_all=True,
|
||||
179| )
|
||||
180|
|
||||
181| decision = await self._router.route(text)
|
||||
182|
|
||||
183| # Update stats
|
||||
184| self._stats["total"] += 1
|
||||
185| if decision.is_meta:
|
||||
186| self._stats["meta"] += 1
|
||||
187| elif decision.is_fallback:
|
||||
188| self._stats["fallback"] += 1
|
||||
189| elif decision.is_catch_all:
|
||||
190| self._stats["catch_all"] += 1
|
||||
191| else:
|
||||
192| self._stats["classified"] += 1
|
||||
193|
|
||||
194| logger.debug(
|
||||
195| "Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s",
|
||||
196| decision.category,
|
||||
197| decision.confidence,
|
||||
198| decision.target_room[:8] if decision.target_room else "none",
|
||||
199| decision.is_meta,
|
||||
200| decision.is_fallback,
|
||||
201| decision.is_catch_all,
|
||||
202| )
|
||||
203|
|
||||
204| return decision
|
||||
205|
|
||||
206| async def handle_and_forward(
|
||||
207| self, text: str, origin_room_id: str, message_id: str = ""
|
||||
208| ) -> RoutingDecision:
|
||||
209| """Klassifiziere UND leite die Nachricht weiter (All-in-One).
|
||||
210|
|
||||
211| Convenience-Methode für Adapter, die die Logik nicht selbst
|
||||
212| implementieren wollen. Benötigt ``send_callback`` im Konstruktor.
|
||||
213|
|
||||
214| Ablauf:
|
||||
215| 1. classify_and_route(text)
|
||||
216| 2. Wenn target_room != origin_room: Kopie an target_room senden
|
||||
217| 3. Bei Meta-Fragen: delete_original=True im Decision setzen
|
||||
218|
|
||||
219| Args:
|
||||
220| text: Nachrichtentext.
|
||||
221| origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||
222| message_id: Rocket.Chat Nachrichten-ID (für Lösch-Operationen).
|
||||
223|
|
||||
224| Returns:
|
||||
225| RoutingDecision — der Adapter kann zusätzlich löschen/präfixen.
|
||||
226|
|
||||
227| Raises:
|
||||
228| RuntimeError: Wenn kein send_callback gesetzt wurde.
|
||||
229| """
|
||||
230| if not self._send_callback:
|
||||
231| raise RuntimeError(
|
||||
232| "handle_and_forward() requires a send_callback. "
|
||||
233| "Pass send_callback to ArchivarMessageHandler() constructor, "
|
||||
234| "or use classify_and_route() + manual forwarding."
|
||||
235| )
|
||||
236|
|
||||
237| t_start: float = time.monotonic()
|
||||
238|
|
||||
239| decision = await self.classify_and_route(text)
|
||||
240|
|
||||
241| # Only forward if the target differs from origin
|
||||
242| if decision.target_room and decision.target_room != origin_room_id:
|
||||
243| prefix = decision.prefix or ""
|
||||
244| forwarded_text = f"{prefix}{text}" if prefix else text
|
||||
245|
|
||||
246| try:
|
||||
247| success = await self._send_callback(
|
||||
248| decision.target_room, forwarded_text
|
||||
249| )
|
||||
250| if success:
|
||||
251| logger.info(
|
||||
252| "Forwarded [%s] to room %s (conf=%.3f)",
|
||||
253| decision.category,
|
||||
254| decision.target_room[:8],
|
||||
255| decision.confidence,
|
||||
256| )
|
||||
257| else:
|
||||
258| logger.error(
|
||||
259| "Failed to forward [%s] to room %s",
|
||||
260| decision.category,
|
||||
261| decision.target_room[:8],
|
||||
262| )
|
||||
263| self._stats["errors"] += 1
|
||||
264| self._stats["last_error"] = (
|
||||
265| f"Send callback returned False for room "
|
||||
266| f"{decision.target_room[:8]}"
|
||||
267| )
|
||||
268| except Exception as e:
|
||||
269| logger.error(
|
||||
270| "Exception forwarding [%s] to room %s: %s",
|
||||
271| decision.category,
|
||||
272| decision.target_room[:8],
|
||||
273| e,
|
||||
274| )
|
||||
275| self._stats["errors"] += 1
|
||||
276| self._stats["last_error"] = str(e)
|
||||
277|
|
||||
278| # Update rolling average latency
|
||||
279| elapsed_ms: float = (time.monotonic() - t_start) * 1000.0
|
||||
280| self._stats["latencies"].append(elapsed_ms)
|
||||
281| n: int = len(self._stats["latencies"])
|
||||
282| if n > 0:
|
||||
283| self._stats["avg_latency_ms"] = (
|
||||
284| sum(self._stats["latencies"]) / n
|
||||
285| )
|
||||
286|
|
||||
287| return decision
|
||||
288|
|
||||
289| # ── Statistics ──────────────────────────────────────────────────────
|
||||
290|
|
||||
291| @property
|
||||
292| def stats(self) -> Dict[str, int]:
|
||||
293| """Read-only copy of classification statistics."""
|
||||
294| return dict(self._stats)
|
||||
295|
|
||||
296| def reset_stats(self) -> None:
|
||||
297| """Reset statistics counters."""
|
||||
298| self._stats = {
|
||||
299| "total": 0,
|
||||
300| "classified": 0,
|
||||
301| "catch_all": 0,
|
||||
302| "fallback": 0,
|
||||
303| "meta": 0,
|
||||
304| "errors": 0,
|
||||
305| "avg_latency_ms": 0.0,
|
||||
306| "last_error": None,
|
||||
307| "latencies": [],
|
||||
308| }
|
||||
309|
|
||||
310| # ── Configuration ───────────────────────────────────────────────────
|
||||
311|
|
||||
312| @property
|
||||
313| def confidence_threshold(self) -> float:
|
||||
314| """Current confidence threshold."""
|
||||
315| return self._router.confidence_threshold
|
||||
316|
|
||||
317| def set_confidence_threshold(self, value: float) -> None:
|
||||
318| """Override confidence threshold at runtime."""
|
||||
319| self._router.set_confidence_threshold(value)
|
||||
320|
|
||||
321| @property
|
||||
322| def is_initialized(self) -> bool:
|
||||
323| """True if handler is ready for classification."""
|
||||
324| return self._initialized
|
||||
325|
|
||||
326| @property
|
||||
327| def classifier_ready(self) -> bool:
|
||||
328| """True if the embedding classifier is operational (not just fallback)."""
|
||||
329| return self._classifier.is_initialized
|
||||
330|
|
||||
331| def set_send_callback(self, callback: SendCallback) -> None:
|
||||
332| """Set or replace the send callback after construction.
|
||||
333|
|
||||
334| Ermöglicht ``handle_and_forward()``-Nutzung auch wenn der Callback
|
||||
335| erst nach der Konstruktion verfügbar ist (z.B. nach REST-Login).
|
||||
336|
|
||||
337| Args:
|
||||
338| callback: Async function ``(room_id, text) -> bool``.
|
||||
339| """
|
||||
340| self._send_callback = callback
|
||||
341| logger.debug("Send callback registered")
|
||||
342|
|
||||
@@ -0,0 +1,388 @@
|
||||
1|"""
|
||||
2|Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434).
|
||||
3|
|
||||
4|Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||||
5|berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit.
|
||||
6|Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult
|
||||
7|zurückgegeben — der Router übernimmt dann den Fallback.
|
||||
8|"""
|
||||
9|
|
||||
10|from __future__ import annotations
|
||||
11|
|
||||
12|import abc
|
||||
13|import json
|
||||
14|import logging
|
||||
15|import math
|
||||
16|import time
|
||||
17|import urllib.error
|
||||
18|import urllib.request
|
||||
19|from dataclasses import dataclass, field
|
||||
20|from typing import Dict, List, Optional
|
||||
21|
|
||||
22|from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD
|
||||
23|
|
||||
24|logger = logging.getLogger(__name__)
|
||||
25|
|
||||
26|
|
||||
27|@dataclass
|
||||
28|class ClassificationResult:
|
||||
29| """Ergebnis einer Embedding-basierten Klassifikation."""
|
||||
30|
|
||||
31| category: str
|
||||
32| """Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'."""
|
||||
33|
|
||||
34| confidence: float
|
||||
35| """Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
||||
36|
|
||||
37| all_scores: Dict[str, float] = field(default_factory=dict)
|
||||
38| """Alle Kategorie-Scores für Debugging/Transparenz."""
|
||||
39|
|
||||
40| latency_ms: float = 0.0
|
||||
41| """Gemessene Latenz der Embedding-API in Millisekunden."""
|
||||
42|
|
||||
43| fallback: bool = False
|
||||
44| """True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||
45|
|
||||
46| def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool:
|
||||
47| """True wenn die Konfidenz über dem Schwellenwert liegt."""
|
||||
48| return self.confidence >= threshold
|
||||
49|
|
||||
50| def is_fallback(self) -> bool:
|
||||
51| """True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
||||
52| return self.fallback
|
||||
53|
|
||||
54|
|
||||
55|# ── Embedding Client Interface (injectable) ─────────────────────────────
|
||||
56|
|
||||
57|
|
||||
58|class EmbeddingClient(abc.ABC):
|
||||
59| """Interface for embedding providers. Injectable for testability.
|
||||
60|
|
||||
61| Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||
62| single ``get_embedding()`` method so that ``MessageClassifier`` can
|
||||
63| work with real Ollama, mocks, or alternative backends without change.
|
||||
64|
|
||||
65| Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||
66| ``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
||||
67| """
|
||||
68|
|
||||
69| @abc.abstractmethod
|
||||
70| def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
71| """Return the embedding vector for *text*, or None on failure.
|
||||
72|
|
||||
73| Args:
|
||||
74| text: The text to embed.
|
||||
75|
|
||||
76| Returns:
|
||||
77| A list of floats representing the embedding vector,
|
||||
78| or ``None`` if the embedding could not be computed.
|
||||
79| """
|
||||
80| ...
|
||||
81|
|
||||
82| @classmethod
|
||||
83| def __subclasshook__(cls, subclass):
|
||||
84| if cls is EmbeddingClient:
|
||||
85| if any("get_embedding" in B.__dict__ for B in subclass.__mro__):
|
||||
86| return True
|
||||
87| return NotImplemented
|
||||
88|
|
||||
89|
|
||||
90|class OllamaEmbeddingClient(EmbeddingClient):
|
||||
91| """Embedding client backed by Ollama's `/api/embeddings` endpoint.
|
||||
92|
|
||||
93| Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||
94| the ``EmbeddingClient`` interface. Works with every Ollama model
|
||||
95| that exposes the embeddings API (``nomic-embed-text`` recommended).
|
||||
96|
|
||||
97| Usage::
|
||||
98|
|
||||
99| client = OllamaEmbeddingClient()
|
||||
100| vector = client.get_embedding("hello world")
|
||||
101| # → [0.123, -0.456, ...] (768 floats for nomic-embed-text)
|
||||
102| """
|
||||
103|
|
||||
104| def __init__(
|
||||
105| self,
|
||||
106| base_url: Optional[str] = None,
|
||||
107| model: Optional[str] = None,
|
||||
108| timeout: Optional[float] = None,
|
||||
109| ) -> None:
|
||||
110| """
|
||||
111| Args:
|
||||
112| base_url: Ollama base URL (default from ``config.OLLAMA_CONFIG``).
|
||||
113| model: Embedding model (default from ``config.OLLAMA_CONFIG``).
|
||||
114| timeout: Request timeout in seconds (default from ``config.OLLAMA_CONFIG``).
|
||||
115| """
|
||||
116| self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||
117| self._model = model or OLLAMA_CONFIG["model"]
|
||||
118| self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||
119|
|
||||
120| def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
121| """Call Ollama embeddings API. Returns None on any failure."""
|
||||
122| url = f"{self._base_url}/api/embeddings"
|
||||
123| payload = json.dumps(
|
||||
124| {"model": self._model, "prompt": text}
|
||||
125| ).encode("utf-8")
|
||||
126| headers = {"Content-Type": "application/json"}
|
||||
127|
|
||||
128| try:
|
||||
129| req = urllib.request.Request(
|
||||
130| url, data=payload, headers=headers, method="POST"
|
||||
131| )
|
||||
132| with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||
133| data = json.loads(resp.read().decode("utf-8"))
|
||||
134| embedding = data.get("embedding")
|
||||
135| if not embedding or not isinstance(embedding, list):
|
||||
136| logger.error(
|
||||
137| "Ollama returned invalid embedding: %s", type(embedding)
|
||||
138| )
|
||||
139| return None
|
||||
140| return [float(v) for v in embedding]
|
||||
141| except urllib.error.HTTPError as e:
|
||||
142| logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||
143| return None
|
||||
144| except urllib.error.URLError as e:
|
||||
145| logger.warning("Ollama connection failed: %s", e)
|
||||
146| return None
|
||||
147| except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||
148| logger.error("Ollama response parse error: %s", e)
|
||||
149| return None
|
||||
150| except Exception as e:
|
||||
151| logger.error("Unexpected error in get_embedding: %s", e)
|
||||
152| return None
|
||||
153|
|
||||
154|
|
||||
155|class MessageClassifier:
|
||||
156| """Embedding-basierter Nachrichten-Klassifizierer.
|
||||
157|
|
||||
158| Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
||||
159| Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
||||
160| gehalten (Caching für Sub-100ms-Performance).
|
||||
161|
|
||||
162| Usage::
|
||||
163|
|
||||
164| classifier = MessageClassifier()
|
||||
165| await classifier.initialize() # pre-compute category vectors
|
||||
166| result = await classifier.classify("Wie funktioniert das Plugin?")
|
||||
167| print(result.category) # → "FRAGE"
|
||||
168| """
|
||||
169|
|
||||
170| def __init__(
|
||||
171| self,
|
||||
172| base_url: Optional[str] = None,
|
||||
173| model: Optional[str] = None,
|
||||
174| timeout: Optional[float] = None,
|
||||
175| embedding_client: Optional[EmbeddingClient] = None,
|
||||
176| ) -> None:
|
||||
177| """
|
||||
178| Args:
|
||||
179| base_url: Ollama-Basis-URL (default: aus config.py).
|
||||
180| Ignoriert wenn *embedding_client* gesetzt ist.
|
||||
181| model: Embedding-Modell (default: 'nomic-embed-text').
|
||||
182| Ignoriert wenn *embedding_client* gesetzt ist.
|
||||
183| timeout: Timeout in Sekunden (default: 5.0).
|
||||
184| Ignoriert wenn *embedding_client* gesetzt ist.
|
||||
185| embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||
186| Wenn gesetzt, werden alle Embedding-Calls an diesen
|
||||
187| Client delegiert (z.B. für Mocks oder alternative
|
||||
188| Backends). Wenn ``None``, wird ein
|
||||
189| ``OllamaEmbeddingClient`` mit *base_url*, *model*
|
||||
190| und *timeout* erstellt.
|
||||
191| """
|
||||
192| if embedding_client is not None:
|
||||
193| self._embedding_client: EmbeddingClient = embedding_client
|
||||
194| self._base_url = "injected"
|
||||
195| self._model = "injected"
|
||||
196| self._timeout = 0.0
|
||||
197| else:
|
||||
198| self._embedding_client = OllamaEmbeddingClient(
|
||||
199| base_url=base_url, model=model, timeout=timeout
|
||||
200| )
|
||||
201| self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||
202| self._model = model or OLLAMA_CONFIG["model"]
|
||||
203| self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||
204| self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
||||
205|
|
||||
206| # Cache: category → embedding vector (768 floats)
|
||||
207| self._category_vectors: Dict[str, List[float]] = {}
|
||||
208| self._initialized: bool = False
|
||||
209| self._init_error: Optional[str] = None
|
||||
210|
|
||||
211| # Cache: message text → embedding (avoids re-embedding duplicates)
|
||||
212| self._message_cache: Dict[str, List[float]] = {}
|
||||
213| self._cache_max_size: int = 100
|
||||
214|
|
||||
215| # ── Public API ──────────────────────────────────────────────────────
|
||||
216|
|
||||
217| async def initialize(self) -> bool:
|
||||
218| """Pre-compute category vectors. Returns True on success.
|
||||
219|
|
||||
220| Must be called once before classify(). Safe to call multiple times —
|
||||
221| subsequent calls are no-ops if already initialized.
|
||||
222|
|
||||
223| This is async to fit into the adapter's async startup lifecycle.
|
||||
224| Internally calls synchronous urllib.
|
||||
225| """
|
||||
226| import asyncio
|
||||
227| return await asyncio.to_thread(self._initialize_sync)
|
||||
228|
|
||||
229| def _initialize_sync(self) -> bool:
|
||||
230| """Synchronous initialization logic."""
|
||||
231| if self._initialized:
|
||||
232| return True
|
||||
233|
|
||||
234| logger.info(
|
||||
235| "Initializing classifier: model=%s, base_url=%s, timeout=%.1fs",
|
||||
236| self._model, self._base_url, self._timeout,
|
||||
237| )
|
||||
238|
|
||||
239| success = True
|
||||
240| for category, text in CATEGORY_TEXTS.items():
|
||||
241| vector = self._get_embedding(text)
|
||||
242| if vector is None:
|
||||
243| logger.error(
|
||||
244| "Failed to compute embedding for category '%s' — "
|
||||
245| "classifier will use fallback",
|
||||
246| category,
|
||||
247| )
|
||||
248| self._init_error = f"Failed to embed category '{category}'"
|
||||
249| success = False
|
||||
250| break
|
||||
251| self._category_vectors[category] = vector
|
||||
252| logger.debug("Category '%s' vectorized (%d dims)", category, len(vector))
|
||||
253|
|
||||
254| if success:
|
||||
255| self._initialized = True
|
||||
256| logger.info(
|
||||
257| "Classifier initialized successfully (%d categories)",
|
||||
258| len(self._category_vectors),
|
||||
259| )
|
||||
260| return success
|
||||
261|
|
||||
262| async def classify(self, text: str) -> Optional[ClassificationResult]:
|
||||
263| """Classify a message text. Returns None if embedding fails completely.
|
||||
264|
|
||||
265| This is async to fit into the adapter's async pipeline.
|
||||
266| Internally calls synchronous urllib.
|
||||
267|
|
||||
268| Args:
|
||||
269| text: The message text to classify.
|
||||
270|
|
||||
271| Returns:
|
||||
272| ClassificationResult with category and confidence,
|
||||
273| or None if the classifier is not initialized or embedding fails.
|
||||
274| """
|
||||
275| import asyncio
|
||||
276| return await asyncio.to_thread(self._classify_sync, text)
|
||||
277|
|
||||
278| def _classify_sync(self, text: str) -> Optional[ClassificationResult]:
|
||||
279| if not self._initialized:
|
||||
280| logger.warning("classify() called before initialize() — returning None")
|
||||
281| return None
|
||||
282|
|
||||
283| if not text or not text.strip():
|
||||
284| return None
|
||||
285|
|
||||
286| text = text.strip()
|
||||
287|
|
||||
288| t0 = time.monotonic()
|
||||
289|
|
||||
290| vector = self._get_cached_or_compute(text)
|
||||
291| if vector is None:
|
||||
292| logger.debug("Failed to embed message: %.60s...", text)
|
||||
293| return None
|
||||
294|
|
||||
295| # Compare against all category vectors
|
||||
296| scores: Dict[str, float] = {}
|
||||
297| best_category: str = ""
|
||||
298| best_score: float = -1.0
|
||||
299|
|
||||
300| for category, cat_vector in self._category_vectors.items():
|
||||
301| score = self._cosine_similarity(vector, cat_vector)
|
||||
302| scores[category] = score
|
||||
303| if score > best_score:
|
||||
304| best_score = score
|
||||
305| best_category = category
|
||||
306|
|
||||
307| latency_ms = (time.monotonic() - t0) * 1000.0
|
||||
308|
|
||||
309| if best_score < 0:
|
||||
310| return None
|
||||
311|
|
||||
312| return ClassificationResult(
|
||||
313| category=best_category,
|
||||
314| confidence=best_score,
|
||||
315| all_scores=scores,
|
||||
316| latency_ms=latency_ms,
|
||||
317| fallback=False,
|
||||
318| )
|
||||
319|
|
||||
320| # ── Embedding-API ───────────────────────────────────────────────────
|
||||
321|
|
||||
322| def _get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
323| """Delegate to the injectable ``EmbeddingClient``.
|
||||
324|
|
||||
325| Returns None on any failure — the caller (router) handles fallback.
|
||||
326| """
|
||||
327| return self._embedding_client.get_embedding(text)
|
||||
328|
|
||||
329| def _get_cached_or_compute(self, text: str) -> Optional[List[float]]:
|
||||
330| """Return cached embedding or compute and cache a new one."""
|
||||
331| # Simple LRU-like: evict if over max
|
||||
332| if len(self._message_cache) >= self._cache_max_size:
|
||||
333| # Evict the oldest key (first inserted)
|
||||
334| oldest = next(iter(self._message_cache))
|
||||
335| del self._message_cache[oldest]
|
||||
336|
|
||||
337| if text in self._message_cache:
|
||||
338| return self._message_cache[text]
|
||||
339|
|
||||
340| vector = self._get_embedding(text)
|
||||
341| if vector is not None:
|
||||
342| self._message_cache[text] = vector
|
||||
343| return vector
|
||||
344|
|
||||
345| # ── Math ────────────────────────────────────────────────────────────
|
||||
346|
|
||||
347| @staticmethod
|
||||
348| def _cosine_similarity(a: List[float], b: List[float]) -> float:
|
||||
349| """Compute cosine similarity between two vectors.
|
||||
350|
|
||||
351| Returns 0.0 if either vector has zero magnitude.
|
||||
352| """
|
||||
353| if len(a) != len(b):
|
||||
354| raise ValueError(
|
||||
355| f"Vector dimension mismatch: {len(a)} vs {len(b)}"
|
||||
356| )
|
||||
357|
|
||||
358| dot = sum(x * y for x, y in zip(a, b))
|
||||
359| norm_a = math.sqrt(sum(x * x for x in a))
|
||||
360| norm_b = math.sqrt(sum(y * y for y in b))
|
||||
361|
|
||||
362| if norm_a == 0.0 or norm_b == 0.0:
|
||||
363| return 0.0
|
||||
364|
|
||||
365| return dot / (norm_a * norm_b)
|
||||
366|
|
||||
367| # ── Introspection ───────────────────────────────────────────────────
|
||||
368|
|
||||
369| @property
|
||||
370| def is_initialized(self) -> bool:
|
||||
371| """True if category vectors have been computed successfully."""
|
||||
372| return self._initialized
|
||||
373|
|
||||
374| @property
|
||||
375| def init_error(self) -> Optional[str]:
|
||||
376| """Error message from initialization, or None."""
|
||||
377| return self._init_error
|
||||
378|
|
||||
379| @property
|
||||
380| def category_count(self) -> int:
|
||||
381| """Number of cached category vectors."""
|
||||
382| return len(self._category_vectors)
|
||||
383|
|
||||
384| @property
|
||||
385| def cache_size(self) -> int:
|
||||
386| """Number of cached message embeddings."""
|
||||
387| return len(self._message_cache)
|
||||
388|
|
||||
@@ -0,0 +1,87 @@
|
||||
1|"""
|
||||
2|Archivar-Konfiguration: Raum-Mapping, Kategorie-Texte und Ollama-Einstellungen.
|
||||
3|
|
||||
4|Alle Raum-IDs stammen direkt aus der Architektur-Skizze
|
||||
5|(/home/bernd/Archivar_Architecture.md) und werden als kanonisch betrachtet.
|
||||
6|"""
|
||||
7|
|
||||
8|from __future__ import annotations
|
||||
9|
|
||||
10|from typing import Dict
|
||||
11|
|
||||
12|# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
||||
13|
|
||||
14|OLLAMA_CONFIG: dict = {
|
||||
15| "base_url": "http://localhost:11434",
|
||||
16| "model": "nomic-embed-text",
|
||||
17| "timeout": 5.0, # Sekunden — bei Überschreitung → Fallback
|
||||
18| "embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||
19|}
|
||||
20|
|
||||
21|# ── Kategorie-Referenztexte (für Embedding-Vergleich) ───────────────────────
|
||||
22|# Diese Texte werden einmalig beim Start vektorisiert. Neue Nachrichten werden
|
||||
23|# via Kosinus-Ähnlichkeit gegen diese Vektoren verglichen.
|
||||
24|
|
||||
25|CATEGORY_TEXTS: Dict[str, str] = {
|
||||
26| "FAKT": (
|
||||
27| "Dies ist eine Information oder ein Faktenbeitrag. Es enthält objektive "
|
||||
28| "Aussagen, Dokumentation oder Wissenswertes ohne Handlungsbedarf. Beispiele "
|
||||
29| "sind Dokumentationsabschnitte, Systeminformationen oder allgemeine Erklärungen."
|
||||
30| ),
|
||||
31| "FRAGE": (
|
||||
32| "Dies ist eine Frage oder ein Hilferuf. Es wird ein Wissensbeitrag oder "
|
||||
33| "eine Antwort auf ein konkretes Problem erwartet. Beispiele sind "
|
||||
34| "Problembeschreibungen oder Anfragen nach Lösungen."
|
||||
35| ),
|
||||
36| "ALARM": (
|
||||
37| "Dies ist eine dringende Nachricht oder ein Alarm. Es erfordert eine "
|
||||
38| "sofortige Reaktion oder Handlung. Beispiele sind Systemausfälle, "
|
||||
39| "kritische Fehler oder Zeitdruck betreffende Anfragen."
|
||||
40| ),
|
||||
41|}
|
||||
42|
|
||||
43|# ── Konfidenz-Schwellenwert ─────────────────────────────────────────────────
|
||||
44|
|
||||
45|CONFIDENCE_THRESHOLD: float = 0.6
|
||||
46|"""Nachrichten mit confidence >= 0.6 werden klassifiziert, alles darunter
|
||||
47|geht an den CATCH_ALL_ROOM."""
|
||||
48|
|
||||
49|# ── Raum-Mapping ────────────────────────────────────────────────────────────
|
||||
50|# ECHTE IDs aus der Architektur-Skizze — NICHT ERFUNDEN!
|
||||
51|# FRAGE ist nested: FRAGE["default"] = string, FRAGE["project_specific"] = dict
|
||||
52|
|
||||
53|ROOM_MAPPING: dict = {
|
||||
54| # Protonbridge-Plugin: Catch-All / Wissensdatenbank
|
||||
55| "FAKT": "69f8beaef06dba03be82f9fc",
|
||||
56|
|
||||
57| # Fragen-Routing — default: BAT-Team, projektspezifisch weiterleitbar
|
||||
58| "FRAGE": {
|
||||
59| "default": "6a049d493a62ef8f1ead2320", # #BAT-Team
|
||||
60| "project_specific": {
|
||||
61| "plugin": "6a19b0ff02aeecd36b1aa16c", # #Rocketchat-Plugin
|
||||
62| "lan": "6a1c56d4b73efec2bebec2db", # #LAN-Dokumentation
|
||||
63| },
|
||||
64| },
|
||||
65|
|
||||
66| # DM mit Andreas — direkter Alarm-Kanal
|
||||
67| "ALARM": "69f4e777f06dba03be82dce7",
|
||||
68|}
|
||||
69|
|
||||
70|# Catch-All-Raum: wohin unklassifizierbare Nachrichten gehen
|
||||
71|CATCH_ALL_ROOM: str = "69f8beaef06dba03be82f9fc" # Protonbridge-Plugin
|
||||
72|
|
||||
73|# ── Fallback-Keyword-Heuristik ──────────────────────────────────────────────
|
||||
74|
|
||||
75|FALLBACK_KEYWORDS: dict = {
|
||||
76| "FRAGE": ["frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||
77| "kannst du", "können sie", "help", "hilfe", "problem",
|
||||
78| "funktioniert nicht", "kaputt", "erklären", "erkläre"],
|
||||
79| "ALARM": ["alarm", "hilfe", "dringend", "sofort", "notfall",
|
||||
80| "ausfall", "absturz", "kritisch", "emergency",
|
||||
81| "feuer", "panne", "sos", "sicherheitslücke"],
|
||||
82|}
|
||||
83|"""
|
||||
84|Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
||||
85|wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||
86|"""
|
||||
87|
|
||||
@@ -0,0 +1,336 @@
|
||||
1|"""
|
||||
2|Routing-Logik für klassifizierte Nachrichten.
|
||||
3|
|
||||
4|Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle
|
||||
5|und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie
|
||||
6|und Meta-Fragen-Erkennung.
|
||||
7|"""
|
||||
8|
|
||||
9|from __future__ import annotations
|
||||
10|
|
||||
11|import logging
|
||||
12|import re
|
||||
13|from dataclasses import dataclass, field
|
||||
14|from typing import Dict, List, Optional, Tuple
|
||||
15|
|
||||
16|from .classifier import ClassificationResult, MessageClassifier
|
||||
17|from .config import (
|
||||
18| ROOM_MAPPING,
|
||||
19| CATCH_ALL_ROOM,
|
||||
20| CONFIDENCE_THRESHOLD,
|
||||
21| FALLBACK_KEYWORDS,
|
||||
22| OLLAMA_CONFIG,
|
||||
23|)
|
||||
24|
|
||||
25|logger = logging.getLogger(__name__)
|
||||
26|
|
||||
27|
|
||||
28|# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
|
||||
29|# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
|
||||
30|# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
|
||||
31|# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem
|
||||
32|# Hinweis in der Kopie versehen.
|
||||
33|
|
||||
34|_META_PATTERNS: List[re.Pattern] = [
|
||||
35| re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)",
|
||||
36| re.IGNORECASE),
|
||||
37| re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)",
|
||||
38| re.IGNORECASE),
|
||||
39| re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)",
|
||||
40| re.IGNORECASE),
|
||||
41| re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar",
|
||||
42| re.IGNORECASE),
|
||||
43| re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)",
|
||||
44| re.IGNORECASE),
|
||||
45| re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)",
|
||||
46| re.IGNORECASE),
|
||||
47| re.compile(r"(?:who|which room|where).*(?:message|routed|sent)",
|
||||
48| re.IGNORECASE),
|
||||
49|]
|
||||
50|
|
||||
51|# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
|
||||
52|
|
||||
53|_PROJECT_KEYWORDS: Dict[str, List[str]] = {
|
||||
54| "plugin": [
|
||||
55| "plugin", "adapter", "rocketchat", "gateway", "webhook",
|
||||
56| "archivar", "module", "schnittstelle",
|
||||
57| ],
|
||||
58| "lan": [
|
||||
59| "lan", "netzwerk", "router", "switch", "vlan", "dns",
|
||||
60| "dhcp", "ip-adresse", "subnetz", "firewall", "wlan",
|
||||
61| "ethernet", "kabel", "patchpanel", "zugangspunkt",
|
||||
62| ],
|
||||
63|}
|
||||
64|
|
||||
65|
|
||||
66|@dataclass
|
||||
67|class RoutingDecision:
|
||||
68| """Entscheidung, wohin eine Nachricht weitergeleitet wird."""
|
||||
69|
|
||||
70| category: str
|
||||
71| """Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'."""
|
||||
72|
|
||||
73| target_room: str
|
||||
74| """Rocket.Chat Raum-ID des Zielraums."""
|
||||
75|
|
||||
76| confidence: float
|
||||
77| """Konfidenz der Klassifikation (0.0–1.0)."""
|
||||
78|
|
||||
79| is_catch_all: bool = False
|
||||
80| """True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging."""
|
||||
81|
|
||||
82| is_fallback: bool = False
|
||||
83| """True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||
84|
|
||||
85| is_meta: bool = False
|
||||
86| """True, wenn die Nachricht als Meta-Frage erkannt wurde."""
|
||||
87|
|
||||
88| prefix: str = ""
|
||||
89| """Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK])."""
|
||||
90|
|
||||
91| delete_original: bool = False
|
||||
92| """True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
|
||||
93|
|
||||
94| project: Optional[str] = None
|
||||
95| """Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
|
||||
96|
|
||||
97| all_scores: Dict[str, float] = field(default_factory=dict)
|
||||
98| """Alle Kategorie-Scores für Debugging/Logging."""
|
||||
99|
|
||||
100|
|
||||
101|class MessageRouter:
|
||||
102| """Nachrichten-Router: Klassifikation → Raum-Ermittlung → RoutingDecision.
|
||||
103|
|
||||
104| Usage::
|
||||
105|
|
||||
106| router = MessageRouter(classifier)
|
||||
107| decision = await router.route("Wie konfiguriere ich das Plugin?")
|
||||
108| # decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
|
||||
109| # decision.category → "FRAGE"
|
||||
110| # decision.project → "plugin"
|
||||
111| """
|
||||
112|
|
||||
113| def __init__(self, classifier: MessageClassifier) -> None:
|
||||
114| """
|
||||
115| Args:
|
||||
116| classifier: Ein (initialisierter) MessageClassifier.
|
||||
117| """
|
||||
118| self._classifier = classifier
|
||||
119| self._confidence_threshold = CONFIDENCE_THRESHOLD
|
||||
120|
|
||||
121| # ── Public API ──────────────────────────────────────────────────────
|
||||
122|
|
||||
123| async def route(self, text: str) -> RoutingDecision:
|
||||
124| """Klassifiziere und route eine Nachricht.
|
||||
125|
|
||||
126| Der vollständige Routing-Flow:
|
||||
127| 1. Meta-Fragen-Check (vor Embedding, da billig)
|
||||
128| 2. Embedding-basierte Klassifikation via Classifier
|
||||
129| 3. Bei Classifier-Fehler → Fallback-Keyword-Heuristik
|
||||
130| 4. Konfidenz-Prüfung → Catch-All bei < threshold
|
||||
131| 5. Raum-Ermittlung (projektspezifisch für FRAGE)
|
||||
132|
|
||||
133| Args:
|
||||
134| text: Der Nachrichtentext.
|
||||
135|
|
||||
136| Returns:
|
||||
137| RoutingDecision mit Zielraum, Kategorie und Metadaten.
|
||||
138| """
|
||||
139| if not text or not text.strip():
|
||||
140| return RoutingDecision(
|
||||
141| category="FAKT",
|
||||
142| target_room=CATCH_ALL_ROOM,
|
||||
143| confidence=0.0,
|
||||
144| is_catch_all=True,
|
||||
145| )
|
||||
146|
|
||||
147| text = text.strip()
|
||||
148|
|
||||
149| # ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
|
||||
150| if self._is_meta_question(text):
|
||||
151| logger.info("Meta-question detected: %.80s...", text)
|
||||
152| return RoutingDecision(
|
||||
153| category="FRAGE",
|
||||
154| target_room=CATCH_ALL_ROOM,
|
||||
155| confidence=1.0,
|
||||
156| is_meta=True,
|
||||
157| delete_original=True,
|
||||
158| prefix="[META-FRAGE] ",
|
||||
159| )
|
||||
160|
|
||||
161| # ── Schritt 2: Embedding-basierte Klassifikation ───────────────
|
||||
162| result: Optional[ClassificationResult] = None
|
||||
163|
|
||||
164| if self._classifier.is_initialized:
|
||||
165| result = await self._classifier.classify(text)
|
||||
166|
|
||||
167| # ── Schritt 3: Fallback bei Classifier-Versagen ────────────────
|
||||
168| if result is None:
|
||||
169| logger.info(
|
||||
170| "Classifier unavailable — using keyword fallback for: %.80s...",
|
||||
171| text,
|
||||
172| )
|
||||
173| category, is_fallback = self._keyword_classify(text)
|
||||
174| return RoutingDecision(
|
||||
175| category=category,
|
||||
176| target_room=self._resolve_room(category, text),
|
||||
177| confidence=0.0,
|
||||
178| is_fallback=is_fallback,
|
||||
179| prefix="[FALLBACK] " if is_fallback else "",
|
||||
180| )
|
||||
181|
|
||||
182| # ── Schritt 4: Konfidenz-Prüfung ───────────────────────────────
|
||||
183| if not result.is_confident(self._confidence_threshold):
|
||||
184| logger.debug(
|
||||
185| "Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all",
|
||||
186| result.confidence, self._confidence_threshold, result.category,
|
||||
187| )
|
||||
188| return RoutingDecision(
|
||||
189| category=result.category,
|
||||
190| target_room=CATCH_ALL_ROOM,
|
||||
191| confidence=result.confidence,
|
||||
192| is_catch_all=True,
|
||||
193| all_scores=result.all_scores,
|
||||
194| )
|
||||
195|
|
||||
196| # ── Schritt 5: Raum-Ermittlung ─────────────────────────────────
|
||||
197| target_room, project = self._resolve_room_with_project(
|
||||
198| result.category, text
|
||||
199| )
|
||||
200|
|
||||
201| return RoutingDecision(
|
||||
202| category=result.category,
|
||||
203| target_room=target_room,
|
||||
204| confidence=result.confidence,
|
||||
205| all_scores=result.all_scores,
|
||||
206| project=project,
|
||||
207| )
|
||||
208|
|
||||
209| # ── Room Resolution ────────────────────────────────────────────────
|
||||
210|
|
||||
211| def _resolve_room(self, category: str, text: str = "") -> str:
|
||||
212| """Resolve the target room ID for a category.
|
||||
213|
|
||||
214| For FRAGE: checks project-specific keywords and falls back to default.
|
||||
215| """
|
||||
216| room, _ = self._resolve_room_with_project(category, text)
|
||||
217| return room
|
||||
218|
|
||||
219| def _resolve_room_with_project(
|
||||
220| self, category: str, text: str
|
||||
221| ) -> Tuple[str, Optional[str]]:
|
||||
222| """Resolve room and detect project for FRAGE routing.
|
||||
223|
|
||||
224| Returns:
|
||||
225| (room_id, project_name_or_None)
|
||||
226| """
|
||||
227| mapping = ROOM_MAPPING.get(category)
|
||||
228|
|
||||
229| if mapping is None:
|
||||
230| logger.warning(
|
||||
231| "Unknown category '%s' — falling back to CATCH_ALL_ROOM", category
|
||||
232| )
|
||||
233| return CATCH_ALL_ROOM, None
|
||||
234|
|
||||
235| # Simple string mapping (FAKT, ALARM)
|
||||
236| if isinstance(mapping, str):
|
||||
237| return mapping, None
|
||||
238|
|
||||
239| # Nested mapping (FRAGE)
|
||||
240| if isinstance(mapping, dict):
|
||||
241| default_room = mapping.get("default", CATCH_ALL_ROOM)
|
||||
242|
|
||||
243| # Check project-specific keywords
|
||||
244| project_specific = mapping.get("project_specific", {})
|
||||
245| if isinstance(project_specific, dict) and project_specific:
|
||||
246| detected_project = self._detect_project(text, project_specific)
|
||||
247| if detected_project:
|
||||
248| project_room = project_specific[detected_project]
|
||||
249| logger.debug(
|
||||
250| "FRAGE → project '%s' → room %s", detected_project, project_room
|
||||
251| )
|
||||
252| return project_room, detected_project
|
||||
253|
|
||||
254| return default_room, None
|
||||
255|
|
||||
256| return CATCH_ALL_ROOM, None
|
||||
257|
|
||||
258| @staticmethod
|
||||
259| def _detect_project(
|
||||
260| text: str, project_specific: Dict[str, str]
|
||||
261| ) -> Optional[str]:
|
||||
262| """Detect which project a FRAGE targets based on keywords.
|
||||
263|
|
||||
264| Args:
|
||||
265| text: The message text (lowercased for matching).
|
||||
266| project_specific: Mapping of project_key → room_id.
|
||||
267|
|
||||
268| Returns:
|
||||
269| The project key, or None if no project keywords match.
|
||||
270| """
|
||||
271| text_lower = text.lower()
|
||||
272|
|
||||
273| for project_key in project_specific:
|
||||
274| keywords = _PROJECT_KEYWORDS.get(project_key, [project_key])
|
||||
275| for kw in keywords:
|
||||
276| if kw in text_lower:
|
||||
277| return project_key
|
||||
278|
|
||||
279| return None
|
||||
280|
|
||||
281| # ── Meta-Question Detection ────────────────────────────────────────
|
||||
282|
|
||||
283| @staticmethod
|
||||
284| def _is_meta_question(text: str) -> bool:
|
||||
285| """Check if a message is a meta-question about the Archivar system.
|
||||
286|
|
||||
287| Meta-questions ask about the classification/routing system itself.
|
||||
288| They should NOT be forwarded as regular questions.
|
||||
289| """
|
||||
290| for pattern in _META_PATTERNS:
|
||||
291| if pattern.search(text):
|
||||
292| return True
|
||||
293| return False
|
||||
294|
|
||||
295| # ── Fallback: Keyword-Heuristik ────────────────────────────────────
|
||||
296|
|
||||
297| @staticmethod
|
||||
298| def _keyword_classify(text: str) -> Tuple[str, bool]:
|
||||
299| """Classify using keyword heuristics when Ollama is unavailable.
|
||||
300|
|
||||
301| Returns:
|
||||
302| (category, is_fallback) — is_fallback is always True here.
|
||||
303| """
|
||||
304| text_lower = text.lower()
|
||||
305|
|
||||
306| # Check ALARM keywords first (highest priority)
|
||||
307| for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||
308| if kw in text_lower:
|
||||
309| return "ALARM", True
|
||||
310|
|
||||
311| # Check FRAGE keywords
|
||||
312| for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||
313| if kw in text_lower:
|
||||
314| return "FRAGE", True
|
||||
315|
|
||||
316| # Default: FAKT
|
||||
317| return "FAKT", True
|
||||
318|
|
||||
319| # ── Configuration ──────────────────────────────────────────────────
|
||||
320|
|
||||
321| @property
|
||||
322| def confidence_threshold(self) -> float:
|
||||
323| """Current confidence threshold."""
|
||||
324| return self._confidence_threshold
|
||||
325|
|
||||
326| def set_confidence_threshold(self, value: float) -> None:
|
||||
327| """Override the confidence threshold at runtime.
|
||||
328|
|
||||
329| Args:
|
||||
330| value: New threshold (0.0–1.0).
|
||||
331| """
|
||||
332| if not 0.0 <= value <= 1.0:
|
||||
333| raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}")
|
||||
334| self._confidence_threshold = value
|
||||
335| logger.info("Confidence threshold set to %.2f", value)
|
||||
336|
|
||||
Reference in New Issue
Block a user