Extract verbatim in ExtractClaims not in TypeClaim
This commit is contained in:
@@ -1285,22 +1285,24 @@ class KnowledgeExpert:
|
|||||||
extracted = 0
|
extracted = 0
|
||||||
for chunk in capped:
|
for chunk in capped:
|
||||||
if self.cfg.extract_mode == "two_pass":
|
if self.cfg.extract_mode == "two_pass":
|
||||||
# two-pass (26/10): Pass 1 claims (short strings, coref
|
# two-pass (26/10; verbatim moved 1/11): Pass 1 claims WITH
|
||||||
# resolved), Pass 2 one typed Fact per claim — every
|
# their VERBATIM quotes (extracted while the text is in
|
||||||
# output short; the giant typed array is gone from prose.
|
# front of the model), Pass 2 one typed Fact per claim —
|
||||||
|
# TYPING only, the verbatim enters as an input and the TYPE
|
||||||
|
# call no longer carries the chunk.
|
||||||
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)
|
||||||
self._rec("claims.done", page=page.title,
|
self._rec("claims.done", page=page.title,
|
||||||
heading=chunk.heading_path,
|
heading=chunk.heading_path,
|
||||||
out_={"n_claims": len(claims),
|
out_={"n_claims": len(claims),
|
||||||
"claims": list(claims)})
|
"claims": [c.__dict__ for c in claims]})
|
||||||
# owner ruling 26/10: completeness beats budget — every
|
# owner ruling 26/10: completeness beats budget — every
|
||||||
# unique claim gets its TYPE call (no cap, dedup only)
|
# unique claim gets its TYPE call (no cap, dedup only)
|
||||||
for claim in claims:
|
for c in claims:
|
||||||
fact = fact_from_claim(self, claim, text=chunk.text,
|
fact = fact_from_claim(self, c.claim, verbatim=c.verbatim,
|
||||||
charge_llm=charge_llm)
|
charge_llm=charge_llm)
|
||||||
self._rec("type.done", page=page.title, claim=claim[:200],
|
self._rec("type.done", page=page.title, claim=c.claim[:200],
|
||||||
out_={"fact": getattr(fact, "__dict__", None)}
|
out_={"fact": getattr(fact, "__dict__", None)}
|
||||||
if fact is not None else {"fact": None})
|
if fact is not None else {"fact": None})
|
||||||
if fact is None:
|
if fact is None:
|
||||||
|
|||||||
+37
-19
@@ -3,6 +3,10 @@
|
|||||||
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
||||||
VERBATIM spans. The containment check (checks.py) validates every span against
|
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
|
||||||
|
VERBATIM spans; Pass 2 (TypeClaim) types ONE claim, the verbatim given to it
|
||||||
|
as an input — typing only, the VERBATIM is obtained before (owner 1/11).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -72,39 +76,53 @@ class ExtractSignature(dspy.Signature):
|
|||||||
desc="the extracted facts; empty list if none")
|
desc="the extracted facts; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
|
class Claim(BaseModel):
|
||||||
|
"""One claim of Pass 1: the free-form claim PLUS the VERBATIM span
|
||||||
|
that states it. The quote is extracted HERE, in the same call that
|
||||||
|
reads the text (owner 1/11: the VERBATIM is obtained before the
|
||||||
|
typing — Pass 2 only enforces the Fact's typing)."""
|
||||||
|
claim: str = dspy.OutputField(
|
||||||
|
desc="the factual claim, coreferences resolved (entities named, "
|
||||||
|
"never pronouns)")
|
||||||
|
verbatim: str = dspy.OutputField(
|
||||||
|
desc="VERBATIM quote from the text that states the claim: the FULL "
|
||||||
|
"sentence or table row, copied exactly (at least 10 characters)")
|
||||||
|
|
||||||
|
|
||||||
class ExtractClaims(dspy.Signature):
|
class ExtractClaims(dspy.Signature):
|
||||||
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
||||||
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
||||||
and offices held, biographical facts, events, relationships,
|
and offices held, biographical facts, events, relationships,
|
||||||
quantities with units. One claim per line, plain text, no numbering.
|
quantities with units. Each claim carries the VERBATIM quote that
|
||||||
Resolve coreferences: name the entity in the claim, never a pronoun
|
states it: the FULL sentence or table row, copied exactly (at least
|
||||||
or a shorthand. Only what the text states; no inference."""
|
10 characters). 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(
|
entities: str = dspy.InputField(
|
||||||
desc="the named entities to extract claims about, comma separated")
|
desc="the named entities to extract claims about, comma separated")
|
||||||
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()
|
||||||
claims: list[str] = dspy.OutputField(
|
claims: list[Claim] = dspy.OutputField(
|
||||||
desc="the factual claims, one string each, coreferences resolved "
|
desc="the factual claims, each with its VERBATIM quote copied "
|
||||||
"(entities named, never pronouns); empty list if none")
|
"exactly from the text; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
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 TEXT it was extracted from, type the claim into the Fact
|
and the VERBATIM quote that states it (extracted before, from the
|
||||||
schema: subject entity, relation, object/value, the VERBATIM quote
|
text the claim came from), type the claim into the Fact schema:
|
||||||
copied EXACTLY from the text (the FULL sentence or table row that
|
subject entity, relation, object/value, and the temporal
|
||||||
states the claim, at least 10 characters), and the temporal
|
restrictions the quote states. The Fact's quote is the given
|
||||||
restrictions the text states. All temporal fields are optional and
|
verbatim, copied exactly. All temporal fields are optional and must
|
||||||
must be contained in the quote. Only what the claim and its quote
|
be contained in the quote. Only what the claim and its quote state;
|
||||||
state; no inference. If the text does not state the claim, return
|
no inference. If the claim cannot be typed honestly, return null."""
|
||||||
null."""
|
|
||||||
claim: str = dspy.InputField(desc="the claim to type")
|
claim: str = dspy.InputField(desc="the claim to type")
|
||||||
text: str = dspy.InputField(
|
verbatim: str = dspy.InputField(
|
||||||
desc="the text the claim was extracted from — find the VERBATIM "
|
desc="the VERBATIM quote that states the claim, obtained before — "
|
||||||
"quote here, copied exactly")
|
"the Fact's quote field must copy it exactly")
|
||||||
fact: Fact | None = dspy.OutputField(
|
fact: Fact | None = dspy.OutputField(
|
||||||
desc="the typed Fact with its verbatim quote from the text, or "
|
desc="the typed Fact whose quote is the given verbatim, or null "
|
||||||
"null when the claim cannot be typed honestly")
|
"when the claim cannot be typed honestly")
|
||||||
|
|
||||||
|
|
||||||
class AnswerFromKG(dspy.Signature):
|
class AnswerFromKG(dspy.Signature):
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass EXTRACT tests (Pass 1 claims + verbatim, Pass 2 typing).
|
||||||
|
|
||||||
Law: the old single call asked a slow model for verbatim quotes + typed
|
Law: the old single call asked a slow model for verbatim quotes + typed
|
||||||
temporal fields + sibling order assertions in ONE giant JSON array — the
|
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 plain claims (free-form strings
|
shortens EVERY output: Pass 1 extracts the claims, each with its
|
||||||
with coreference resolved to the entity names — near-zero format tax);
|
VERBATIM quote (coreference resolved to the entity names); Pass 2 types
|
||||||
Pass 2 types ONE claim into the existing Fact schema per call.
|
ONE claim into the existing Fact schema per call — typing ONLY, the
|
||||||
|
verbatim given to it as an input (owner 1/11: the VERBATIM is obtained
|
||||||
|
before; the TYPE call never sees the text).
|
||||||
|
|
||||||
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
|
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
|
||||||
assertions become IMPOSSIBLE by construction, so orders are dropped from
|
assertions become IMPOSSIBLE by construction, so orders are dropped from
|
||||||
@@ -15,15 +17,19 @@ The store, the containment checks and the merge are UNTOUCHED — Pass 2
|
|||||||
emits the same typed Fact as before, minus orders.
|
emits the same typed Fact as before, minus orders.
|
||||||
|
|
||||||
Pinned:
|
Pinned:
|
||||||
1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the
|
1. ExtractClaims: free-form claims, coreferences RESOLVED (the claim
|
||||||
claim must name its entities, not 'he/it/the party').
|
must name its entities, not 'he/it/the party'), each carrying its
|
||||||
2. TypeClaim: one claim in -> one typed Fact out (same fields as the
|
VERBATIM quote — the quote is extracted HERE, in Pass 1.
|
||||||
legacy ExtractSignature.facts minus orders; temporal fields optional).
|
2. TypeClaim: one claim + its verbatim in -> one typed Fact out (same
|
||||||
3. The pipeline wiring: _extract_two_pass returns typed Fact objects;
|
fields as the legacy ExtractSignature.facts minus orders; temporal
|
||||||
|
fields optional) — no text input: the VERBATIM enters as an input.
|
||||||
|
3. The pipeline wiring: the two-pass path returns typed Fact objects;
|
||||||
candidates flow into _ingest_candidate exactly as before.
|
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
|
||||||
|
decides) — the TYPE model cannot corrupt the span.
|
||||||
|
|
||||||
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
||||||
"""
|
"""
|
||||||
@@ -36,7 +42,8 @@ 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 ExtractClaims, TypeClaim, Fact, ExtractSignature
|
from knowledge.extract import (Claim, ExtractClaims, ExtractSignature, Fact,
|
||||||
|
TypeClaim)
|
||||||
from knowledge.two_pass import claims_from, fact_from_claim
|
from knowledge.two_pass import claims_from, fact_from_claim
|
||||||
|
|
||||||
|
|
||||||
@@ -49,19 +56,27 @@ class Scripted:
|
|||||||
|
|
||||||
|
|
||||||
def test_extract_claims_signature():
|
def test_extract_claims_signature():
|
||||||
"""Pass 1: claims are free-form strings; coreferences resolved."""
|
"""Pass 1: claims + their VERBATIM quotes; coreferences resolved."""
|
||||||
fields = set(ExtractClaims.__fields__)
|
fields = set(ExtractClaims.__fields__)
|
||||||
assert fields == {"entities", "heading", "text", "claims"}, fields
|
assert fields == {"entities", "heading", "text", "claims"}, fields
|
||||||
|
a = ExtractClaims.model_fields["claims"].annotation
|
||||||
|
assert "Claim" in str(a), a # each claim now carries its verbatim
|
||||||
# what the model actually sees: dspy keeps desc in json_schema_extra
|
# what the model actually sees: dspy keeps desc in json_schema_extra
|
||||||
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
||||||
assert "coreference" in d.lower() or "resolved" in d.lower(), d
|
assert "verbatim" in d.lower(), d
|
||||||
print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft")
|
dv = (Claim.model_fields["verbatim"].json_schema_extra or {}).get("desc", "")
|
||||||
|
assert "verbatim" in dv.lower() and "copied exactly" in dv.lower(), dv
|
||||||
|
print("ok: ExtractClaims = claims with their VERBATIM quotes, coreferences resolved")
|
||||||
|
|
||||||
|
|
||||||
def test_type_claim_signature():
|
def test_type_claim_signature():
|
||||||
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
"""Pass 2: one claim + its verbatim -> one typed Fact; no text input;
|
||||||
|
orders NEVER produced here."""
|
||||||
fields = set(TypeClaim.__fields__)
|
fields = set(TypeClaim.__fields__)
|
||||||
assert fields == {"claim", "text", "fact"}, fields # text: the quote must be COPIED from it (live finding: without it, 69/70 invented quotes rejected)
|
# the VERBATIM is obtained BEFORE (Pass 1) and enters as an input; the
|
||||||
|
# text is GONE — the quote-finding job moved to ExtractClaims (owner
|
||||||
|
# 1/11: TypeClaim only enforces the correct typing of the Fact).
|
||||||
|
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 "Fact" in str(f), f
|
||||||
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
||||||
@@ -70,34 +85,44 @@ def test_type_claim_signature():
|
|||||||
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
|
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
|
||||||
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 -> one Fact; orders never produced (no siblings)")
|
print("ok: TypeClaim = one claim + verbatim in -> one Fact (typing only; no text)")
|
||||||
|
|
||||||
|
|
||||||
def test_claims_from_runs_pass1():
|
def test_claims_from_runs_pass1():
|
||||||
e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018",
|
e = Scripted(claims=Scripted(claims=[
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"]))
|
Claim(claim="Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]))
|
||||||
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
||||||
assert out == ["Pedro Sanchez is the prime minister of Spain since 2018",
|
assert [(c.claim, c.verbatim) for c in out] == [
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"], out
|
("Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
print("ok: claims_from extracts the plain claim strings")
|
"has been the prime minister of Spain since 2018"),
|
||||||
|
("Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")], out
|
||||||
|
print("ok: claims_from extracts the claims with their verbatim quotes")
|
||||||
|
|
||||||
|
|
||||||
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
|
||||||
|
verbatim — the scripted fact proposes a paraphrase, and it MUST be
|
||||||
|
overwritten (LLMs propose, code decides)."""
|
||||||
e = Scripted(typeclaim=Scripted(fact=Fact(
|
e = Scripted(typeclaim=Scripted(fact=Fact(
|
||||||
subject="Pedro Sanchez", relation="prime minister of",
|
subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain", quote="is a Spanish politician who has been the "
|
object="Spain", quote="a paraphrase the TYPE model invented",
|
||||||
"prime minister of Spain since 2018",
|
|
||||||
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", text="...")
|
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")
|
||||||
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
||||||
print("ok: fact_from_claim returns the typed Fact for one claim")
|
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")
|
||||||
|
|
||||||
|
|
||||||
def test_honest_empty():
|
def test_honest_empty():
|
||||||
e = Scripted(claims=Scripted(claims=[]))
|
e = Scripted(claims=Scripted(claims=[]))
|
||||||
assert claims_from(e, entities="", heading="", text="") == []
|
assert claims_from(e, entities="", heading="", text="") == []
|
||||||
e2 = Scripted(typeclaim=Scripted(fact=None))
|
e2 = Scripted(typeclaim=Scripted(fact=None))
|
||||||
assert fact_from_claim(e2, claim="", text="") is None
|
assert fact_from_claim(e2, claim="", verbatim="") is None
|
||||||
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||||
|
|
||||||
|
|
||||||
@@ -105,25 +130,32 @@ def test_claims_from_dedupes_exact_repeats():
|
|||||||
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||||
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||||
deterministic — the claim list must not be capped or filtered
|
deterministic — the claim list must not be capped or filtered
|
||||||
semantically, only made honest: no exact duplicates survive."""
|
semantically, only made honest: no exact duplicates survive. The
|
||||||
|
FIRST occurrence's verbatim is the one kept."""
|
||||||
calls = []
|
calls = []
|
||||||
|
|
||||||
class E: # minimal expert double
|
class E: # minimal expert double
|
||||||
def claims(self, entities, heading, text):
|
def claims(self, entities, heading, text):
|
||||||
calls.append((entities, heading))
|
calls.append((entities, heading))
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez is prime minister of Spain.",
|
claims = [Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
"pedro sanchez is prime minister of spain. ",
|
verbatim="prime minister of Spain"),
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
Claim(claim="pedro sanchez is prime minister of spain. ",
|
||||||
"Pedro Sanchez is prime minister of Spain.",
|
verbatim="the repeat's quote — must not survive"),
|
||||||
"from the text. I need to list factual claims"]
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
verbatim="Secretary-General of the PSOE"),
|
||||||
|
Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
|
verbatim="second repeat's quote"),
|
||||||
|
Claim(claim="from the text. I need to list factual claims",
|
||||||
|
verbatim="thinking leakage")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||||
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
assert [(c.claim, c.verbatim) for c in got] == [
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
("Pedro Sanchez is prime minister of Spain.", "prime minister of Spain"),
|
||||||
"from the text. I need to list factual claims"], got
|
("Pedro Sanchez is Secretary-General of the PSOE.", "Secretary-General of the PSOE"),
|
||||||
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
("from the text. I need to list factual claims", "thinking leakage")], got
|
||||||
|
print("ok: exact repeats deduped (case/space-insensitive); the first verbatim kept")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -5,6 +5,11 @@ mode ingests the typed facts from Pass 2 exactly as the legacy path
|
|||||||
did — same _ingest_candidate, same containment checks, same merge; the
|
did — same _ingest_candidate, same containment checks, same merge; the
|
||||||
single-pass path keeps working (control). No network: the expert's
|
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
|
||||||
|
only types — code PINS the fact's quote to Pass 1's verbatim, so the
|
||||||
|
STORED quotes (quotes.verbatim) must be Pass 1's spans (contained in
|
||||||
|
the page text), never the TYPE model's paraphrases.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -16,7 +21,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 Fact
|
from knowledge.extract import Claim, Fact
|
||||||
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
|
||||||
@@ -36,14 +41,22 @@ def make_page() -> WikiPage:
|
|||||||
|
|
||||||
|
|
||||||
class ScriptedClaims:
|
class ScriptedClaims:
|
||||||
|
"""Pass 1 double: claims WITH their verbatim quotes — spans that ARE
|
||||||
|
contained in PAGE_TEXT (the containment check runs for real)."""
|
||||||
|
|
||||||
def __call__(self, **kw):
|
def __call__(self, **kw):
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
|
claims = [Claim(claim="Pedro Sanchez has been the prime minister of Spain since 2018",
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE since 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
|
|
||||||
class ScriptedTypeClaim:
|
class ScriptedTypeClaim:
|
||||||
|
"""Pass 2 double: typing only — its scripted quotes are PARAPHRASES;
|
||||||
|
code must pin the fact's quote to Pass 1's verbatim instead."""
|
||||||
|
|
||||||
def __init__(self, facts):
|
def __init__(self, facts):
|
||||||
self.facts = facts
|
self.facts = facts
|
||||||
self.i = 0
|
self.i = 0
|
||||||
@@ -66,12 +79,11 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
e.typeclaim = ScriptedTypeClaim([
|
e.typeclaim = ScriptedTypeClaim([
|
||||||
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain",
|
object="Spain",
|
||||||
quote="has been the prime minister of Spain since 2018",
|
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"),
|
||||||
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
||||||
object="PSOE",
|
object="PSOE",
|
||||||
quote="Secretary-General of the Spanish Socialist Workers' "
|
quote="another paraphrase (must be overwritten)",
|
||||||
"Party (PSOE) since 2017",
|
|
||||||
start="2017", end=None, point=None, granularity="year"),
|
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
|
||||||
@@ -89,7 +101,14 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
assert len(rows) == 2, rows
|
assert len(rows) == 2, rows
|
||||||
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]
|
||||||
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
|
# the verbatim law end-to-end: the STORED quotes are Pass 1's verbatims
|
||||||
|
# (Pass 2's paraphrases never reach the store)
|
||||||
|
quotes = {r[0] for r in store.db.execute(
|
||||||
|
"SELECT verbatim FROM quotes").fetchall()}
|
||||||
|
assert quotes == {"has been the prime minister of Spain since 2018",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' "
|
||||||
|
"Party (PSOE) since 2017"}, quotes
|
||||||
|
print("ok: two_pass ingests typed facts (verbatim pinned, legacy checks)")
|
||||||
|
|
||||||
|
|
||||||
def test_single_pass_still_works():
|
def test_single_pass_still_works():
|
||||||
|
|||||||
+34
-21
@@ -1,52 +1,65 @@
|
|||||||
"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass extraction (Pass 1 claims + verbatim quotes, Pass 2 typing).
|
||||||
|
|
||||||
The single-pass EXTRACT asked slow local models for a giant JSON array
|
The single-pass EXTRACT asked slow local models for a giant JSON array
|
||||||
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
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 plain claims (free-form
|
Two-pass shortens every output: Pass 1 lists the claims, each with its
|
||||||
strings, coreferences resolved — near-zero format tax); Pass 2 types
|
VERBATIM quote (extracted while the text is in front of the model);
|
||||||
ONE claim at a time into the same Fact schema the store already eats.
|
Pass 2 types ONE claim at a time into the same Fact schema the store
|
||||||
|
already eats — typing ONLY, the verbatim given as an input and the
|
||||||
|
TYPE call never carrying the chunk (owner 1/11: the VERBATIM is
|
||||||
|
obtained before).
|
||||||
|
|
||||||
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. The legacy single-pass path (and table frags) keeps them.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .extract import Claim
|
||||||
|
|
||||||
|
|
||||||
def claims_from(expert, entities: str, heading: str, text: str,
|
def claims_from(expert, entities: str, heading: str, text: str,
|
||||||
charge_llm=None) -> list[str]:
|
charge_llm=None) -> list[Claim]:
|
||||||
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.
|
"""Pass 1: the chunk's claims, each with its VERBATIM quote — the
|
||||||
|
quote is extracted HERE, in the same call that reads the text.
|
||||||
|
|
||||||
The list is made honest by CODE only: exact repeats are dropped
|
The list is made honest by CODE only: exact repeats are dropped
|
||||||
(live finding 26/10: glm sometimes lists its whole list twice, and
|
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||||
thinking leakage leaks in as list items). Dedup is case- and
|
thinking leakage leaks in as list items). Dedup is case- and
|
||||||
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
whitespace-insensitive on the CLAIM text; the FIRST occurrence's
|
||||||
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
(claim, verbatim) is kept. NO cap, NO semantic filter: completeness
|
||||||
26/10) — every unique claim gets its TYPE call.
|
beats budget (owner ruling 26/10) — every unique claim gets its
|
||||||
|
TYPE call.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.claims(entities=entities, heading=heading, text=text)
|
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||||
seen: dict[str, str] = {}
|
seen: dict[str, Claim] = {}
|
||||||
for c in (pred.claims or []):
|
for c in (pred.claims or []):
|
||||||
c = (c or "").strip()
|
claim = (getattr(c, "claim", "") or "").strip()
|
||||||
if c:
|
verbatim = (getattr(c, "verbatim", "") or "").strip()
|
||||||
key = " ".join(c.lower().split())
|
if claim:
|
||||||
|
key = " ".join(claim.lower().split())
|
||||||
if key not in seen:
|
if key not in seen:
|
||||||
seen[key] = c
|
seen[key] = Claim(claim=claim, verbatim=verbatim)
|
||||||
return list(seen.values())
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
def fact_from_claim(expert, claim: str, text: 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).
|
||||||
|
|
||||||
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
TYPING ONLY: the VERBATIM was obtained in Pass 1 and enters as an
|
||||||
came from) — without the text the model invents a quote and the
|
input — the TYPE call never sees the text. Code PINS the Fact's
|
||||||
containment check rejects it (live finding 26/10: 69/70 rejected).
|
quote to it (LLMs propose, code decides): a paraphrased copy would
|
||||||
The store's checks validate everything downstream as before. No
|
fail the containment check and lose the fact (live finding 26/10:
|
||||||
|
without grounding, 69/70 invented quotes were rejected). The
|
||||||
|
store's checks validate everything downstream as before. No
|
||||||
orders: no siblings by construction.
|
orders: no siblings by construction.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.typeclaim(claim=claim, text=text)
|
pred = expert.typeclaim(claim=claim, verbatim=verbatim)
|
||||||
return getattr(pred, "fact", None)
|
fact = getattr(pred, "fact", None)
|
||||||
|
if fact is not None:
|
||||||
|
fact.quote = verbatim # the law: the Fact's quote IS Pass 1's verbatim
|
||||||
|
return fact
|
||||||
@@ -23,7 +23,8 @@ EVENTS = [
|
|||||||
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
|
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
|
||||||
"event": "claims.done", "page": "Pedro Sanchez",
|
"event": "claims.done", "page": "Pedro Sanchez",
|
||||||
"heading": "Career", "out": {"n_claims": 1,
|
"heading": "Career", "out": {"n_claims": 1,
|
||||||
"claims": ["PM of Spain since 2018"]}},
|
"claims": [{"claim": "PM of Spain since 2018",
|
||||||
|
"verbatim": "prime minister of Spain since 2018"}]}},
|
||||||
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
|
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
|
||||||
"event": "type.done", "page": "Pedro Sanchez",
|
"event": "type.done", "page": "Pedro Sanchez",
|
||||||
"claim": "PM of Spain since 2018",
|
"claim": "PM of Spain since 2018",
|
||||||
|
|||||||
Reference in New Issue
Block a user