TypeClaim does not need to rewrite the quote/verbatim

This commit is contained in:
2026-11-01 17:12:32 +01:00
parent 4e7229c92c
commit 3d541ec8d6
5 changed files with 112 additions and 88 deletions
+3 -3
View File
@@ -1287,9 +1287,9 @@ class KnowledgeExpert:
if self.cfg.extract_mode == "two_pass": if self.cfg.extract_mode == "two_pass":
# two-pass (26/10; verbatim moved 1/11): Pass 1 claims WITH # two-pass (26/10; verbatim moved 1/11): Pass 1 claims WITH
# their VERBATIM quotes (extracted while the text is in # their VERBATIM quotes (extracted while the text is in
# front of the model), Pass 2 one typed Fact per claim — # front of the model), Pass 2 one typed fact per claim —
# TYPING only, the verbatim enters as an input and the TYPE # TYPING only, the model sees JUST the claim (FactNoQuote);
# call no longer carries the chunk. # code composes the Fact: FactNoQuote + verbatim.
claims = claims_from(self, entities=ent_str, claims = claims_from(self, entities=ent_str,
heading=chunk.heading_path, heading=chunk.heading_path,
text=chunk.text, charge_llm=charge_llm) text=chunk.text, charge_llm=charge_llm)
+29 -16
View File
@@ -5,8 +5,8 @@ VERBATIM spans. The containment check (checks.py) validates every span against
the FULL document text — so chunking can never fake a quote. the FULL document text — so chunking can never fake a quote.
Two-pass (two_pass.py): Pass 1 (ExtractClaims) extracts the claims WITH their Two-pass (two_pass.py): Pass 1 (ExtractClaims) extracts the claims WITH their
VERBATIM spans; Pass 2 (TypeClaim) types ONE claim, the verbatim given to it VERBATIM spans; Pass 2 (TypeClaim) types ONE claim — typing only, the model
as an input — typing only, the VERBATIM is obtained before (owner 1/11). never sees the quote; code composes Fact = FactNoQuote + verbatim (owner 1/11).
""" """
from __future__ import annotations from __future__ import annotations
@@ -60,6 +60,24 @@ class Fact(BaseModel):
"of the sibling fact>}; empty when the text asserts no order") "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): 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 about the NAMED ENTITIES: biographical facts, positions extract facts about the NAMED ENTITIES: biographical facts, positions
@@ -108,21 +126,16 @@ class ExtractClaims(dspy.Signature):
class TypeClaim(dspy.Signature): class TypeClaim(dspy.Signature):
"""You are the TYPE step of a knowledge machine. Given ONE single claim """You are the TYPE step of a knowledge machine. Given ONE single claim,
and the VERBATIM quote that states it (extracted before, from the type the claim into the typed fact schema: subject entity, relation,
text the claim came from), type the claim into the Fact schema: object/value, and the temporal restrictions the claim states. All
subject entity, relation, object/value, and the temporal temporal fields are optional. Only what the claim states; no
restrictions the quote states. The Fact's quote is the given inference. If the claim cannot be typed honestly, return null."""
verbatim, copied exactly. All temporal fields are optional and must
be contained in the quote. Only what the claim and its quote state;
no inference. If the claim cannot be typed honestly, return null."""
claim: str = dspy.InputField(desc="the claim to type") claim: str = dspy.InputField(desc="the claim to type")
verbatim: str = dspy.InputField( fact: FactNoQuote | None = dspy.OutputField(
desc="the VERBATIM quote that states the claim, obtained before — " desc="the typed fact — subject, relation, object, temporal "
"the Fact's quote field must copy it exactly") "restrictions, or null when the "
fact: Fact | None = dspy.OutputField( "claim cannot be typed honestly")
desc="the typed Fact whose quote is the given verbatim, or null "
"when the claim cannot be typed honestly")
class AnswerFromKG(dspy.Signature): class AnswerFromKG(dspy.Signature):
+44 -35
View File
@@ -5,31 +5,34 @@ temporal fields + sibling order assertions in ONE giant JSON array — the
output budget that produced the 40-minute arithmetic. The two-pass split output budget that produced the 40-minute arithmetic. The two-pass split
shortens EVERY output: Pass 1 extracts the claims, each with its shortens EVERY output: Pass 1 extracts the claims, each with its
VERBATIM quote (coreference resolved to the entity names); Pass 2 types VERBATIM quote (coreference resolved to the entity names); Pass 2 types
ONE claim into the existing Fact schema per call — typing ONLY, the ONE claim per call — TYPING only, the model sees ONLY the claim and
verbatim given to it as an input (owner 1/11: the VERBATIM is obtained returns FactNoQuote; code composes the Fact: FactNoQuote + verbatim
before; the TYPE call never sees the text). (owner 1/11: the VERBATIM is obtained before, the TYPE model never sees
nor rewrites it).
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — the TYPE schema
assertions become IMPOSSIBLE by construction, so orders are dropped from (FactNoQuote) has NO orders field at all, so sibling order assertions
the two-pass path (the store's fact_order keeps working for whatever are impossible by construction (the store's fact_order keeps working
arrives as a typed Fact with orders; the two-pass facts carry none). for whatever arrives as a typed Fact with orders; the two-pass facts
The store, the containment checks and the merge are UNTOUCHED — Pass 2 carry none). The store, the containment checks and the merge are
emits the same typed Fact as before, minus orders. UNTOUCHED — the composed Fact is the same typed Fact as before, minus
orders.
Pinned: Pinned:
1. ExtractClaims: free-form claims, coreferences RESOLVED (the claim 1. ExtractClaims: free-form claims, coreferences RESOLVED (the claim
must name its entities, not 'he/it/the party'), each carrying its must name its entities, not 'he/it/the party'), each carrying its
VERBATIM quote — the quote is extracted HERE, in Pass 1. VERBATIM quote — the quote is extracted HERE, in Pass 1.
2. TypeClaim: one claim + its verbatim in -> one typed Fact out (same 2. TypeClaim: one claim in -> one FactNoQuote out (Fact minus quote,
fields as the legacy ExtractSignature.facts minus orders; temporal minus orders; temporal fields optional) — no text, no verbatim
fields optional) — no text input: the VERBATIM enters as an input. input: the TYPE model never sees the quote.
3. The pipeline wiring: the two-pass path returns typed Fact objects; 3. The pipeline wiring: the two-pass path returns composed Fact
candidates flow into _ingest_candidate exactly as before. objects; candidates flow into _ingest_candidate exactly as before.
4. Honest empty: no claims -> no facts, no invention. 4. Honest empty: no claims -> no facts, no invention.
5. The legacy single-pass signature STAYS (table frags use it; flipping 5. The legacy single-pass signature STAYS (table frags use it; flipping
the whole pipeline over is a later decision, config-driven). the whole pipeline over is a later decision, config-driven).
6. Code PINS the Fact's quote to Pass 1's verbatim (LLMs propose, code 6. Code COMPOSES the output Fact = FactNoQuote + verbatim (LLMs
decides) — the TYPE model cannot corrupt the span. propose, code decides) — the TYPE model never sees nor rewrites
the quote, so it cannot corrupt the span.
Run: .venv/bin/python knowledge/tests/two_pass_extract.py Run: .venv/bin/python knowledge/tests/two_pass_extract.py
""" """
@@ -43,7 +46,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.extract import (Claim, ExtractClaims, ExtractSignature, Fact, from knowledge.extract import (Claim, ExtractClaims, ExtractSignature, Fact,
TypeClaim) FactNoQuote, TypeClaim)
from knowledge.two_pass import claims_from, fact_from_claim from knowledge.two_pass import claims_from, fact_from_claim
@@ -70,22 +73,25 @@ def test_extract_claims_signature():
def test_type_claim_signature(): def test_type_claim_signature():
"""Pass 2: one claim + its verbatim -> one typed Fact; no text input; """Pass 2: one claim -> one typed FactNoQuote; no verbatim, no text;
orders NEVER produced here.""" orders IMPOSSIBLE (no orders field at all)."""
fields = set(TypeClaim.__fields__) fields = set(TypeClaim.__fields__)
# the VERBATIM is obtained BEFORE (Pass 1) and enters as an input; the # the model sees ONLY the claim: the VERBATIM (Pass 1's) is NOT an
# text is GONE — the quote-finding job moved to ExtractClaims (owner # input — nothing to copy, nothing to rewrite (owner 1/11).
# 1/11: TypeClaim only enforces the correct typing of the Fact). assert fields == {"claim", "fact"}, fields
assert fields == {"claim", "verbatim", "fact"}, fields
f = TypeClaim.model_fields["fact"].annotation f = TypeClaim.model_fields["fact"].annotation
assert "Fact" in str(f), f assert "FactNoQuote" in str(f), f
# Fact KEEPS orders (the legacy single-pass path and table frags use # FactNoQuote: Fact minus quote (never shown to the TYPE model)
# them — untouched); the two-pass law is that TypeClaim never fills # minus orders (one claim per call: no siblings to reference — the
# them: one claim per call means no siblings to reference. # two-pass law, now enforced by the SCHEMA itself)
assert "orders" in Fact.model_fields, "legacy Fact must keep orders" assert "quote" not in FactNoQuote.model_fields, "FactNoQuote must not carry a quote"
assert "orders" not in FactNoQuote.model_fields, "one claim per call: no siblings to reference"
# Fact KEEPS quote + orders (the legacy single-pass path and table
# frags use them — untouched)
assert "quote" in Fact.model_fields and "orders" in Fact.model_fields
d = TypeClaim.__doc__ or "" d = TypeClaim.__doc__ or ""
assert "one claim" in d.lower() or "single" in d.lower(), d assert "one claim" in d.lower() or "single" in d.lower(), d
print("ok: TypeClaim = one claim + verbatim in -> one Fact (typing only; no text)") print("ok: TypeClaim = one claim -> FactNoQuote (typing only; no quote, no orders)")
def test_claims_from_runs_pass1(): def test_claims_from_runs_pass1():
@@ -104,18 +110,21 @@ def test_claims_from_runs_pass1():
def test_fact_from_claim_types_one_fact(): def test_fact_from_claim_types_one_fact():
"""Pass 2 types one claim; CODE pins the Fact's quote to the given """Pass 2 types one claim; code COMPOSES the Fact = FactNoQuote +
verbatim — the scripted fact proposes a paraphrase, and it MUST be verbatim — the scripted FactNoQuote has no quote to invent, and the
overwritten (LLMs propose, code decides).""" returned Fact carries Pass 1's verbatim (LLMs propose, code
e = Scripted(typeclaim=Scripted(fact=Fact( decides)."""
e = Scripted(typeclaim=Scripted(fact=FactNoQuote(
subject="Pedro Sanchez", relation="prime minister of", subject="Pedro Sanchez", relation="prime minister of",
object="Spain", quote="a paraphrase the TYPE model invented", object="Spain",
start="2018", end=None, point=None, granularity="year"))) start="2018", end=None, point=None, granularity="year")))
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018", f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018",
verbatim="has been the prime minister of Spain since 2018") verbatim="has been the prime minister of Spain since 2018")
assert f.subject == "Pedro Sanchez" and f.start == "2018", f assert f.subject == "Pedro Sanchez" and f.start == "2018", f
assert f.quote == "has been the prime minister of Spain since 2018", f.quote assert f.quote == "has been the prime minister of Spain since 2018", f.quote
print("ok: fact_from_claim types one claim; code pins quote to the verbatim") assert isinstance(f, Fact), f # the store eats a real Fact
assert f.orders == [], f.orders # composed default: no siblings
print("ok: fact_from_claim composes Fact = FactNoQuote + verbatim")
def test_honest_empty(): def test_honest_empty():
+15 -16
View File
@@ -7,9 +7,10 @@ single-pass path keeps working (control). No network: the expert's
claims/typeclaim/extract modules are scripted. claims/typeclaim/extract modules are scripted.
The verbatim law (1/11): Pass 1 extracts the VERBATIM quote, Pass 2 The verbatim law (1/11): Pass 1 extracts the VERBATIM quote, Pass 2
only types — code PINS the fact's quote to Pass 1's verbatim, so the only types — the model sees ONLY the claim and returns FactNoQuote;
STORED quotes (quotes.verbatim) must be Pass 1's spans (contained in code COMPOSES the Fact (FactNoQuote + verbatim), so the STORED quotes
the page text), never the TYPE model's paraphrases. (quotes.verbatim) must be Pass 1's spans (contained in the page text),
never the TYPE model's.
""" """
from __future__ import annotations from __future__ import annotations
@@ -21,7 +22,7 @@ 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))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.extract import Claim, Fact from knowledge.extract import Claim, FactNoQuote
from knowledge.expert import KnowledgeConfig, KnowledgeExpert from knowledge.expert import KnowledgeConfig, KnowledgeExpert
from knowledge.store import KnowledgeStore from knowledge.store import KnowledgeStore
from knowledge.wiki import WikiPage from knowledge.wiki import WikiPage
@@ -54,8 +55,8 @@ class ScriptedClaims:
class ScriptedTypeClaim: class ScriptedTypeClaim:
"""Pass 2 double: typing only — its scripted quotes are PARAPHRASES; """Pass 2 double: typing only — FactNoQuote, NO quote field at all;
code must pin the fact's quote to Pass 1's verbatim instead.""" code composes the Fact with Pass 1's verbatim."""
def __init__(self, facts): def __init__(self, facts):
self.facts = facts self.facts = facts
@@ -77,14 +78,12 @@ def test_two_pass_ingests_typed_facts():
store=store) store=store)
e.claims = ScriptedClaims() e.claims = ScriptedClaims()
e.typeclaim = ScriptedTypeClaim([ e.typeclaim = ScriptedTypeClaim([
Fact(subject="Pedro Sanchez", relation="prime minister of", FactNoQuote(subject="Pedro Sanchez", relation="prime minister of",
object="Spain", object="Spain",
quote="a paraphrase Pass 2 invented (must be overwritten)", start="2018", end=None, point=None, granularity="year"),
start="2018", end=None, point=None, granularity="year"), FactNoQuote(subject="Pedro Sanchez", relation="secretary-general of",
Fact(subject="Pedro Sanchez", relation="secretary-general of", object="PSOE",
object="PSOE", start="2017", end=None, point=None, granularity="year"),
quote="another paraphrase (must be overwritten)",
start="2017", end=None, point=None, granularity="year"),
]) ])
# per-call state that answer_question initializes (the wiring test # per-call state that answer_question initializes (the wiring test
# drives _process_page directly) # drives _process_page directly)
@@ -102,13 +101,13 @@ def test_two_pass_ingests_typed_facts():
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0] 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] assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
# the verbatim law end-to-end: the STORED quotes are Pass 1's verbatims # the verbatim law end-to-end: the STORED quotes are Pass 1's verbatims
# (Pass 2's paraphrases never reach the store) # (the TYPE model never produced a quote at all — code composed it)
quotes = {r[0] for r in store.db.execute( quotes = {r[0] for r in store.db.execute(
"SELECT verbatim FROM quotes").fetchall()} "SELECT verbatim FROM quotes").fetchall()}
assert quotes == {"has been the prime minister of Spain since 2018", assert quotes == {"has been the prime minister of Spain since 2018",
"Secretary-General of the Spanish Socialist Workers' " "Secretary-General of the Spanish Socialist Workers' "
"Party (PSOE) since 2017"}, quotes "Party (PSOE) since 2017"}, quotes
print("ok: two_pass ingests typed facts (verbatim pinned, legacy checks)") print("ok: two_pass ingests typed facts (Fact = FactNoQuote + verbatim, legacy checks)")
def test_single_pass_still_works(): def test_single_pass_still_works():
+21 -18
View File
@@ -5,17 +5,18 @@ of typed Facts with verbatim quotes + temporal restrictions + sibling
order assertions — the output budget behind the 40-minute arithmetic. order assertions — the output budget behind the 40-minute arithmetic.
Two-pass shortens every output: Pass 1 lists the claims, each with its Two-pass shortens every output: Pass 1 lists the claims, each with its
VERBATIM quote (extracted while the text is in front of the model); VERBATIM quote (extracted while the text is in front of the model);
Pass 2 types ONE claim at a time into the same Fact schema the store Pass 2 types ONE claim at a time — the model sees ONLY the claim and
already eats — typing ONLY, the verbatim given as an input and the returns FactNoQuote; code composes the Fact the store already eats:
TYPE call never carrying the chunk (owner 1/11: the VERBATIM is Fact = FactNoQuote + verbatim (owner 1/11: the VERBATIM is obtained
obtained before). before, the TYPE model never sees nor rewrites it).
Orders: NEVER produced here — one claim per call has no siblings to Orders: NEVER produced here — one claim per call has no siblings to
reference. The legacy single-pass path (and table frags) keeps them. reference, and the TYPE schema (FactNoQuote) has no orders field at
all. The legacy single-pass path (and table frags) keeps them.
""" """
from __future__ import annotations from __future__ import annotations
from .extract import Claim from .extract import Claim, Fact
def claims_from(expert, entities: str, heading: str, text: str, def claims_from(expert, entities: str, heading: str, text: str,
@@ -48,18 +49,20 @@ def claims_from(expert, entities: str, heading: str, text: str,
def fact_from_claim(expert, claim: str, verbatim: str, charge_llm=None): def fact_from_claim(expert, claim: str, verbatim: str, charge_llm=None):
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined). """Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
TYPING ONLY: the VERBATIM was obtained in Pass 1 and enters as an TYPING ONLY: the model sees ONLY the claim — no text, no verbatim
input — the TYPE call never sees the text. Code PINS the Fact's (owner 1/11: the VERBATIM is Pass 1's and the TYPE model never sees
quote to it (LLMs propose, code decides): a paraphrased copy would nor rewrites it). Code COMPOSES the store's Fact: FactNoQuote +
fail the containment check and lose the fact (live finding 26/10: verbatim (LLMs propose, code decides) — the quote is Pass 1's span
without grounding, 69/70 invented quotes were rejected). The BY CONSTRUCTION, and the store's checks validate it downstream as
store's checks validate everything downstream as before. No before (a temporal field not contained in the quote rejects the
orders: no siblings by construction. candidate; live finding 26/10: without grounding, 69/70 invented
quotes were rejected). No orders: no siblings by construction, and
FactNoQuote has no orders field at all.
""" """
if charge_llm: if charge_llm:
charge_llm() charge_llm()
pred = expert.typeclaim(claim=claim, verbatim=verbatim) pred = expert.typeclaim(claim=claim)
fact = getattr(pred, "fact", None) nq = getattr(pred, "fact", None)
if fact is not None: if nq is None:
fact.quote = verbatim # the law: the Fact's quote IS Pass 1's verbatim return None
return fact return Fact(**nq.model_dump(), quote=verbatim)