Files
floop/code/knowledge/extract.py
T
onibot 99f8b6e9db knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2)
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
typed Fact gains start/end/point (optional, ISO-ish) + granularity +
orders [{rel: before|after|concurrent, other: <sibling index>}] — the
text's connectives transcribed, not classified. The Allen algebra stays
a COMPUTED VIEW over endpoints.

- checks.py: every stated date must be CONTAINED IN THE QUOTE — an
  invented date rejects the whole candidate (LLM proposes, code
  verifies against the source surface).
- store.py: edges gain t_start/t_end (valid-time window, None end =
  OPEN, honest to 'since 2018'); fact_order table (order assertions
  between addressable facts — reification is free); _classify consumes
  interval arithmetic: overlapping open windows -> alternatives
  (coexistence provable, no statistics), disjoint windows ->
  succession (never a conflict). Boundary law at year granularity:
  [2014,2018) vs [2018,None) = succession — the mandate changed hands
  in 2018. add_fact_order validates rel in {before, after, concurrent}.
- expert.py: _ingest_candidate returns (merged, eid) and passes the
  windows; the prose path collects positional fact_ids and wires the
  orders' sibling references to real edge ids (malformed refs skip
  honestly).

Tests: temporal.py 6/6 (typed fields, containment rejection, open-
window overlap -> alternatives, touch-at-year -> succession, empty
stays empty, fact_order ingest) + 7/7 interval cases incl. the
open-past degenerate. Suite: all green.

LIVE (run 20261025-205018, cold KG, glm-5.3-flash): 29 edges carry
windows (Spain 2018 / PSOE 2017 / SI 2022 all open-ended), 25
fact_order rows (Madrid before Congress of Deputies...), 8 invented
end-dates REJECTED by the containment check (the footballer Pedro
articles — the check catching exactly what it should), 0 conflicts.
The run itself answered UNKNOWN on its Q1 ("what DATE did he take
office") — honest: the blind extractor did not transcribe the exact
date this run and the noisy re-probe view (four Pedros) is the known
branch weakness, not a phase-2 regression. Design note for phase 4:
the three presidencies live under DIFFERENT rels, so the alternatives
substrate must be queried trans-rel by the consumer (alternatives_of
is per-rel by construction).
2026-10-25 21:07:34 +01:00

195 lines
9.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
and its TEMPORAL RESTRICTIONS (phase 2 — restrictions, never Allen
labels; the algebra is a computed view over these endpoints).
All temporal fields are optional and must be CONTAINED IN THE QUOTE
(an invented date fails the containment check and the whole fact is
rejected — the honest law). 'since YYYY' means start=YYYY, end OPEN.
Granularity is honest precision: 'year' | 'month' | 'day'.
orders: temporal-order assertions BETWEEN SIBLING FACTS of the same
extraction, by their 0-based position in the same facts list —
{rel: before|after|concurrent, other: <index>}."""
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)")
start: str | None = dspy.OutputField(
default=None,
desc="when the fact begins, as stated in the text (a year like 2018, or a full date); empty when the text states no start")
end: str | None = dspy.OutputField(
default=None,
desc="when the fact ends, as stated in the text; empty when ongoing/unknown")
point: str | None = dspy.OutputField(
default=None,
desc="for point-in-time facts (events): the stated date; empty otherwise")
granularity: str | None = dspy.OutputField(
default=None,
desc="precision of the stated dates: year, month, or day; empty when no dates")
orders: list[dict] = dspy.OutputField(
default_factory=list,
desc="temporal order between THIS fact and SIBLING facts of the same list, "
"ONLY when the text asserts it with a connective (before/after/at the same "
"time as); each entry {rel: before|after|concurrent, other: <0-based index "
"of the sibling fact>}; empty when the text asserts no order")
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 — the value ONLY, no row citations, no parenthetical explanations")
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