research(knowledge): semantic KG retrieval + question-blind extraction
Implements his design (RESEARCH-semantic-kg.md) on the research branch: 1. EMBEDDINGS (knowledge/embeddings.py): local ollama /api/embed, nomic-embed-text 768d — the only proven endpoint (ollama.com has NO embeddings API). Honest failure: EmbedderDown -> lexical probe fallback, never a dead run. 2. SEMANTIC PROBE: edge_vectors cache in the store (keyed edge_id + model + text_hash; upsert, last model wins), cosine rank over all cached edges, tau=0.45 from real calibration (rivers 0.49-0.52 must pass; cross-question Pedro-vs-rivers 0.35-0.38 must not). Hybrid _probe: lexical UNION semantic, dedup by eid. EdgeView gains eid. 3. QUESTION-BLIND EXTRACTION: ExtractSignature loses 'question' and stop_table — it receives ENTITIES only (from TRANSLATE + evidence + proper nouns) and transcribes their facts, capped per chunk (max_facts_per_chunk=12). Facts cache vectors at ingest. The KG fattens per-entity, reusable across questions (his cacheability argument). 4. STOP MOVES TO THE SKIM: SkimTableSignature decides per table from caption+header+row count+first rows (one LLM call per page) BEFORE any extraction spend; tables that literally name an entity skip the call. The extractor itself never judges relevance. VERIFIED: knowledge suite 8/8 (semantic.py new 4/4: lexical-missed edge surfaced, hybrid dedup, embedder-down degradation, cache upsert; tablefrags adapted: skim kills tables pre-extract). floop suite 9/9. Live E2E (glm): semantic probe fires live (+1 lexical-missed edge); blind extractor ingests 12-fact chunks; Pedro run answers 'himself' (3rd gov succeeded his 2nd — a reading trap, NOT a retrieval failure; INIT degraded honestly on garbage); rivers run burned budget on fan-out ROUTE calls (22x2) — both findings logged as open work on the research doc, not regressions of this PR.
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
"""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 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 not vecs or len(vecs) != len(texts):
|
||||
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
||||
f"{len(vecs) if vecs else 0}")
|
||||
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)
|
||||
Reference in New Issue
Block a user