""" Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434). 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. """ 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 from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD logger = logging.getLogger(__name__) @dataclass class ClassificationResult: """Ergebnis einer Embedding-basierten Klassifikation.""" category: str """Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'.""" 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).""" def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool: """True wenn die Konfidenz über dem Schwellenwert liegt.""" return self.confidence >= threshold 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 ``MessageClassifier`` can work with real Ollama, mocks, or alternative backends without change. Implementations must be thread-safe since ``MessageClassifier`` 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 ``MessageClassifier`` can work with real Ollama, mocks, or alternative backends without change. Implementations must be thread-safe since ``MessageClassifier`` 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.""" ... 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?") # → "FRAGE" """ 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: Request timeout in seconds (default from ``config.LLM_CONFIG``). """ self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/") self._model = model or LLM_CONFIG["model"] self._timeout = timeout or LLM_CONFIG["timeout"] def classify(self, text: str) -> Optional[str]: """Call Ollama generate API. Returns category or None on any failure.""" url = f"{self._base_url}/api/generate" payload = json.dumps( { "model": self._model, "prompt": text, "stream": False, "options": { "temperature": LLM_CONFIG["temperature"], "num_predict": LLM_CONFIG["max_tokens"], } } ).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")) response_text = data.get("response", "") if not response_text: logger.error("Ollama returned empty response") return None # Trim whitespace and normalize category category = response_text.strip().upper() if category in ("FAKT", "FRAGE", "ALARM"): return category else: logger.warning("LLM returned invalid category: %s", category) return None 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 classify: %s", e) return None class MessageClassifier: """Embedding-basierter Nachrichten-Klassifizierer. 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 = MessageClassifier() await classifier.initialize() # pre-compute category vectors result = await classifier.classify("Wie funktioniert das Plugin?") print(result.category) # → "FRAGE" """ 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 'ALARM', 'FRAGE' oder None.""" from .config import FALLBACK_KEYWORDS 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" return None async def _llm_classify(self, text: str) -> Optional[str]: import asyncio return await asyncio.to_thread(self._llm_classify_sync, text) def _llm_classify_sync(self, text: str) -> Optional[str]: 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 except Exception as e: logger.warning("LLM classification failed: %s", e) return None def _llm_raw_sync(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 FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the ``LLM_ROOM_PROMPT`` where the expected answer is a room name. Args: prompt: The complete prompt to send. Returns: The LLM's response text (stripped), or None on failure. """ try: if not self._llm_client or not self._llm_enabled: return None result = self._llm_client.classify(prompt) if result: return result.strip() return None 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 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( "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 == "ALARM": # ALARM hat höchste Priorität - sofortige Rückgabe latency_ms = (time.monotonic() - t0) * 1000.0 return ClassificationResult( category="ALARM", confidence=0.95, # Hohe Konfidenz für Keyword-Treffer all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0}, latency_ms=latency_ms, fallback=False, ) # Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert) # 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 # Prüfe, ob die Embedding-Konfidenz ausreicht if best_score >= LLM_CONFIDENCE_THRESHOLD: return ClassificationResult( category=best_category, confidence=best_score, all_scores=scores, latency_ms=latency_ms, fallback=False, ) # Stufe 2: LLM-Klassifikation, wenn Konfidenz niedrig ist if self._llm_enabled and best_score < LLM_CONFIDENCE_THRESHOLD and self._llm_client: llm_category = self._llm_classify_sync(text) if llm_category: latency_ms = (time.monotonic() - t0) * 1000.0 return ClassificationResult( category=llm_category, confidence=0.95, # Hohe Konfidenz für LLM-Klassifikation all_scores=scores, latency_ms=latency_ms, fallback=False, ) # Ansonsten: originales Embedding-Ergebnis zurückgeben (auch wenn unter Schwellwert) return ClassificationResult( category=best_category, confidence=best_score, all_scores=scores, latency_ms=latency_ms, fallback=False, ) # ── 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)