knowledge: typed Fact extraction via dspy native structured output
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.
This commit is contained in:
+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()
|
||||
|
||||
Reference in New Issue
Block a user