65 lines
2.6 KiB
Python
65 lines
2.6 KiB
Python
"""Embedding client for semantic KG retrieval (research/semantic-kg).
|
|
|
|
Config: local ollama /api/embed (nomic-embed-text, 768d) — the only
|
|
proven endpoint (ollama.com has NO embeddings API: 404 on /v1/embeddings,
|
|
401 on /api/embed). Failure is honest: embed() raises EmbedderDown, the
|
|
expert degrades to the lexical probe (law: offline fallback, never a
|
|
dead run). No API keys in code.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import math
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
DEFAULT_MODEL = "nomic-embed-text:latest"
|
|
DEFAULT_URL = "http://127.0.0.1:11435/api/embed"
|
|
|
|
|
|
class EmbedderDown(Exception):
|
|
"""The embedding endpoint is unreachable or misbehaving — the caller
|
|
degrades to the lexical probe (offline fallback law)."""
|
|
|
|
|
|
def embed(texts: list[str], model: str = DEFAULT_MODEL,
|
|
url: str = DEFAULT_URL, timeout: int = 60) -> list[list[float]]:
|
|
"""Batch-embed texts via ollama /api/embed. Raises EmbedderDown on any
|
|
transport/format error — honest failure, never fabricated vectors."""
|
|
texts = [t or " " for t in texts]
|
|
if not texts:
|
|
return []
|
|
payload = json.dumps({"model": model, "input": texts}).encode()
|
|
req = urllib.request.Request(
|
|
url, data=payload, headers={"Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
data = json.load(r)
|
|
except Exception as e: # noqa: BLE001 — one honest exception type
|
|
raise EmbedderDown(f"{url}: {e}") from e
|
|
vecs = data.get("embeddings") if isinstance(data, dict) else None
|
|
if not isinstance(vecs, list) or len(vecs) != len(texts):
|
|
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
|
f"{len(vecs) if isinstance(vecs, list) else 0}")
|
|
dimension = None
|
|
for vector in vecs:
|
|
if (not isinstance(vector, list) or not vector
|
|
or any(type(x) not in (int, float) or not math.isfinite(x)
|
|
for x in vector)
|
|
or not any(vector)):
|
|
raise EmbedderDown(f"{url}: expected finite, nonzero numeric vectors")
|
|
if dimension is not None and len(vector) != dimension:
|
|
raise EmbedderDown(f"{url}: inconsistent embedding dimensions")
|
|
dimension = len(vector)
|
|
return vecs
|
|
|
|
|
|
def cosine(a: list[float], b: list[float]) -> float:
|
|
"""Plain cosine — at hundreds of edges numpy brute force is not worth
|
|
the dependency."""
|
|
dot = sum(x * y for x, y in zip(a, b))
|
|
na = sum(x * x for x in a) ** 0.5
|
|
nb = sum(y * y for y in b) ** 0.5
|
|
if na == 0 or nb == 0:
|
|
return 0.0
|
|
return dot / (na * nb) |