""" Embedding-basierte Intent-Klassifikation für Archivar v3. Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab 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 import abc import json import logging import math import time import urllib.error import urllib.request from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple from .config import ( OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLDS, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD, FALLBACK_KEYWORDS ) from .adaptive_timeout import adaptive_timeout logger = logging.getLogger(__name__) @dataclass class ClassificationResult: """Ergebnis einer Intent-Klassifikation.""" category: str """Kategorie-Label: 'direct_question', 'smalltalk', 'work_order', oder 'ambiguous'.""" confidence: float """Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor.""" all_scores: Dict[str, float] = field(default_factory=dict) """Alle Kategorie-Scores für Debugging/Transparenz.""" latency_ms: float = 0.0 """Gemessene Latenz der Embedding-API in Millisekunden.""" fallback: bool = False """True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down).""" 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 # ── Embedding Client Interface (injectable) ───────────────────────────── 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 ``IntentClassifier`` can work with real Ollama, mocks, or alternative backends without change. Implementations must be thread-safe since ``IntentClassifier`` calls ``get_embedding()`` synchronously inside ``asyncio.to_thread``. """ @abc.abstractmethod def get_embedding(self, text: str) -> Optional[List[float]]: """Return the embedding vector for *text*, or None on failure. Args: text: The text to embed. Returns: A list of floats representing the embedding vector, or ``None`` if the embedding could not be computed. """ ... @classmethod def __subclasshook__(cls, subclass): if cls is EmbeddingClient: if any("get_embedding" in B.__dict__ for B in subclass.__mro__): return True return NotImplemented class OllamaEmbeddingClient(EmbeddingClient): """Embedding client backed by Ollama's `/api/embeddings` endpoint. Wraps ``urllib.request.urlopen`` so the transport is hidden behind the ``EmbeddingClient`` interface. Works with every Ollama model that exposes the embeddings API (``nomic-embed-text`` recommended). Usage:: client = OllamaEmbeddingClient() vector = client.get_embedding("hello world") # → [0.123, -0.456, ...] (768 floats for nomic-embed-text) """ def __init__( self, base_url: Optional[str] = None, model: Optional[str] = None, timeout: Optional[float] = None, ) -> None: """ Args: base_url: Ollama base URL (default from ``config.OLLAMA_CONFIG``). model: Embedding model (default from ``config.OLLAMA_CONFIG``). timeout: Request timeout in seconds (default from ``config.OLLAMA_CONFIG``). """ self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/") self._model = model or OLLAMA_CONFIG["model"] self._timeout = timeout or OLLAMA_CONFIG["timeout"] def get_embedding(self, text: str) -> Optional[List[float]]: """Call Ollama embeddings API. Returns None on any failure.""" url = f"{self._base_url}/api/embeddings" payload = json.dumps( {"model": self._model, "prompt": text} ).encode("utf-8") headers = {"Content-Type": "application/json"} try: req = urllib.request.Request( url, data=payload, headers=headers, method="POST" ) with urllib.request.urlopen(req, timeout=self._timeout) as resp: data = json.loads(resp.read().decode("utf-8")) embedding = data.get("embedding") if not embedding or not isinstance(embedding, list): logger.error( "Ollama returned invalid embedding: %s", type(embedding) ) return None return [float(v) for v in embedding] except urllib.error.HTTPError as e: logger.warning("Ollama HTTP %d: %s", e.code, e.reason) return None except urllib.error.URLError as e: logger.warning("Ollama connection failed: %s", e) return None except (json.JSONDecodeError, TypeError, ValueError) as e: logger.error("Ollama response parse error: %s", e) return None except Exception as e: logger.error("Unexpected error in get_embedding: %s", e) return None # ── LLM Client Interface (injectable) ─────────────────────────────────── 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 ``IntentClassifier`` can work with real Ollama, mocks, or alternative backends without change. Implementations must be thread-safe since ``IntentClassifier`` calls ``classify()`` synchronously inside ``asyncio.to_thread``. """ @abc.abstractmethod def classify(self, text: str) -> Optional[str]: """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.""" ... @abc.abstractmethod def generate(self, prompt: str) -> Optional[str]: """Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung). Wird vom Raum-Router verwendet, um die Zielraum-ID direkt vom LLM zu erhalten. Anders als ``classify()`` wird die Antwort NICHT gegen Intent-Kategorien validiert. Args: prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT). Returns: Die LLM-Antwort als String (getrimmt), oder None bei Fehler. """ ... class OllamaLLMClient(LLMClient): """LLM client backed by Ollama's `/api/generate` endpoint. Wraps ``urllib.request.urlopen`` so the transport is hidden behind the ``LLMClient`` interface. Works with every Ollama model that exposes the generate API (``qwen2.5:7b`` recommended). Usage:: client = OllamaLLMClient() category = client.classify("Wie funktioniert das Plugin?") # → "direct_question" """ def __init__( self, base_url: Optional[str] = None, model: Optional[str] = None, timeout: Optional[float] = None, ) -> None: """ Args: base_url: Ollama base URL (default from ``config.LLM_CONFIG``). model: LLM model (default from ``config.LLM_CONFIG``). timeout: Deprecated/ignored. Der Timeout wird seit F93 adaptiv über ``adaptive_timeout.current_timeout()`` bestimmt; der Parameter bleibt nur für API-Kompatibilität erhalten. """ self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/") self._model = model or LLM_CONFIG["model"] # F93: Modell-Schlüssel registrieren (Reset bei Modellwechsel). adaptive_timeout.set_model(self._base_url, self._model) def _call_generate(self, prompt: str) -> Optional[str]: """Führe einen /api/generate-Call mit adaptivem Timeout aus. F93: Der Timeout wird aus der selbstkalibrierenden Statistik (``adaptive_timeout.current_timeout()``) bezogen. Die gemessene Antwortzeit wird zurückgespeist (``record``), Timeouts/Fehler als außerhalb-Toleranz gewertet (Eskalations-Streak). Returns: Der ``response``-String oder None bei Fehler/Timeout. """ url = f"{self._base_url}/api/generate" payload = json.dumps( { "model": self._model, "prompt": prompt, "stream": False, "options": { "temperature": LLM_CONFIG["temperature"], "num_predict": LLM_CONFIG["max_tokens"], } } ).encode("utf-8") headers = {"Content-Type": "application/json"} timeout = adaptive_timeout.current_timeout() t0 = time.monotonic() # F169: in-flight-Zähler für Race-Condition-Erkennung beim Reset. adaptive_timeout.begin_call() try: req = urllib.request.Request( url, data=payload, headers=headers, method="POST" ) with urllib.request.urlopen(req, timeout=timeout) as resp: data = json.loads(resp.read().decode("utf-8")) duration = time.monotonic() - t0 adaptive_timeout.record(duration, success=True) return data.get("response", "") except (urllib.error.HTTPError, urllib.error.URLError) as e: duration = time.monotonic() - t0 adaptive_timeout.record(duration, success=False) logger.warning("Ollama request failed: %s", e) return None except (json.JSONDecodeError, TypeError, ValueError) as e: # F6a: Parse-Fehler = kaputtes Modell/Endpoint (Server liefert Müll # oder Verarbeitungsfehler) → success=False, damit der # Eskalations-Streak getriggert wird (Spec: Eskalation bei # "Modell-/Endpoint-Problem"). duration = time.monotonic() - t0 adaptive_timeout.record(duration, success=False) logger.error("Ollama response parse error: %s", e) return None except Exception as e: duration = time.monotonic() - t0 adaptive_timeout.record(duration, success=False) logger.error("Unexpected error in LLM call: %s", e) return None finally: # F169: in-flight-Zähler immer dekrementieren (auch bei Exception). adaptive_timeout.end_call() def classify(self, text: str) -> Optional[str]: """Call Ollama generate API. Returns category or None on any failure.""" response_text = self._call_generate(text) if not response_text: logger.error("Ollama returned empty response") return None # Trim whitespace and normalize category 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) 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} 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 def generate(self, prompt: str) -> Optional[str]: """Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung). Sendet den Prompt an Ollama's /api/generate und gibt die Antwort unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet. Args: prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT). Returns: Die LLM-Antwort als String (getrimmt), oder None bei Fehler. """ response_text = self._call_generate(prompt) if not response_text: logger.error("Ollama returned empty response for generate()") return None return response_text.strip() 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 gehalten (Caching für Sub-100ms-Performance). Usage:: classifier = IntentClassifier() await classifier.initialize() # pre-compute category vectors result = await classifier.classify("Wie funktioniert das Plugin?") print(result.category) # → "direct_question" """ def __init__( self, base_url: Optional[str] = None, model: Optional[str] = None, timeout: Optional[float] = None, embedding_client: Optional[EmbeddingClient] = None, llm_client: Optional[LLMClient] = None, ) -> None: """ Args: base_url: Ollama-Basis-URL (default: aus config.py). Ignoriert wenn *embedding_client* gesetzt ist. model: Embedding-Modell (default: 'nomic-embed-text'). Ignoriert wenn *embedding_client* gesetzt ist. timeout: Timeout in Sekunden (default: 5.0). Ignoriert wenn *embedding_client* gesetzt ist. embedding_client: Optionales ``EmbeddingClient``-Interface. Wenn gesetzt, werden alle Embedding-Calls an diesen Client delegiert (z.B. für Mocks oder alternative Backends). Wenn ``None``, wird ein ``OllamaEmbeddingClient`` mit *base_url*, *model* und *timeout* erstellt. llm_client: Optionales ``LLMClient``-Interface. Wenn gesetzt, werden LLM-Calls an diesen Client delegiert. Wenn ``None`` und LLM aktiviert ist, wird ein ``OllamaLLMClient`` erstellt. """ if embedding_client is not None: self._embedding_client: EmbeddingClient = embedding_client self._base_url = "injected" self._model = "injected" self._timeout = 0.0 else: self._embedding_client = OllamaEmbeddingClient( base_url=base_url, model=model, timeout=timeout ) self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/") self._model = model or OLLAMA_CONFIG["model"] self._timeout = timeout or OLLAMA_CONFIG["timeout"] self._embedding_dim = OLLAMA_CONFIG["embedding_dim"] # Handle LLM client self._llm_enabled = LLM_CONFIG["enabled"] if self._llm_enabled: if llm_client is not None: self._llm_client: Optional[LLMClient] = llm_client else: self._llm_client = OllamaLLMClient( base_url=LLM_CONFIG["base_url"], model=LLM_CONFIG["model"], timeout=LLM_CONFIG["timeout"] ) else: self._llm_client = None # Cache: category → embedding vector (768 floats) self._category_vectors: Dict[str, List[float]] = {} self._initialized: bool = False self._init_error: Optional[str] = None # Cache: message text → embedding (avoids re-embedding duplicates) self._message_cache: Dict[str, List[float]] = {} self._cache_max_size: int = 100 def _keyword_prefilter(self, text: str) -> Optional[str]: """Stufe 0: Keyword-Vorfilter. Liefert Intent-Kategorie oder None.""" t = text.lower() # 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, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: import asyncio return await asyncio.to_thread(self._llm_classify_sync, text, scores) 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 return self._llm_client.verify_confidence(text, scores) except Exception as e: logger.warning("LLM classification failed: %s", e) return None async def _llm_raw(self, prompt: str) -> Optional[str]: """Send a raw prompt to the LLM and return its response. Unlike ``_llm_classify_sync``, this does NOT validate against Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form output. Used by the router for LLM_ROOM_PROMPT. Wraps synchronous OllamaLLMClient.generate() in asyncio.to_thread(). Args: prompt: The complete prompt to send. Returns: The LLM's response text (stripped), or None on failure. """ import asyncio try: if not self._llm_client or not self._llm_enabled: return None return await asyncio.to_thread(self._llm_client.generate, prompt) except Exception as e: logger.warning("LLM raw call failed: %s", e) return None # ── Public API ────────────────────────────────────────────────────── async def initialize(self) -> bool: """Pre-compute category vectors. Returns True on success. Must be called once before classify(). Safe to call multiple times — subsequent calls are no-ops if already initialized. This is async to fit into the adapter's async startup lifecycle. Internally calls synchronous urllib. """ import asyncio return await asyncio.to_thread(self._initialize_sync) def _initialize_sync(self) -> bool: """Synchronous initialization logic.""" if self._initialized: return True logger.info( "Initializing intent classifier: model=%s, base_url=%s, timeout=%.1fs", self._model, self._base_url, self._timeout, ) success = True for category, text in CATEGORY_TEXTS.items(): vector = self._get_embedding(text) if vector is None: logger.error( "Failed to compute embedding for category '%s' — " "classifier will use fallback", category, ) self._init_error = f"Failed to embed category '{category}'" success = False break self._category_vectors[category] = vector logger.debug("Category '%s' vectorized (%d dims)", category, len(vector)) if success: self._initialized = True logger.info( "Intent classifier initialized successfully (%d categories)", len(self._category_vectors), ) return success async def classify(self, text: str) -> Optional[ClassificationResult]: """Classify a message text. Returns None if embedding fails completely. This is async to fit into the adapter's async pipeline. Internally calls synchronous urllib. Args: text: The message text to classify. Returns: ClassificationResult with category and confidence, or None if the classifier is not initialized or embedding fails. """ import asyncio return await asyncio.to_thread(self._classify_sync, text) def _classify_sync(self, text: str) -> Optional[ClassificationResult]: if not self._initialized: logger.warning("classify() called before initialize() — returning None") return None if not text or not text.strip(): return None text = text.strip() t0 = time.monotonic() # Stufe 0: Keyword-Vorfilter keyword_result = self._keyword_prefilter(text) 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=keyword_result, confidence=confidence, all_scores={keyword_result: confidence}, latency_ms=latency_ms, fallback=True, ) # Stufe 1: Embedding-Klassifikation vector = self._get_cached_or_compute(text) if vector is None: logger.debug("Failed to embed message: %.60s...", text) return None # Compare against all category vectors scores: Dict[str, float] = {} best_category: str = "" best_score: float = -1.0 for category, cat_vector in self._category_vectors.items(): score = self._cosine_similarity(vector, cat_vector) scores[category] = score if score > best_score: best_score = score best_category = category latency_ms = (time.monotonic() - t0) * 1000.0 if best_score < 0: return None # 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=final_category, confidence=final_score, all_scores=scores, latency_ms=latency_ms, fallback=False, llm_verified=llm_verified, ) # ── Embedding-API ─────────────────────────────────────────────────── def _get_embedding(self, text: str) -> Optional[List[float]]: """Delegate to the injectable ``EmbeddingClient``. Returns None on any failure — the caller (router) handles fallback. """ return self._embedding_client.get_embedding(text) def _get_cached_or_compute(self, text: str) -> Optional[List[float]]: """Return cached embedding or compute and cache a new one.""" # Simple LRU-like: evict if over max if len(self._message_cache) >= self._cache_max_size: # Evict the oldest key (first inserted) oldest = next(iter(self._message_cache)) del self._message_cache[oldest] if text in self._message_cache: return self._message_cache[text] vector = self._get_embedding(text) if vector is not None: self._message_cache[text] = vector return vector # ── Math ──────────────────────────────────────────────────────────── @staticmethod def _cosine_similarity(a: List[float], b: List[float]) -> float: """Compute cosine similarity between two vectors. Returns 0.0 if either vector has zero magnitude. """ if len(a) != len(b): raise ValueError( f"Vector dimension mismatch: {len(a)} vs {len(b)}" ) dot = sum(x * y for x, y in zip(a, b)) norm_a = math.sqrt(sum(x * x for x in a)) norm_b = math.sqrt(sum(y * y for y in b)) if norm_a == 0.0 or norm_b == 0.0: return 0.0 return dot / (norm_a * norm_b) # ── Introspection ─────────────────────────────────────────────────── @property def is_initialized(self) -> bool: """True if category vectors have been computed successfully.""" return self._initialized @property def init_error(self) -> Optional[str]: """Error message from initialization, or None.""" return self._init_error @property def category_count(self) -> int: """Number of cached category vectors.""" return len(self._category_vectors) @property def cache_size(self) -> int: """Number of cached message embeddings.""" return len(self._message_cache)