Compare commits
2
Commits
5c97fbf50a
...
2a515795e5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a515795e5 | ||
|
|
109885773c |
@@ -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}): "
|
||||
|
||||
+23
-14
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user