Files
floop/code/knowledge/extract.py
T

261 lines
13 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.
Two-pass (two_pass.py): Pass 1 (ExtractClaims) extracts the claims WITH their
VERBATIM spans; Pass 2 (TypeClaim) types ONE claim — typing only, the model
never sees the quote; code composes Fact = FactNoQuote + verbatim (owner 1/11).
"""
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 FactNoQuote(BaseModel):
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")
start: str | None = dspy.OutputField(
default=None,
desc="when the fact begins, as stated in the claim (a year like 2018, or a full date); empty when the claim states no start")
end: str | None = dspy.OutputField(
default=None,
desc="when the fact ends, as stated in the claim; 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")
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 Claim(BaseModel):
"""One claim of Pass 1: the free-form claim PLUS the VERBATIM span
that states it. The quote is extracted HERE, in the same call that
reads the text (owner 1/11: the VERBATIM is obtained before the
typing — Pass 2 only enforces the Fact's typing)."""
claim: str = dspy.OutputField(
desc="the factual claim, coreferences resolved (entities named, "
"never pronouns)")
verbatim: str = dspy.OutputField(
desc="VERBATIM quote from the text that states the claim: the FULL "
"sentence or table row, copied exactly (at least 10 characters)")
class ExtractClaims(dspy.Signature):
"""You are the CLAIMS step of a knowledge machine. From the given text,
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
and offices held, biographical facts, events, relationships,
quantities with units. Each claim carries the VERBATIM quote that
states it: the FULL sentence or table row, copied exactly (at least
10 characters). Resolve coreferences: name the entity in the claim,
never a pronoun or a shorthand. Only what the text states; no
inference."""
entities: str = dspy.InputField(
desc="the named entities to extract claims about, comma separated")
heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField()
claims: list[Claim] = dspy.OutputField(
desc="the factual claims, each with its VERBATIM quote copied "
"exactly from the text; empty list if none")
class TypeClaim(dspy.Signature):
"""You are the TYPE step of a knowledge machine. Given ONE single claim,
type the claim into the typed fact schema: subject entity, relation,
object/value, and the temporal restrictions the claim states. All
temporal fields are optional. Only what the claim states; no
inference. If the claim cannot be typed honestly, return null."""
claim: str = dspy.InputField(desc="the claim to type")
fact: FactNoQuote | None = dspy.OutputField(
desc="the typed fact — subject, relation, object, temporal "
"restrictions, or null when the "
"claim cannot be typed honestly")
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