88b7149dd1
- Add archivar/ submodule to plugin/ (5 files, relative imports) - Update adapter.py with relative Archivar import from .archivar.adapter_integration - install.sh: fix --non-interactive env-var reading (Z.316-318, Bug #7) - install.sh: recursive file copy (was 4 flat files, now entire plugin/ tree incl. submodules) - install.sh: Ollama presence check + nomic-embed-text pull - install.sh: write OLLAMA_BASE_URL to rocketchat.env - install.sh: add new message keys (collama_check, nomic_pull, nomic_ok, nomic_fail, copied) Closes: Archivar delivery gap (2026-06-03) Reviewed-by: Bernd (Advisor)
388 lines
16 KiB
Python
388 lines
16 KiB
Python
1|"""
|
||
2|Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434).
|
||
3|
|
||
4|Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||
5|berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit.
|
||
6|Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult
|
||
7|zurückgegeben — der Router übernimmt dann den Fallback.
|
||
8|"""
|
||
9|
|
||
10|from __future__ import annotations
|
||
11|
|
||
12|import abc
|
||
13|import json
|
||
14|import logging
|
||
15|import math
|
||
16|import time
|
||
17|import urllib.error
|
||
18|import urllib.request
|
||
19|from dataclasses import dataclass, field
|
||
20|from typing import Dict, List, Optional
|
||
21|
|
||
22|from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD
|
||
23|
|
||
24|logger = logging.getLogger(__name__)
|
||
25|
|
||
26|
|
||
27|@dataclass
|
||
28|class ClassificationResult:
|
||
29| """Ergebnis einer Embedding-basierten Klassifikation."""
|
||
30|
|
||
31| category: str
|
||
32| """Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'."""
|
||
33|
|
||
34| confidence: float
|
||
35| """Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
||
36|
|
||
37| all_scores: Dict[str, float] = field(default_factory=dict)
|
||
38| """Alle Kategorie-Scores für Debugging/Transparenz."""
|
||
39|
|
||
40| latency_ms: float = 0.0
|
||
41| """Gemessene Latenz der Embedding-API in Millisekunden."""
|
||
42|
|
||
43| fallback: bool = False
|
||
44| """True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||
45|
|
||
46| def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool:
|
||
47| """True wenn die Konfidenz über dem Schwellenwert liegt."""
|
||
48| return self.confidence >= threshold
|
||
49|
|
||
50| def is_fallback(self) -> bool:
|
||
51| """True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
||
52| return self.fallback
|
||
53|
|
||
54|
|
||
55|# ── Embedding Client Interface (injectable) ─────────────────────────────
|
||
56|
|
||
57|
|
||
58|class EmbeddingClient(abc.ABC):
|
||
59| """Interface for embedding providers. Injectable for testability.
|
||
60|
|
||
61| Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||
62| single ``get_embedding()`` method so that ``MessageClassifier`` can
|
||
63| work with real Ollama, mocks, or alternative backends without change.
|
||
64|
|
||
65| Implementations must be thread-safe since ``MessageClassifier`` calls
|
||
66| ``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
||
67| """
|
||
68|
|
||
69| @abc.abstractmethod
|
||
70| def get_embedding(self, text: str) -> Optional[List[float]]:
|
||
71| """Return the embedding vector for *text*, or None on failure.
|
||
72|
|
||
73| Args:
|
||
74| text: The text to embed.
|
||
75|
|
||
76| Returns:
|
||
77| A list of floats representing the embedding vector,
|
||
78| or ``None`` if the embedding could not be computed.
|
||
79| """
|
||
80| ...
|
||
81|
|
||
82| @classmethod
|
||
83| def __subclasshook__(cls, subclass):
|
||
84| if cls is EmbeddingClient:
|
||
85| if any("get_embedding" in B.__dict__ for B in subclass.__mro__):
|
||
86| return True
|
||
87| return NotImplemented
|
||
88|
|
||
89|
|
||
90|class OllamaEmbeddingClient(EmbeddingClient):
|
||
91| """Embedding client backed by Ollama's `/api/embeddings` endpoint.
|
||
92|
|
||
93| Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||
94| the ``EmbeddingClient`` interface. Works with every Ollama model
|
||
95| that exposes the embeddings API (``nomic-embed-text`` recommended).
|
||
96|
|
||
97| Usage::
|
||
98|
|
||
99| client = OllamaEmbeddingClient()
|
||
100| vector = client.get_embedding("hello world")
|
||
101| # → [0.123, -0.456, ...] (768 floats for nomic-embed-text)
|
||
102| """
|
||
103|
|
||
104| def __init__(
|
||
105| self,
|
||
106| base_url: Optional[str] = None,
|
||
107| model: Optional[str] = None,
|
||
108| timeout: Optional[float] = None,
|
||
109| ) -> None:
|
||
110| """
|
||
111| Args:
|
||
112| base_url: Ollama base URL (default from ``config.OLLAMA_CONFIG``).
|
||
113| model: Embedding model (default from ``config.OLLAMA_CONFIG``).
|
||
114| timeout: Request timeout in seconds (default from ``config.OLLAMA_CONFIG``).
|
||
115| """
|
||
116| self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||
117| self._model = model or OLLAMA_CONFIG["model"]
|
||
118| self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||
119|
|
||
120| def get_embedding(self, text: str) -> Optional[List[float]]:
|
||
121| """Call Ollama embeddings API. Returns None on any failure."""
|
||
122| url = f"{self._base_url}/api/embeddings"
|
||
123| payload = json.dumps(
|
||
124| {"model": self._model, "prompt": text}
|
||
125| ).encode("utf-8")
|
||
126| headers = {"Content-Type": "application/json"}
|
||
127|
|
||
128| try:
|
||
129| req = urllib.request.Request(
|
||
130| url, data=payload, headers=headers, method="POST"
|
||
131| )
|
||
132| with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||
133| data = json.loads(resp.read().decode("utf-8"))
|
||
134| embedding = data.get("embedding")
|
||
135| if not embedding or not isinstance(embedding, list):
|
||
136| logger.error(
|
||
137| "Ollama returned invalid embedding: %s", type(embedding)
|
||
138| )
|
||
139| return None
|
||
140| return [float(v) for v in embedding]
|
||
141| except urllib.error.HTTPError as e:
|
||
142| logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||
143| return None
|
||
144| except urllib.error.URLError as e:
|
||
145| logger.warning("Ollama connection failed: %s", e)
|
||
146| return None
|
||
147| except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||
148| logger.error("Ollama response parse error: %s", e)
|
||
149| return None
|
||
150| except Exception as e:
|
||
151| logger.error("Unexpected error in get_embedding: %s", e)
|
||
152| return None
|
||
153|
|
||
154|
|
||
155|class MessageClassifier:
|
||
156| """Embedding-basierter Nachrichten-Klassifizierer.
|
||
157|
|
||
158| Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
||
159| Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
||
160| gehalten (Caching für Sub-100ms-Performance).
|
||
161|
|
||
162| Usage::
|
||
163|
|
||
164| classifier = MessageClassifier()
|
||
165| await classifier.initialize() # pre-compute category vectors
|
||
166| result = await classifier.classify("Wie funktioniert das Plugin?")
|
||
167| print(result.category) # → "FRAGE"
|
||
168| """
|
||
169|
|
||
170| def __init__(
|
||
171| self,
|
||
172| base_url: Optional[str] = None,
|
||
173| model: Optional[str] = None,
|
||
174| timeout: Optional[float] = None,
|
||
175| embedding_client: Optional[EmbeddingClient] = None,
|
||
176| ) -> None:
|
||
177| """
|
||
178| Args:
|
||
179| base_url: Ollama-Basis-URL (default: aus config.py).
|
||
180| Ignoriert wenn *embedding_client* gesetzt ist.
|
||
181| model: Embedding-Modell (default: 'nomic-embed-text').
|
||
182| Ignoriert wenn *embedding_client* gesetzt ist.
|
||
183| timeout: Timeout in Sekunden (default: 5.0).
|
||
184| Ignoriert wenn *embedding_client* gesetzt ist.
|
||
185| embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||
186| Wenn gesetzt, werden alle Embedding-Calls an diesen
|
||
187| Client delegiert (z.B. für Mocks oder alternative
|
||
188| Backends). Wenn ``None``, wird ein
|
||
189| ``OllamaEmbeddingClient`` mit *base_url*, *model*
|
||
190| und *timeout* erstellt.
|
||
191| """
|
||
192| if embedding_client is not None:
|
||
193| self._embedding_client: EmbeddingClient = embedding_client
|
||
194| self._base_url = "injected"
|
||
195| self._model = "injected"
|
||
196| self._timeout = 0.0
|
||
197| else:
|
||
198| self._embedding_client = OllamaEmbeddingClient(
|
||
199| base_url=base_url, model=model, timeout=timeout
|
||
200| )
|
||
201| self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||
202| self._model = model or OLLAMA_CONFIG["model"]
|
||
203| self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||
204| self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
||
205|
|
||
206| # Cache: category → embedding vector (768 floats)
|
||
207| self._category_vectors: Dict[str, List[float]] = {}
|
||
208| self._initialized: bool = False
|
||
209| self._init_error: Optional[str] = None
|
||
210|
|
||
211| # Cache: message text → embedding (avoids re-embedding duplicates)
|
||
212| self._message_cache: Dict[str, List[float]] = {}
|
||
213| self._cache_max_size: int = 100
|
||
214|
|
||
215| # ── Public API ──────────────────────────────────────────────────────
|
||
216|
|
||
217| async def initialize(self) -> bool:
|
||
218| """Pre-compute category vectors. Returns True on success.
|
||
219|
|
||
220| Must be called once before classify(). Safe to call multiple times —
|
||
221| subsequent calls are no-ops if already initialized.
|
||
222|
|
||
223| This is async to fit into the adapter's async startup lifecycle.
|
||
224| Internally calls synchronous urllib.
|
||
225| """
|
||
226| import asyncio
|
||
227| return await asyncio.to_thread(self._initialize_sync)
|
||
228|
|
||
229| def _initialize_sync(self) -> bool:
|
||
230| """Synchronous initialization logic."""
|
||
231| if self._initialized:
|
||
232| return True
|
||
233|
|
||
234| logger.info(
|
||
235| "Initializing classifier: model=%s, base_url=%s, timeout=%.1fs",
|
||
236| self._model, self._base_url, self._timeout,
|
||
237| )
|
||
238|
|
||
239| success = True
|
||
240| for category, text in CATEGORY_TEXTS.items():
|
||
241| vector = self._get_embedding(text)
|
||
242| if vector is None:
|
||
243| logger.error(
|
||
244| "Failed to compute embedding for category '%s' — "
|
||
245| "classifier will use fallback",
|
||
246| category,
|
||
247| )
|
||
248| self._init_error = f"Failed to embed category '{category}'"
|
||
249| success = False
|
||
250| break
|
||
251| self._category_vectors[category] = vector
|
||
252| logger.debug("Category '%s' vectorized (%d dims)", category, len(vector))
|
||
253|
|
||
254| if success:
|
||
255| self._initialized = True
|
||
256| logger.info(
|
||
257| "Classifier initialized successfully (%d categories)",
|
||
258| len(self._category_vectors),
|
||
259| )
|
||
260| return success
|
||
261|
|
||
262| async def classify(self, text: str) -> Optional[ClassificationResult]:
|
||
263| """Classify a message text. Returns None if embedding fails completely.
|
||
264|
|
||
265| This is async to fit into the adapter's async pipeline.
|
||
266| Internally calls synchronous urllib.
|
||
267|
|
||
268| Args:
|
||
269| text: The message text to classify.
|
||
270|
|
||
271| Returns:
|
||
272| ClassificationResult with category and confidence,
|
||
273| or None if the classifier is not initialized or embedding fails.
|
||
274| """
|
||
275| import asyncio
|
||
276| return await asyncio.to_thread(self._classify_sync, text)
|
||
277|
|
||
278| def _classify_sync(self, text: str) -> Optional[ClassificationResult]:
|
||
279| if not self._initialized:
|
||
280| logger.warning("classify() called before initialize() — returning None")
|
||
281| return None
|
||
282|
|
||
283| if not text or not text.strip():
|
||
284| return None
|
||
285|
|
||
286| text = text.strip()
|
||
287|
|
||
288| t0 = time.monotonic()
|
||
289|
|
||
290| vector = self._get_cached_or_compute(text)
|
||
291| if vector is None:
|
||
292| logger.debug("Failed to embed message: %.60s...", text)
|
||
293| return None
|
||
294|
|
||
295| # Compare against all category vectors
|
||
296| scores: Dict[str, float] = {}
|
||
297| best_category: str = ""
|
||
298| best_score: float = -1.0
|
||
299|
|
||
300| for category, cat_vector in self._category_vectors.items():
|
||
301| score = self._cosine_similarity(vector, cat_vector)
|
||
302| scores[category] = score
|
||
303| if score > best_score:
|
||
304| best_score = score
|
||
305| best_category = category
|
||
306|
|
||
307| latency_ms = (time.monotonic() - t0) * 1000.0
|
||
308|
|
||
309| if best_score < 0:
|
||
310| return None
|
||
311|
|
||
312| return ClassificationResult(
|
||
313| category=best_category,
|
||
314| confidence=best_score,
|
||
315| all_scores=scores,
|
||
316| latency_ms=latency_ms,
|
||
317| fallback=False,
|
||
318| )
|
||
319|
|
||
320| # ── Embedding-API ───────────────────────────────────────────────────
|
||
321|
|
||
322| def _get_embedding(self, text: str) -> Optional[List[float]]:
|
||
323| """Delegate to the injectable ``EmbeddingClient``.
|
||
324|
|
||
325| Returns None on any failure — the caller (router) handles fallback.
|
||
326| """
|
||
327| return self._embedding_client.get_embedding(text)
|
||
328|
|
||
329| def _get_cached_or_compute(self, text: str) -> Optional[List[float]]:
|
||
330| """Return cached embedding or compute and cache a new one."""
|
||
331| # Simple LRU-like: evict if over max
|
||
332| if len(self._message_cache) >= self._cache_max_size:
|
||
333| # Evict the oldest key (first inserted)
|
||
334| oldest = next(iter(self._message_cache))
|
||
335| del self._message_cache[oldest]
|
||
336|
|
||
337| if text in self._message_cache:
|
||
338| return self._message_cache[text]
|
||
339|
|
||
340| vector = self._get_embedding(text)
|
||
341| if vector is not None:
|
||
342| self._message_cache[text] = vector
|
||
343| return vector
|
||
344|
|
||
345| # ── Math ────────────────────────────────────────────────────────────
|
||
346|
|
||
347| @staticmethod
|
||
348| def _cosine_similarity(a: List[float], b: List[float]) -> float:
|
||
349| """Compute cosine similarity between two vectors.
|
||
350|
|
||
351| Returns 0.0 if either vector has zero magnitude.
|
||
352| """
|
||
353| if len(a) != len(b):
|
||
354| raise ValueError(
|
||
355| f"Vector dimension mismatch: {len(a)} vs {len(b)}"
|
||
356| )
|
||
357|
|
||
358| dot = sum(x * y for x, y in zip(a, b))
|
||
359| norm_a = math.sqrt(sum(x * x for x in a))
|
||
360| norm_b = math.sqrt(sum(y * y for y in b))
|
||
361|
|
||
362| if norm_a == 0.0 or norm_b == 0.0:
|
||
363| return 0.0
|
||
364|
|
||
365| return dot / (norm_a * norm_b)
|
||
366|
|
||
367| # ── Introspection ───────────────────────────────────────────────────
|
||
368|
|
||
369| @property
|
||
370| def is_initialized(self) -> bool:
|
||
371| """True if category vectors have been computed successfully."""
|
||
372| return self._initialized
|
||
373|
|
||
374| @property
|
||
375| def init_error(self) -> Optional[str]:
|
||
376| """Error message from initialization, or None."""
|
||
377| return self._init_error
|
||
378|
|
||
379| @property
|
||
380| def category_count(self) -> int:
|
||
381| """Number of cached category vectors."""
|
||
382| return len(self._category_vectors)
|
||
383|
|
||
384| @property
|
||
385| def cache_size(self) -> int:
|
||
386| """Number of cached message embeddings."""
|
||
387| return len(self._message_cache)
|
||
388| |