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