From f6e9164e92e1ee4cbd55007f6235de45f2b116b6 Mon Sep 17 00:00:00 2001 From: Onibot Date: Mon, 26 Oct 2026 16:42:22 +0100 Subject: [PATCH] feat: two-pass EXTRACT (claims -> typed Facts) for prose chunks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit His diagnosis accepted (26/10): the single-pass EXTRACT's giant typed JSON array (verbatim quotes + temporal restrictions + sibling orders) is the output budget behind the 40-minute arithmetic on slow local models. Two-pass shortens EVERY output: - Pass 1 ExtractClaims: plain claim strings, coreferences resolved (entities named, never pronouns) — near-zero format tax. - Pass 2 TypeClaim: ONE claim -> one typed Fact per call (same Fact schema the store eats; temporal fields optional, containment-checked downstream as always). Orders NEVER produced here: one claim at a time has no siblings — the legacy Fact keeps orders for the single-pass path and table frags, untouched. - extract_mode: two_pass (default) | single (legacy) — config-driven, read from config.yaml's knowledge block by run_app. - Budget: Pass 1 charges once per chunk; Pass 2 charges once per claim. Table frags keep the legacy single-pass call. - Prompt log: CLAIMS/TYPE stage labels added. TDD: two_pass_extract 5/5 (signatures, coref law, honest empties) + two_pass_wiring 2/2 (end-to-end on a real store: two_pass ingests typed facts with windows kept; single-pass control green). Suite: 29 test files green. The router from #26 makes the upcoming extraction-model swap a pure config edit. --- code/floop/llm.py | 2 + code/knowledge/expert.py | 27 ++++- code/knowledge/extract.py | 29 +++++ code/knowledge/tests/tablefrags.py | 2 +- code/knowledge/tests/two_pass_extract.py | 110 +++++++++++++++++++ code/knowledge/tests/two_pass_wiring.py | 133 +++++++++++++++++++++++ code/knowledge/two_pass.py | 40 +++++++ code/run_app.py | 1 + 8 files changed, 340 insertions(+), 4 deletions(-) create mode 100644 code/knowledge/tests/two_pass_extract.py create mode 100644 code/knowledge/tests/two_pass_wiring.py create mode 100644 code/knowledge/two_pass.py diff --git a/code/floop/llm.py b/code/floop/llm.py index 3238733..258f7d1 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -164,6 +164,8 @@ _STAGE_BY_MODULE = { "MissingSignature": "MISSING", "AnswerSignature": "ANSWER", "ExtractSignature": "EXTRACT", + "ExtractClaims": "CLAIMS", + "TypeClaim": "TYPE", "AnswerFromKG": "answer_kg", "SelectTableSignature": "SELECT_TABLE", "VerifyCountSignature": "VERIFY_COUNT", diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index 02f0b6c..c2ee1ec 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -30,12 +30,13 @@ from floop.llm import predict from .checks import check_candidate, quote_containment from .chunker import chunk_page from .skim import find_quantities, skim_article -from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature, - SkimPromoteSignature, SkimTableSignature, - VerifyCountSignature) +from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact, + SelectTableSignature, SkimPromoteSignature, + SkimTableSignature, TypeClaim, VerifyCountSignature) from .embeddings import EmbedderDown, embed from .queries import compose_queries, keywords, proper_nouns from .store import KnowledgeStore, norm_name +from .two_pass import claims_from, fact_from_claim from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, tables_as_chunks, format_table_frag) @@ -163,6 +164,9 @@ class KnowledgeConfig: semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro # cross-question 0.35-0.38 out, spouse-noise ~0.67 max_facts_per_chunk: int = 12 # question-blind extraction needs a cap + extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short + # outputs) | "single" (legacy one-call typed + # array — table frags keep using it) class KnowledgeExpert: @@ -176,6 +180,8 @@ class KnowledgeExpert: self.client = client or WikipediaClient() self.streams = streams self.extract = predict(ExtractSignature) + self.claims = predict(ExtractClaims) + self.typeclaim = predict(TypeClaim) self.answer = predict(AnswerFromKG) self.select_table = predict(SelectTableSignature) self.verify_count = predict(VerifyCountSignature) @@ -1166,6 +1172,21 @@ class KnowledgeExpert: think=True) extracted = 0 for chunk in capped: + if self.cfg.extract_mode == "two_pass": + # two-pass (26/10): Pass 1 claims (short strings, coref + # resolved), Pass 2 one typed Fact per claim — every + # output short; the giant typed array is gone from prose. + claims = claims_from(self, entities=ent_str, + heading=chunk.heading_path, + text=chunk.text, charge_llm=charge_llm) + for claim in claims[: self.cfg.max_facts_per_chunk]: + fact = fact_from_claim(self, claim, charge_llm=charge_llm) + if fact is None: + continue # honestly declined: no invention + merged, _eid = self._ingest_candidate( + fact, page, containment=page.text) + extracted += merged + continue if charge_llm: charge_llm() raw = self.extract(entities=ent_str, heading=chunk.heading_path, diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index 1f69025..40f472f 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -72,6 +72,35 @@ class ExtractSignature(dspy.Signature): desc="the extracted facts; empty list if none") +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. One claim per line, plain text, no numbering. + 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[str] = dspy.OutputField( + desc="the factual claims, one string each, coreferences resolved " + "(entities named, never pronouns); empty list if none") + + +class TypeClaim(dspy.Signature): + """You are the TYPE step of a knowledge machine. Given ONE single claim, + type it into the Fact schema: subject entity, relation, object/value, + the VERBATIM quote from the text that states the claim (the FULL + sentence or table row, copied exactly, at least 10 characters), and + the temporal restrictions the text states. All temporal fields are + optional and must be contained in the quote. Only what the claim and + its quote state; no inference.""" + claim: str = dspy.InputField(desc="the claim to type") + fact: Fact | None = dspy.OutputField( + desc="the typed Fact, 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 diff --git a/code/knowledge/tests/tablefrags.py b/code/knowledge/tests/tablefrags.py index a539a36..c355495 100644 --- a/code/knowledge/tests/tablefrags.py +++ b/code/knowledge/tests/tablefrags.py @@ -64,7 +64,7 @@ def test_format_and_parse_stop(): def make_expert(store: KnowledgeStore) -> KnowledgeExpert: e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init - e.cfg = KnowledgeConfig() + e.cfg = KnowledgeConfig(extract_mode="single") # this test pins the LEGACY path e.store = store e.streams = None e._checked = e._merged = 0 diff --git a/code/knowledge/tests/two_pass_extract.py b/code/knowledge/tests/two_pass_extract.py new file mode 100644 index 0000000..b4ef419 --- /dev/null +++ b/code/knowledge/tests/two_pass_extract.py @@ -0,0 +1,110 @@ +"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts). + +Law: the old single call asked a slow model for verbatim quotes + typed +temporal fields + sibling order assertions in ONE giant JSON array — the +output budget that produced the 40-minute arithmetic. The two-pass split +shortens EVERY output: Pass 1 extracts plain claims (free-form strings +with coreference resolved to the entity names — near-zero format tax); +Pass 2 types ONE claim into the existing Fact schema per call. + +CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order +assertions become IMPOSSIBLE by construction, so orders are dropped from +the two-pass path (the store's fact_order keeps working for whatever +arrives as a typed Fact with orders; the two-pass facts carry none). +The store, the containment checks and the merge are UNTOUCHED — Pass 2 +emits the same typed Fact as before, minus orders. + +Pinned: +1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the + claim must name its entities, not 'he/it/the party'). +2. TypeClaim: one claim in -> one typed Fact out (same fields as the + legacy ExtractSignature.facts minus orders; temporal fields optional). +3. The pipeline wiring: _extract_two_pass returns typed Fact objects; + candidates flow into _ingest_candidate exactly as before. +4. Honest empty: no claims -> no facts, no invention. +5. The legacy single-pass signature STAYS (table frags use it; flipping + the whole pipeline over is a later decision, config-driven). + +Run: .venv/bin/python knowledge/tests/two_pass_extract.py +""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) + +from knowledge.extract import ExtractClaims, TypeClaim, Fact, ExtractSignature +from knowledge.two_pass import claims_from, fact_from_claim + + +class Scripted: + def __init__(self, **attrs): + self.__dict__.update(attrs) + + def __call__(self, **kw): + return self + + +def test_extract_claims_signature(): + """Pass 1: claims are free-form strings; coreferences resolved.""" + fields = set(ExtractClaims.__fields__) + assert fields == {"entities", "heading", "text", "claims"}, fields + # what the model actually sees: dspy keeps desc in json_schema_extra + d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "") + assert "coreference" in d.lower() or "resolved" in d.lower(), d + print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft") + + +def test_type_claim_signature(): + """Pass 2: one claim -> one typed Fact; orders NEVER produced here.""" + fields = set(TypeClaim.__fields__) + assert fields == {"claim", "fact"}, fields + f = TypeClaim.model_fields["fact"].annotation + assert "Fact" in str(f), f + # Fact KEEPS orders (the legacy single-pass path and table frags use + # them — untouched); the two-pass law is that TypeClaim never fills + # them: one claim per call means no siblings to reference. + assert "orders" in Fact.model_fields, "legacy Fact must keep orders" + d = TypeClaim.__doc__ or "" + assert "one claim" in d.lower() or "single" in d.lower(), d + print("ok: TypeClaim = one claim -> one Fact; orders never produced (no siblings)") + + +def test_claims_from_runs_pass1(): + e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018", + "Sanchez became Secretary-General of the PSOE in 2017"])) + out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...") + assert out == ["Pedro Sanchez is the prime minister of Spain since 2018", + "Sanchez became Secretary-General of the PSOE in 2017"], out + print("ok: claims_from extracts the plain claim strings") + + +def test_fact_from_claim_types_one_fact(): + e = Scripted(typeclaim=Scripted(fact=Fact( + subject="Pedro Sanchez", relation="prime minister of", + object="Spain", quote="is a Spanish politician who has been the " + "prime minister of Spain since 2018", + start="2018", end=None, point=None, granularity="year"))) + f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018") + assert f.subject == "Pedro Sanchez" and f.start == "2018", f + print("ok: fact_from_claim returns the typed Fact for one claim") + + +def test_honest_empty(): + e = Scripted(claims=Scripted(claims=[])) + assert claims_from(e, entities="", heading="", text="") == [] + e2 = Scripted(typeclaim=Scripted(fact=None)) + assert fact_from_claim(e2, claim="") is None + print("ok: no claims -> no facts; untypeable claim -> None, no invention") + + +if __name__ == "__main__": + test_extract_claims_signature() + test_type_claim_signature() + test_claims_from_runs_pass1() + test_fact_from_claim_types_one_fact() + test_honest_empty() + print("\ntwo_pass_extract: 5/5 ok") \ No newline at end of file diff --git a/code/knowledge/tests/two_pass_wiring.py b/code/knowledge/tests/two_pass_wiring.py new file mode 100644 index 0000000..f1a08b9 --- /dev/null +++ b/code/knowledge/tests/two_pass_wiring.py @@ -0,0 +1,133 @@ +"""The two-pass pipeline wiring test: prose chunks flow claims->facts->store. + +End-to-end on a REAL store (tmp kg.sqlite): _process_page in two_pass +mode ingests the typed facts from Pass 2 exactly as the legacy path +did — same _ingest_candidate, same containment checks, same merge; the +single-pass path keeps working (control). No network: the expert's +claims/typeclaim/extract modules are scripted. +""" +from __future__ import annotations + +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) + +from knowledge.extract import Fact +from knowledge.expert import KnowledgeConfig, KnowledgeExpert +from knowledge.store import KnowledgeStore +from knowledge.wiki import WikiPage + + +PAGE_TEXT = ( + "Pedro Sanchez is a Spanish politician who has been the prime " + "minister of Spain since 2018. He is also Secretary-General of the " + "Spanish Socialist Workers' Party (PSOE) since 2017." +) + + +def make_page() -> WikiPage: + return WikiPage(title="Pedro Sanchez", pageid=1, + url="https://en.wikipedia.org/wiki/P", + fetched_at="2026-10-26", text=PAGE_TEXT, tables=[]) + + +class ScriptedClaims: + def __call__(self, **kw): + class Out: + claims = ["Pedro Sanchez has been the prime minister of Spain since 2018", + "Pedro Sanchez is Secretary-General of the PSOE since 2017"] + return Out() + + +class ScriptedTypeClaim: + def __init__(self, facts): + self.facts = facts + self.i = 0 + + def __call__(self, **kw): + f = self.facts[self.i] + self.i += 1 + class Out: + fact = f + return Out() + + +def test_two_pass_ingests_typed_facts(): + tmp = tempfile.mkdtemp() + store = KnowledgeStore(str(Path(tmp) / "kg.sqlite")) + e = KnowledgeExpert(config=KnowledgeConfig( + kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="two_pass"), + store=store) + e.claims = ScriptedClaims() + e.typeclaim = ScriptedTypeClaim([ + Fact(subject="Pedro Sanchez", relation="prime minister of", + object="Spain", + quote="has been the prime minister of Spain since 2018", + start="2018", end=None, point=None, granularity="year"), + Fact(subject="Pedro Sanchez", relation="secretary-general of", + object="PSOE", + quote="Secretary-General of the Spanish Socialist Workers' " + "Party (PSOE) since 2017", + start="2017", end=None, point=None, granularity="year"), + ]) + # per-call state that answer_question initializes (the wiring test + # drives _process_page directly) + e._extract_entities = [] + e._current_goal_terms = [] + e._current_goal_question = "the question" + n = e._process_page(make_page(), "the question", kws=["pedro", "prime"], + charge_llm=None, goal_terms=[]) + assert n >= 2, f"two_pass should merge both facts (merged={n})" + rows = store.db.execute( + "SELECT n.norm_name, e.rel, e.dst_value, e.t_start FROM edges e " + "JOIN nodes n ON n.id=e.src_node " + "WHERE n.norm_name='pedro sanchez' ORDER BY e.id").fetchall() + assert len(rows) == 2, rows + assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0] + assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1] + print("ok: two_pass ingests typed facts (windows kept, legacy checks)") + + +def test_single_pass_still_works(): + """Control: extract_mode='single' -> the legacy one-call path.""" + tmp = tempfile.mkdtemp() + store = KnowledgeStore(str(Path(tmp) / "kg.sqlite")) + e = KnowledgeExpert(config=KnowledgeConfig( + kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="single"), + store=store) + from knowledge.extract import Fact + + class ScriptedExtract: + def __call__(self, **kw): + class Out: + facts = [Fact(subject="Pedro Sanchez", + relation="prime minister of", object="Spain", + quote="has been the prime minister of Spain " + "since 2018", + start="2018", end=None, point=None, + granularity="year")] + return Out() + + e.extract = ScriptedExtract() + e._extract_entities = [] + e._current_goal_terms = [] + e._current_goal_question = "the question" + n = e._process_page(make_page(), "the question", kws=["pedro"], + charge_llm=None, goal_terms=[]) + assert n >= 1, n + rows = store.db.execute( + "SELECT COUNT(*) FROM edges e JOIN nodes n ON n.id=e.src_node " + "WHERE n.norm_name='pedro sanchez'" + ).fetchone()[0] + assert rows == 1, rows + print("ok: single-pass legacy path untouched (control)") + + +if __name__ == "__main__": + test_two_pass_ingests_typed_facts() + test_single_pass_still_works() + print("\ntwo_pass_wiring: 2/2 ok") \ No newline at end of file diff --git a/code/knowledge/two_pass.py b/code/knowledge/two_pass.py new file mode 100644 index 0000000..0c866f3 --- /dev/null +++ b/code/knowledge/two_pass.py @@ -0,0 +1,40 @@ +"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts). + +The single-pass EXTRACT asked slow local models for a giant JSON array +of typed Facts with verbatim quotes + temporal restrictions + sibling +order assertions — the output budget behind the 40-minute arithmetic. +Two-pass shortens every output: Pass 1 lists plain claims (free-form +strings, coreferences resolved — near-zero format tax); Pass 2 types +ONE claim at a time into the same Fact schema the store already eats. + +Orders: NEVER produced here — one claim per call has no siblings to +reference. The legacy single-pass path (and table frags) keeps them. +""" +from __future__ import annotations + + +def claims_from(expert, entities: str, heading: str, text: str, + charge_llm=None) -> list[str]: + """Pass 1: the chunk's claims as plain strings, coreferences resolved.""" + if charge_llm: + charge_llm() + pred = expert.claims(entities=entities, heading=heading, text=text) + out = [] + for c in (pred.claims or []): + c = (c or "").strip() + if c: + out.append(c) + return out + + +def fact_from_claim(expert, claim: str, charge_llm=None): + """Pass 2: ONE claim -> one typed Fact (or None, honestly declined). + + The Fact carries the verbatim quote and any temporal restrictions + the text states; the store's containment checks validate everything + downstream exactly as before. No orders: no siblings by construction. + """ + if charge_llm: + charge_llm() + pred = expert.typeclaim(claim=claim) + return getattr(pred, "fact", None) \ No newline at end of file diff --git a/code/run_app.py b/code/run_app.py index 2ca40ab..85179bf 100644 --- a/code/run_app.py +++ b/code/run_app.py @@ -130,6 +130,7 @@ def main() -> None: max_chunks_extracted=kcfg.get("max_chunks_extracted", 6), chunk_chars_target=kcfg.get("chunk_chars_target", 32000), chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000), + extract_mode=kcfg.get("extract_mode", "two_pass"), ) ke = KnowledgeExpert(config=kconfig, streams=streams) knowledge_engine = KnowledgeEngine(ke) -- 2.55.0