From 109885773cb5aa4cd81a9b9f2d48a9ec97f87802 Mon Sep 17 00:00:00 2001 From: Onibot Date: Thu, 22 Oct 2026 14:21:13 +0200 Subject: [PATCH] knowledge: typed Fact extraction via dspy native structured output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit His direction: stop explaining string formats to the LLM and parsing them back with Python — that's exactly what dspy does natively and better. The pipe format ('subject | relation | object | quote') was fragile (run-L verbose values, pipe-in-quote ambiguity, STOP_TABLE string protocol). THE CHANGE (extractor only, PR-10 scope): - Fact(BaseModel) with subject/relation/object/quote OutputFields - ExtractSignature.facts: list[Fact] — the adapter renders the JSON schema into the prompt itself (verified in a live run's prompt log) and parses responses back into typed Fact objects - STOP_TABLE string protocol -> stop: bool OutputField - expert.py consumes typed objects; the cand dict is built at the check_candidate boundary only (checks.py unchanged) - parse_facts/parse_stop_table kept as LEGACY for existing tests only VERIFIED: - dspy 3.4.1 pattern E2E'd first with a raw-text engine: list[Fact] parses back as Fact objects, schema rendered in prompt (tmp probes) - full suite 12/12 green (74 tests) — tablefrags.py updated to script typed Fact objects - live E2E run (ollama-cloud glm-5.3-flash, Italy rivers): correct Po/Adige/Tiber answer; prompt log shows the native JSON schema; table rows ingested cleanly (22 rows, quotes verbatim) NEXT (his direction, not this PR): apply the same typed-output law to ALL floop signatures — INIT subquestions, ROUTE engine choice, AnswerFromKG, SelectTable, SkimPromote, Translate, VerifyCount. --- code/knowledge/expert.py | 14 +++++++---- code/knowledge/extract.py | 37 +++++++++++++++++++----------- code/knowledge/tests/tablefrags.py | 16 ++++++++----- code/knowledge/wiki.py | 6 ++--- 4 files changed, 44 insertions(+), 29 deletions(-) diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index de36f8c..65addba 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -24,9 +24,9 @@ import dspy from .checks import check_candidate, quote_containment from .chunker import chunk_page from .skim import find_quantities, skim_article -from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, +from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature, SkimPromoteSignature, TranslateSignature, - VerifyCountSignature, parse_facts) + VerifyCountSignature) from .store import KnowledgeStore, norm_name from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, tables_as_chunks, format_table_frag, parse_stop_table) @@ -964,8 +964,10 @@ class KnowledgeExpert: if charge_llm: charge_llm() 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 + cand = {"subject": cand.subject, "relation": cand.relation, + "object": cand.object, "quote": cand.quote} ok, reason = check_candidate(cand, page.text) if not ok: self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") @@ -1001,17 +1003,19 @@ class KnowledgeExpert: charge_llm() heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})" raw = self.extract(question=question, heading=heading, text=text) - if parse_stop_table(raw.facts): + if raw.stop: stopped.add(frag["table_idx"]) self._log(f"extractor STOP_TABLE: table {frag['table_idx']} " f"({frag['caption'][:40]!r}) not relevant — " f"skipping {frag['of'] - frag['part']} remaining parts", think=True) continue - for cand in parse_facts(raw.facts): + for cand in (raw.facts or []): self._checked += 1 # containment against prose + FULL table text: the fragment is # 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) if not ok: self._log(f"frag candidate rejected ({reason}): " diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index 54907e8..6cc143e 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -7,6 +7,16 @@ the FULL document text — so chunking can never fake a quote. from __future__ import annotations 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): @@ -24,21 +34,21 @@ class TranslateSignature(dspy.Signature): class ExtractSignature(dspy.Signature): """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: - subject | relation | object | verbatim quote from the text. - The quote must be the FULL sentence or table ROW that states the fact, + 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 and you can already tell - from its caption/headers that this table cannot contain anything - relevant to the question (wrong subject entirely), reply with the - single word STOP_TABLE and no facts. Do NOT use STOP_TABLE for text - that is merely hard — only when the table's subject is wrong.""" + If the text is a fragment of a larger TABLE whose caption/headers show + its subject is wrong for the question, set stop=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: str = 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") + facts: list[Fact] = dspy.OutputField( + 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): @@ -102,10 +112,9 @@ class SkimPromoteSignature(dspy.Signature): def parse_facts(raw: str) -> list[dict]: - """Parse the extractor's piped lines; malformed lines are dropped+counted. - - Split into AT MOST 4 fields — the quote is the last field and may itself - contain pipes (table rows like 'France | 68,635,900 | 15.2%').""" + """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() diff --git a/code/knowledge/tests/tablefrags.py b/code/knowledge/tests/tablefrags.py index dfe7cdf..b3573c4 100644 --- a/code/knowledge/tests/tablefrags.py +++ b/code/knowledge/tests/tablefrags.py @@ -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, parse_stop_table) from knowledge.expert import KnowledgeExpert, KnowledgeConfig +from knowledge.extract import Fact from knowledge.store import KnowledgeStore from knowledge.wiki import WikiPage @@ -91,23 +92,26 @@ def test_process_page_fragments(): wikitext=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 = [] class FakeOut: - def __init__(self, facts): + def __init__(self, facts, stop=False): self.facts = facts + self.stop = stop def fake_extract(question, heading, text, _calls=calls): _calls.append((question, heading, text)) if "World rivers" in text: - return FakeOut("STOP_TABLE") + return FakeOut([], stop=True) if "Rivers of Italy" in text: # quote = the full rendered row context (header + row), verbatim # from the fragment the extractor saw - return FakeOut("Po | Flow at the mouth | 1540 m3/s | " - "River | Flow at the mouth Po | 1540") - return FakeOut("") + return FakeOut([Fact( + subject="Po", relation="Flow at the mouth", + object="1540 m3/s", + quote="River | Flow at the mouth Po | 1540")]) + return FakeOut([]) e.extract = fake_extract diff --git a/code/knowledge/wiki.py b/code/knowledge/wiki.py index 436b490..b6545af 100644 --- a/code/knowledge/wiki.py +++ b/code/knowledge/wiki.py @@ -190,10 +190,8 @@ def part_of(frag: dict) -> str: def parse_stop_table(out_text: str) -> bool: - """True when the extractor's output names this table as not relevant for - the question. The extractor may write STOP_TABLE for a fragment's table - after seeing its identity (caption/header) — fixed code then skips all - remaining fragments of THAT table (never other tables).""" + """LEGACY textual STOP_TABLE detector — kept only for tests. Production + code reads the typed `stop: bool` field of ExtractSignature.""" return "STOP_TABLE" in (out_text or "").upper()[:80] -- 2.55.0