diff --git a/plugin/archivar/classifier.py b/plugin/archivar/classifier.py index 6df44de..117d429 100644 --- a/plugin/archivar/classifier.py +++ b/plugin/archivar/classifier.py @@ -1,10 +1,10 @@ """ -Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434). +Embedding-basierte Intent-Klassifikation für Archivar v3. Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab -berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit. -Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult -zurückgegeben — der Router übernimmt dann den Fallback. +berechneten Kategorie-Vektoren (direct_question, smalltalk, work_order, ambiguous) +via Kosinus-Ähnlichkeit. Bei Ollama-Fehlern oder Timeout wird None als +ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback. """ from __future__ import annotations @@ -17,19 +17,27 @@ import time import urllib.error import urllib.request from dataclasses import dataclass, field -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Tuple -from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD +from .config import ( + OLLAMA_CONFIG, + CATEGORY_TEXTS, + CONFIDENCE_THRESHOLDS, + LLM_CONFIG, + LLM_CLASSIFY_PROMPT, + LLM_CONFIDENCE_THRESHOLD, + FALLBACK_KEYWORDS +) logger = logging.getLogger(__name__) @dataclass class ClassificationResult: - """Ergebnis einer Embedding-basierten Klassifikation.""" + """Ergebnis einer Intent-Klassifikation.""" category: str - """Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'.""" + """Kategorie-Label: 'direct_question', 'smalltalk', 'work_order', oder 'ambiguous'.""" confidence: float """Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor.""" @@ -43,10 +51,35 @@ class ClassificationResult: fallback: bool = False """True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down).""" - def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool: - """True wenn die Konfidenz über dem Schwellenwert liegt.""" + llm_verified: bool = False + """True, wenn das Ergebnis durch LLM-Verifikation bestätigt wurde.""" + + def is_confident(self, threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]) -> bool: + """True wenn die Konfidenz über dem Schwellenwert für automatisches Routing liegt.""" return self.confidence >= threshold + def needs_clarification(self) -> bool: + """True wenn die Konfidenz im Bereich 60-90% liegt und Klärung benötigt.""" + return ( + self.confidence >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and + self.confidence < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] + ) + + def should_route(self) -> bool: + """True wenn die Nachricht geroutet werden sollte. + + - work_order mit >90% Konfidenz wird geroutet + - direct_question und smalltalk werden nie geroutet + - ambiguous benötigt Klärung + """ + if self.category in ("direct_question", "smalltalk"): + return False + if self.category == "work_order": + return self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] + if self.category == "ambiguous": + return False # Benötigt Klärung + return False + def is_fallback(self) -> bool: """True wenn dieses Ergebnis aus der Keyword-Heuristik stammt.""" return self.fallback @@ -59,10 +92,10 @@ class EmbeddingClient(abc.ABC): """Interface for embedding providers. Injectable for testability. Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a - single ``get_embedding()`` method so that ``MessageClassifier`` can + single ``get_embedding()`` method so that ``IntentClassifier`` can work with real Ollama, mocks, or alternative backends without change. - Implementations must be thread-safe since ``MessageClassifier`` calls + Implementations must be thread-safe since ``IntentClassifier`` calls ``get_embedding()`` synchronously inside ``asyncio.to_thread``. """ @@ -159,10 +192,10 @@ class LLMClient(abc.ABC): """Interface for LLM providers. Injectable for testability. Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a - single ``classify()`` method so that ``MessageClassifier`` can + single ``classify()`` method so that ``IntentClassifier`` can work with real Ollama, mocks, or alternative backends without change. - Implementations must be thread-safe since ``MessageClassifier`` calls + Implementations must be thread-safe since ``IntentClassifier`` calls ``classify()`` synchronously inside ``asyncio.to_thread``. """ @@ -171,6 +204,11 @@ class LLMClient(abc.ABC): """Klassifiziere Text. Gibt Kategorie-String oder None zurück.""" ... + @abc.abstractmethod + def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: + """Verifiziere die Konfidenz mit dem LLM und gib (Kategorie, Konfidenz) zurück.""" + ... + class OllamaLLMClient(LLMClient): """LLM client backed by Ollama's `/api/generate` endpoint. @@ -183,7 +221,7 @@ class OllamaLLMClient(LLMClient): client = OllamaLLMClient() category = client.classify("Wie funktioniert das Plugin?") - # → "FRAGE" + # → "direct_question" """ def __init__( @@ -230,8 +268,8 @@ class OllamaLLMClient(LLMClient): return None # Trim whitespace and normalize category - category = response_text.strip().upper() - if category in ("FAKT", "FRAGE", "ALARM"): + category = response_text.strip().lower() + if category in ("direct_question", "smalltalk", "work_order", "ambiguous"): return category else: logger.warning("LLM returned invalid category: %s", category) @@ -249,9 +287,30 @@ class OllamaLLMClient(LLMClient): logger.error("Unexpected error in classify: %s", e) return None + def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: + """Verifiziere die Konfidenz mit dem LLM.""" + try: + # Erstelle einen Prompt mit den Scores für die LLM-Verifikation + scores_text = "\n".join([f"- {cat}: {score:.2f}" for cat, score in scores.items()]) + prompt = f"""Nachricht: {text} -class MessageClassifier: - """Embedding-basierter Nachrichten-Klassifizierer. +Embedding-basierte Scores: +{scores_text} + +Welche Kategorie ist am wahrscheinlichsten? Antworte nur mit dem Kategorienamen: +direct_question, smalltalk, work_order, oder ambiguous""" + + category = self.classify(prompt) + if category: + # Setze eine hohe Konfidenz für LLM-verifizierte Ergebnisse + return (category, 0.95) + except Exception as e: + logger.warning("LLM confidence verification failed: %s", e) + return None + + +class IntentClassifier: + """Embedding-basierter Intent-Klassifizierer für Archivar v3. Verwendet nomic-embed-text via Ollama-API auf localhost:11434. Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher @@ -259,10 +318,10 @@ class MessageClassifier: Usage:: - classifier = MessageClassifier() + classifier = IntentClassifier() await classifier.initialize() # pre-compute category vectors result = await classifier.classify("Wie funktioniert das Plugin?") - print(result.category) # → "FRAGE" + print(result.category) # → "direct_question" """ def __init__( @@ -330,32 +389,28 @@ class MessageClassifier: self._cache_max_size: int = 100 def _keyword_prefilter(self, text: str) -> Optional[str]: - """Stufe 0: Keyword-Vorfilter. Liefert 'ALARM', 'FRAGE' oder None.""" - from .config import FALLBACK_KEYWORDS - + """Stufe 0: Keyword-Vorfilter. Liefert Intent-Kategorie oder None.""" t = text.lower() - # ALARM ZUERST — höchste Priorität - for kw in FALLBACK_KEYWORDS.get("ALARM", []): - if kw in t: - return "ALARM" - for kw in FALLBACK_KEYWORDS.get("FRAGE", []): - if kw in t: - return "FRAGE" + + # Prüfe zuerst auf direkte Matches + for category, keywords in FALLBACK_KEYWORDS.items(): + if category == "ambiguous": + continue # Ambiguous wird nicht über Keywords erkannt + for kw in keywords: + if kw in t: + return category return None - async def _llm_classify(self, text: str) -> Optional[str]: + async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: import asyncio - return await asyncio.to_thread(self._llm_classify_sync, text) + return await asyncio.to_thread(self._llm_classify_sync, text, scores) - def _llm_classify_sync(self, text: str) -> Optional[str]: + def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: try: if not self._llm_client or not self._llm_enabled: return None - prompt = LLM_CLASSIFY_PROMPT.format(text=text) - result = self._llm_client.classify(prompt) - if result in ("FAKT", "FRAGE", "ALARM"): - return result + return self._llm_client.verify_confidence(text, scores) except Exception as e: logger.warning("LLM classification failed: %s", e) return None @@ -364,8 +419,7 @@ class MessageClassifier: """Send a raw prompt to the LLM and return its response. Unlike ``_llm_classify_sync``, this does NOT validate against - FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the - ``LLM_ROOM_PROMPT`` where the expected answer is a room name. + Intent-Kategorien. Used by den Router. Args: prompt: The complete prompt to send. @@ -404,7 +458,7 @@ class MessageClassifier: return True logger.info( - "Initializing classifier: model=%s, base_url=%s, timeout=%.1fs", + "Initializing intent classifier: model=%s, base_url=%s, timeout=%.1fs", self._model, self._base_url, self._timeout, ) @@ -426,7 +480,7 @@ class MessageClassifier: if success: self._initialized = True logger.info( - "Classifier initialized successfully (%d categories)", + "Intent classifier initialized successfully (%d categories)", len(self._category_vectors), ) return success @@ -461,17 +515,22 @@ class MessageClassifier: # Stufe 0: Keyword-Vorfilter keyword_result = self._keyword_prefilter(text) - if keyword_result == "ALARM": - # ALARM hat höchste Priorität - sofortige Rückgabe + if keyword_result: + # Keyword-Treffer haben hohe Priorität latency_ms = (time.monotonic() - t0) * 1000.0 + confidence = 0.85 # Hohe Konfidenz für Keyword-Treffer + + # Für ambiguous Ergebnisse setzen wir eine niedrigere Konfidenz + if keyword_result == "ambiguous": + confidence = 0.75 + return ClassificationResult( - category="ALARM", - confidence=0.95, # Hohe Konfidenz für Keyword-Treffer - all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0}, + category=keyword_result, + confidence=confidence, + all_scores={keyword_result: confidence}, latency_ms=latency_ms, - fallback=False, + fallback=True, ) - # Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert) # Stufe 1: Embedding-Klassifikation vector = self._get_cached_or_compute(text) @@ -496,13 +555,29 @@ class MessageClassifier: if best_score < 0: return None - # Direktes Return des Embedding-Ergebnisses + # Stufe 2: LLM-Verifikation bei ambiguous Ergebnissen + llm_verified = False + final_category = best_category + final_score = best_score + + # Wenn der Score im Klärungsbereich liegt, führe LLM-Verifikation durch + if ( + best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and + best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] + ): + llm_result = self._llm_classify_sync(text, scores) + if llm_result: + final_category, final_score = llm_result + llm_verified = True + + # Direktes Return des Ergebnisses return ClassificationResult( - category=best_category, - confidence=best_score, + category=final_category, + confidence=final_score, all_scores=scores, latency_ms=latency_ms, fallback=False, + llm_verified=llm_verified, ) # ── Embedding-API ─────────────────────────────────────────────────── @@ -572,4 +647,4 @@ class MessageClassifier: @property def cache_size(self) -> int: """Number of cached message embeddings.""" - return len(self._message_cache) + return len(self._message_cache) \ No newline at end of file