Files
floop/code/knowledge/extract.py
T
onibot 872d4b9d42 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.
2026-10-23 08:44:36 +02:00

179 lines
8.7 KiB
Python

"""LLM extraction per chunk (map) — dspy Signatures, minimal per floop convention.
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
VERBATIM spans. The containment check (checks.py) validates every span against
the FULL document text — so chunking can never fake a quote.
"""
from __future__ import annotations
from enum import Enum
import dspy
from pydantic import BaseModel
class Confidence(str, Enum):
"""Honest self-assessment of an answer drawn from KG rows."""
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
class Fact(BaseModel):
"""One fact extracted from a text, with its verbatim supporting quote."""
subject: str = dspy.OutputField(desc="the fact's subject entity")
relation: str = dspy.OutputField(desc="the relation between subject and object")
object: str = dspy.OutputField(desc="the fact's object / value")
quote: str = dspy.OutputField(
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
class TranslateSignature(dspy.Signature):
"""You are the TRANSLATE step of a knowledge machine. Turn the question
into Wikipedia search queries AND resolved entity terms. Resolve
references ('that state', 'the same river') using the context: the original
question and the evidence rows already gathered."""
question: str = dspy.InputField()
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
queries: list[str] = dspy.OutputField(
desc="1-2 Wikipedia search queries, most specific first")
entities: list[str] = dspy.OutputField(
desc="the resolved entity names the answer is about")
class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text,
extract facts about the NAMED ENTITIES: biographical facts, positions
and offices held, events, relationships, quantities with their units.
Each fact carries its verbatim quote: the FULL sentence or table ROW
that states it, copied exactly (at least 10 characters). Only facts
the text states; no inference. Extract facts for ALL the named
entities that appear in the text; skip entities not mentioned."""
entities: str = dspy.InputField(
desc="the named entities to extract facts about, comma separated")
heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField()
facts: list[Fact] = dspy.OutputField(
desc="the extracted facts; empty list if none")
class AnswerFromKG(dspy.Signature):
"""You are the ANSWER step of a knowledge machine. Answer the question using
ONLY the given knowledge-graph rows, each with its quote and source. Cite
rows by id. If the rows do not answer it, say UNKNOWN."""
question: str = dspy.InputField()
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
confidence: Confidence = dspy.OutputField(
desc="high: rows settle it; medium: plausible but partial; low: weak support")
class VerifyCountSignature(dspy.Signature):
"""You are the VERIFY step of a knowledge machine. A list answer has been
ingested from a table in one article (set_name, N elements). Find ONE
sentence in the article prose that states the expected count of that set
(independently of the table). Quote it VERBATIM. If no such sentence
exists, write NOQUOTE.
Example:
set_name: European Union member states
count: 27
GOOD quote: "The European Union (EU) is a supranational union of 27
member states that are party to the EU's founding treaties"
BAD (not a count statement): a row of the table itself."""
set_name: str = dspy.InputField()
count: str = dspy.InputField()
text: str = dspy.InputField(desc="the article prose WITHOUT the tables")
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
class TableChoice(BaseModel):
"""The table chosen as the answer's enumeration, if any."""
table_index: int = dspy.OutputField(desc="the chosen table's index")
column: str = dspy.OutputField(desc="header name of the column holding the answer elements")
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates")
class SelectTableSignature(dspy.Signature):
"""You are the SELECT TABLE step of a knowledge machine. Given a question
and the tables found in an article (index, caption, header columns, row
count — NOT the rows), decide: does one of these tables enumerate the
answer?"""
question: str = dspy.InputField()
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'")
chosen: TableChoice | None = dspy.OutputField(
desc="the chosen table and its answer column; null when NO table enumerates the answer")
class PromotionDecision(BaseModel):
"""One table's promotion verdict."""
table_index: int = dspy.OutputField(desc="the table's index from the list")
promote: bool = dspy.OutputField(
desc="True when this table holds data about those entities for the goal")
column: str = dspy.OutputField(
desc="when promoted: the header holding the goal's values; empty otherwise")
class SkimPromoteSignature(dspy.Signature):
"""You are the SKIM PROMOTE step of a knowledge machine. While fetching
articles for one question, tables were seen in passing that carry
quantity data but match none of the goal's words (the goal's vocabulary
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
Given the run's goal, the entities it is about, and the tables' identity
(caption, headers, row count, quantity signals — NOT the rows), decide
per table whether it holds data about those entities for the goal."""
goal: str = dspy.InputField(desc="the run's overall goal question")
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
decisions: list[PromotionDecision] = dspy.OutputField(
desc="one verdict per table in the list")
class TableRelevanceDecision(BaseModel):
"""One table's extraction-worthiness verdict (skim-level stop)."""
table_index: int = dspy.OutputField(desc="the table's index from the list")
relevant: bool = dspy.OutputField(
desc="True when this table plausibly holds facts about the entities "
"or their context; False when its subject is clearly different "
"(wrong country, wrong topic, unrelated data)")
reason: str = dspy.OutputField(
desc="short reason, e.g. 'about world rivers, not Italy'")
class SkimTableSignature(dspy.Signature):
"""You are the TABLE SKIM step of a knowledge machine. For each table
in an article, given its IDENTITY (caption, header columns, row count
— and the FIRST FEW ROWS only), decide whether the table plausibly
holds facts about the named entities or the question's subject. The
goal is to skip hopeless tables BEFORE paying extraction, and to
never skip a table that mentions the entities. Decide per table."""
question: str = dspy.InputField(
desc="the current question (planning context; the extractor itself "
"never sees it)")
entities: str = dspy.InputField(
desc="the named entities the question is about, comma separated")
tables: str = dspy.InputField(
desc="one block per table: 'idx | caption | header: a, b, c | rows: N | first rows: <3-5 sample rows>'")
decisions: list[TableRelevanceDecision] = dspy.OutputField(
desc="one verdict per table in the list")
def parse_facts(raw: str) -> list[dict]:
"""LEGACY pipe parser — kept ONLY for tests that script extractor
responses as text. Production code consumes typed `Fact` objects from
dspy directly (see ExtractSignature.facts). Do not use in new code."""
out: list[dict] = []
for line in (raw or "").strip().splitlines():
line = line.strip()
if not line or "|" not in line:
continue
parts = [p.strip() for p in line.split("|", 3)]
if len(parts) < 4:
continue
subject, relation, obj, quote = parts
if not (subject and relation and obj and quote):
continue
out.append({"subject": subject, "relation": relation,
"object": obj, "quote": quote})
return out