The (K5) bug fix (his 24-25/10 session): glm-5.3-flash glues row
citations and glosses onto the judge's value field, killing the ablation
audit silently ("the judge invented it: nothing to ablate") and leaking
LLM prose into typed payloads. Fixed at the judge's output boundary
(_answer_from_rows): trailing-only, marker-anchored cleanup (_clean_value)
that strips the three live citation shapes and survives legitimate
parentheticals ("(PSOE)", "(since 2018)"). The AnswerFromKG value desc
now says what the value must be.
--no-cache CLI flag (his ruling: the dspy disk cache is not a bug, the
default stays; the flag exists for A/B and freshness testing) — builds
dspy.LM with cache=False for the process; verified live: repeated runs
re-run real inference instead of replaying.
Import assert at startup: floop/knowledge SUBMODULE files must resolve
inside this repo's tree. Namespace-package __path__ lies (it recomputes
dynamically and lists every tree), so the check pins the actual module
files (run 085457 was main's pipeline inside the branch worktree, no
signal). Abort loudly, don't log.
141 lines
6.7 KiB
Python
141 lines
6.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 ExtractSignature(dspy.Signature):
|
|
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
|
extract the facts that help answer the question. Each fact carries its
|
|
verbatim quote: the FULL sentence or table ROW that states the fact,
|
|
copied exactly (at least 10 characters). Only facts the text states;
|
|
no inference.
|
|
If the text is a fragment of a larger TABLE whose caption/headers show
|
|
its subject is wrong for the question, set stop_table=True with no facts.
|
|
Do NOT stop for text that is merely hard — only when the table's
|
|
subject is wrong."""
|
|
question: str = dspy.InputField()
|
|
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")
|
|
stop_table: bool = dspy.OutputField(
|
|
desc="True when this table fragment's subject is wrong for the question")
|
|
|
|
|
|
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")
|
|
|
|
|
|
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 |