knowledge: typed Fact extraction via dspy native structured output #10

Merged
onibot merged 1 commits from feature/typed-facts into main 2026-10-22 14:22:05 +02:00
4 changed files with 44 additions and 29 deletions
+9 -5
View File
@@ -24,9 +24,9 @@ import dspy
from .checks import check_candidate, quote_containment from .checks import check_candidate, quote_containment
from .chunker import chunk_page from .chunker import chunk_page
from .skim import find_quantities, skim_article from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, TranslateSignature, SkimPromoteSignature, TranslateSignature,
VerifyCountSignature, parse_facts) VerifyCountSignature)
from .store import KnowledgeStore, norm_name from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag, parse_stop_table) tables_as_chunks, format_table_frag, parse_stop_table)
@@ -964,8 +964,10 @@ class KnowledgeExpert:
if charge_llm: if charge_llm:
charge_llm() charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts): for cand in (raw.facts or []):
self._checked += 1 self._checked += 1
cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote}
ok, reason = check_candidate(cand, page.text) ok, reason = check_candidate(cand, page.text)
if not ok: if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
@@ -1001,17 +1003,19 @@ class KnowledgeExpert:
charge_llm() charge_llm()
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})" heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
raw = self.extract(question=question, heading=heading, text=text) raw = self.extract(question=question, heading=heading, text=text)
if parse_stop_table(raw.facts): if raw.stop:
stopped.add(frag["table_idx"]) stopped.add(frag["table_idx"])
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} " self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
f"({frag['caption'][:40]!r}) not relevant — " f"({frag['caption'][:40]!r}) not relevant — "
f"skipping {frag['of'] - frag['part']} remaining parts", f"skipping {frag['of'] - frag['part']} remaining parts",
think=True) think=True)
continue continue
for cand in parse_facts(raw.facts): for cand in (raw.facts or []):
self._checked += 1 self._checked += 1
# containment against prose + FULL table text: the fragment is # containment against prose + FULL table text: the fragment is
# rendered from the same rows, so quotes verify honestly # rendered from the same rows, so quotes verify honestly
cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote}
ok, reason = check_candidate(cand, containment) ok, reason = check_candidate(cand, containment)
if not ok: if not ok:
self._log(f"frag candidate rejected ({reason}): " self._log(f"frag candidate rejected ({reason}): "
+23 -14
View File
@@ -7,6 +7,16 @@ the FULL document text — so chunking can never fake a quote.
from __future__ import annotations from __future__ import annotations
import dspy import dspy
from pydantic import BaseModel
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): class TranslateSignature(dspy.Signature):
@@ -24,21 +34,21 @@ class TranslateSignature(dspy.Signature):
class ExtractSignature(dspy.Signature): class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text, """You are the EXTRACT step of a knowledge machine. From the given text,
extract facts that help answer the question. Each fact is one line: extract the facts that help answer the question. Each fact carries its
subject | relation | object | verbatim quote from the text. verbatim quote: the FULL sentence or table ROW that states the fact,
The quote must be the FULL sentence or table ROW that states the fact,
copied exactly (at least 10 characters). Only facts the text states; copied exactly (at least 10 characters). Only facts the text states;
no inference. no inference.
If the text is a fragment of a larger TABLE and you can already tell If the text is a fragment of a larger TABLE whose caption/headers show
from its caption/headers that this table cannot contain anything its subject is wrong for the question, set stop=True with no facts.
relevant to the question (wrong subject entirely), reply with the Do NOT stop for text that is merely hard — only when the table's
single word STOP_TABLE and no facts. Do NOT use STOP_TABLE for text subject is wrong."""
that is merely hard — only when the table's subject is wrong."""
question: str = dspy.InputField() question: str = dspy.InputField()
heading: str = dspy.InputField(desc="section path of this chunk; context only") heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField() text: str = dspy.InputField()
facts: str = dspy.OutputField( facts: list[Fact] = dspy.OutputField(
desc="one fact per line: subject | relation | object | verbatim quote; empty if none; or STOP_TABLE if this table fragment's subject is wrong for the question") desc="the extracted facts; empty list if none")
stop: bool = dspy.OutputField(
desc="True when this table fragment's subject is wrong for the question")
class AnswerFromKG(dspy.Signature): class AnswerFromKG(dspy.Signature):
@@ -102,10 +112,9 @@ class SkimPromoteSignature(dspy.Signature):
def parse_facts(raw: str) -> list[dict]: def parse_facts(raw: str) -> list[dict]:
"""Parse the extractor's piped lines; malformed lines are dropped+counted. """LEGACY pipe parser — kept ONLY for tests that script extractor
responses as text. Production code consumes typed `Fact` objects from
Split into AT MOST 4 fields — the quote is the last field and may itself dspy directly (see ExtractSignature.facts). Do not use in new code."""
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
out: list[dict] = [] out: list[dict] = []
for line in (raw or "").strip().splitlines(): for line in (raw or "").strip().splitlines():
line = line.strip() line = line.strip()
+10 -6
View File
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag, from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
parse_stop_table) parse_stop_table)
from knowledge.expert import KnowledgeExpert, KnowledgeConfig from knowledge.expert import KnowledgeExpert, KnowledgeConfig
from knowledge.extract import Fact
from knowledge.store import KnowledgeStore from knowledge.store import KnowledgeStore
from knowledge.wiki import WikiPage from knowledge.wiki import WikiPage
@@ -91,23 +92,26 @@ def test_process_page_fragments():
wikitext=WIKITEXT_2TABLES) wikitext=WIKITEXT_2TABLES)
page.tables = parse_tables(WIKITEXT_2TABLES) page.tables = parse_tables(WIKITEXT_2TABLES)
# scripted extractor: world-table parts -> STOP_TABLE; Italy table -> one fact # scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
calls = [] calls = []
class FakeOut: class FakeOut:
def __init__(self, facts): def __init__(self, facts, stop=False):
self.facts = facts self.facts = facts
self.stop = stop
def fake_extract(question, heading, text, _calls=calls): def fake_extract(question, heading, text, _calls=calls):
_calls.append((question, heading, text)) _calls.append((question, heading, text))
if "World rivers" in text: if "World rivers" in text:
return FakeOut("STOP_TABLE") return FakeOut([], stop=True)
if "Rivers of Italy" in text: if "Rivers of Italy" in text:
# quote = the full rendered row context (header + row), verbatim # quote = the full rendered row context (header + row), verbatim
# from the fragment the extractor saw # from the fragment the extractor saw
return FakeOut("Po | Flow at the mouth | 1540 m3/s | " return FakeOut([Fact(
"River | Flow at the mouth Po | 1540") subject="Po", relation="Flow at the mouth",
return FakeOut("") object="1540 m3/s",
quote="River | Flow at the mouth Po | 1540")])
return FakeOut([])
e.extract = fake_extract e.extract = fake_extract
+2 -4
View File
@@ -190,10 +190,8 @@ def part_of(frag: dict) -> str:
def parse_stop_table(out_text: str) -> bool: def parse_stop_table(out_text: str) -> bool:
"""True when the extractor's output names this table as not relevant for """LEGACY textual STOP_TABLE detector — kept only for tests. Production
the question. The extractor may write STOP_TABLE for a fragment's table code reads the typed `stop: bool` field of ExtractSignature."""
after seeing its identity (caption/header) — fixed code then skips all
remaining fragments of THAT table (never other tables)."""
return "STOP_TABLE" in (out_text or "").upper()[:80] return "STOP_TABLE" in (out_text or "").upper()[:80]