Files
Hermes_rocket.chat_Plugin/plugin/archivar/classifier.py
T
Hermes Agent bb8623aed5 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
2026-06-03 10:17:03 +02:00

388 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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
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
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,
) -> 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.
"""
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"]
# 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
# ── 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()
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
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)