Merge pull request 'knowledge: typed outputs for all 5 remaining signatures (block PR)' (#14) from feature/typed-knowledge into main
This commit was merged in pull request #14.
This commit is contained in:
+15
-30
@@ -269,18 +269,10 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.translate(question=question, context=context)
|
||||
q_raw = (pred.queries or "").strip()
|
||||
queries = [q.strip() for q in
|
||||
next((ln.split(":", 1)[1] for ln in q_raw.splitlines()
|
||||
if ln.strip().upper().startswith("QUERIES")), q_raw).split(",")
|
||||
if q.strip()][:2]
|
||||
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
|
||||
if not queries:
|
||||
queries = [" ".join(kws[:3])]
|
||||
e_raw = (pred.entities or "").strip()
|
||||
entity_terms = [t.strip() for t in
|
||||
next((ln.split(":", 1)[1] for ln in e_raw.splitlines()
|
||||
if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",")
|
||||
if t.strip()][:4]
|
||||
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
|
||||
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
|
||||
|
||||
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
|
||||
@@ -647,22 +639,19 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.select_table(question=question, tables=rendered)
|
||||
idx_raw = (pred.table_index or "").strip()
|
||||
if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"):
|
||||
return None
|
||||
try:
|
||||
idx = int(re.findall(r"\d+", idx_raw)[0])
|
||||
except (ValueError, IndexError):
|
||||
chosen = pred.chosen
|
||||
if chosen is None:
|
||||
return None
|
||||
idx = chosen.table_index
|
||||
table = next((t for t in page.tables if t.idx == idx), None)
|
||||
if table is None:
|
||||
return None
|
||||
page._list_table_idx = idx # the harvest skips the LIST answer's table
|
||||
column = (pred.column or "").strip()
|
||||
column = chosen.column.strip()
|
||||
col_i = next((i for i, h in enumerate(table.header)
|
||||
if column.casefold() in h.casefold()), 0)
|
||||
set_name = (pred.set_name or "").strip() or question[:60]
|
||||
origin_question = (pred.origin_question or "").strip() or question
|
||||
set_name = chosen.set_name.strip() or question[:60]
|
||||
origin_question = question
|
||||
# INGEST ALL ROWS: one membership edge per row, quote = the full
|
||||
# stored row line, containment against the stored table text
|
||||
doc_id = self.store.add_document(
|
||||
@@ -888,16 +877,12 @@ class KnowledgeExpert:
|
||||
entities=", ".join(expected[:8]),
|
||||
tables="\n".join(rendered))
|
||||
promoted = 0
|
||||
for line in (pred.decision or "").strip().splitlines():
|
||||
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
|
||||
flags=re.I)
|
||||
if not m:
|
||||
continue
|
||||
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
|
||||
got = lookup.get(idx)
|
||||
if verdict != "YES" or got is None:
|
||||
for d in (pred.decisions or []):
|
||||
got = lookup.get(d.table_index)
|
||||
if not d.promote or got is None:
|
||||
continue
|
||||
page, t = got
|
||||
col = (d.column or "").strip()
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
@@ -906,13 +891,13 @@ class KnowledgeExpert:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
|
||||
self._log(f"skim promote: table {d.table_index} ({page.title}): LLM said "
|
||||
f"YES but {overlap}/{nm} entity overlap — refused",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim promote: {merged} rows of table {idx} "
|
||||
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||
promoted += 1
|
||||
self._skim_leads = [] # consumed: bounded, never re-asked
|
||||
@@ -1053,5 +1038,5 @@ class KnowledgeExpert:
|
||||
"quote": pred.quote.strip(),
|
||||
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
||||
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
+38
-16
@@ -6,10 +6,19 @@ the FULL document text — so chunking can never fake a quote.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""Honest self-assessment of an answer drawn from KG rows."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class Fact(BaseModel):
|
||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||
@@ -23,13 +32,13 @@ class TranslateSignature(dspy.Signature):
|
||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
||||
references ('that state', 'the same river') using the context: the original
|
||||
question and the evidence rows already gathered. Output two lines:
|
||||
QUERIES: 1-2 wikipedia search queries, comma separated.
|
||||
ENTITIES: the resolved entity names the answer is about, comma separated."""
|
||||
question and the evidence rows already gathered."""
|
||||
question: str = dspy.InputField()
|
||||
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
|
||||
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries")
|
||||
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river")
|
||||
queries: list[str] = dspy.OutputField(
|
||||
desc="1-2 Wikipedia search queries, most specific first")
|
||||
entities: list[str] = dspy.OutputField(
|
||||
desc="the resolved entity names the answer is about")
|
||||
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
@@ -59,7 +68,8 @@ class AnswerFromKG(dspy.Signature):
|
||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
||||
|
||||
|
||||
class VerifyCountSignature(dspy.Signature):
|
||||
@@ -81,18 +91,31 @@ class VerifyCountSignature(dspy.Signature):
|
||||
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
|
||||
|
||||
|
||||
class TableChoice(BaseModel):
|
||||
"""The table chosen as the answer's enumeration, if any."""
|
||||
table_index: int = dspy.OutputField(desc="the chosen table's index")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates")
|
||||
|
||||
|
||||
class SelectTableSignature(dspy.Signature):
|
||||
"""You are the SELECT TABLE step of a knowledge machine. Given a question
|
||||
and the tables found in an article (index, caption, header columns, row
|
||||
count — NOT the rows), decide: does one of these tables enumerate the
|
||||
answer? Output the table index and the column holding the answer
|
||||
elements, or NONE."""
|
||||
answer?"""
|
||||
question: str = dspy.InputField()
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'")
|
||||
table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE")
|
||||
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
|
||||
chosen: TableChoice | None = dspy.OutputField(
|
||||
desc="the chosen table and its answer column; null when NO table enumerates the answer")
|
||||
|
||||
|
||||
class PromotionDecision(BaseModel):
|
||||
"""One table's promotion verdict."""
|
||||
table_index: int = dspy.OutputField(desc="the table's index from the list")
|
||||
promote: bool = dspy.OutputField(
|
||||
desc="True when this table holds data about those entities for the goal")
|
||||
column: str = dspy.OutputField(
|
||||
desc="when promoted: the header holding the goal's values; empty otherwise")
|
||||
|
||||
|
||||
class SkimPromoteSignature(dspy.Signature):
|
||||
@@ -102,13 +125,12 @@ class SkimPromoteSignature(dspy.Signature):
|
||||
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
|
||||
Given the run's goal, the entities it is about, and the tables' identity
|
||||
(caption, headers, row count, quantity signals — NOT the rows), decide
|
||||
per table whether it holds data about those entities for the goal.
|
||||
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
|
||||
is the header holding the goal's values."""
|
||||
per table whether it holds data about those entities for the goal."""
|
||||
goal: str = dspy.InputField(desc="the run's overall goal question")
|
||||
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
|
||||
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'")
|
||||
decisions: list[PromotionDecision] = dspy.OutputField(
|
||||
desc="one verdict per table in the list")
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from knowledge.wiki import WikiPage, parse_tables
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
|
||||
_tokens, _term_hits, _proper_nouns)
|
||||
from knowledge.store import KnowledgeStore
|
||||
@@ -118,10 +119,8 @@ def test_subject_guard_list():
|
||||
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
|
||||
|
||||
class Pred:
|
||||
table_index = "1"
|
||||
column = "River"
|
||||
set_name = "longest rivers of Italy"
|
||||
origin_question = q
|
||||
chosen = TableChoice(table_index=1, column="River",
|
||||
set_name="longest rivers of Italy")
|
||||
|
||||
e2.select_table = lambda **kw: Pred()
|
||||
ans2 = e2._list_from_page(italy_page(), q, None)
|
||||
|
||||
@@ -13,6 +13,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.extract import PromotionDecision
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
@@ -32,15 +33,15 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
|
||||
|
||||
class FakePromote:
|
||||
"""Scripted skim_promote (dspy module shape): returns fixed decision."""
|
||||
def __init__(self, decision: str):
|
||||
self.decision_text = decision
|
||||
"""Scripted skim_promote (dspy module shape): returns typed decisions."""
|
||||
def __init__(self, decisions):
|
||||
self.decisions = decisions
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
self.calls += 1
|
||||
obj = type("P", (), {})()
|
||||
obj.decision = self.decision_text
|
||||
obj.decisions = self.decisions
|
||||
return obj
|
||||
|
||||
|
||||
@@ -81,7 +82,8 @@ def test_promotion_ingests_goal_table():
|
||||
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
|
||||
# bounded promotion: LLM says YES (column Mean discharge)
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge")
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 1, "promoted table ingested"
|
||||
@@ -100,7 +102,8 @@ def test_promotion_refuses_world_table():
|
||||
e._current_goal_terms = ["total"] # no overlap with caption/header
|
||||
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")]) # LLM WRONG
|
||||
p = e._promote_leads(EVIDENCE, lambda: None)
|
||||
assert p == 0, "code disposes: zero entity overlap -> refused"
|
||||
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
|
||||
@@ -110,7 +113,7 @@ def test_promotion_refuses_world_table():
|
||||
|
||||
def test_no_leads_no_call():
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
e.skim_promote = FakePromote("1: YES x")
|
||||
e.skim_promote = FakePromote([])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 0 and e.skim_promote.calls == 0 and not charged, \
|
||||
|
||||
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo r
|
||||
|
||||
from knowledge.checks import check_candidate, quote_containment, trusted_source
|
||||
from knowledge.chunker import chunk_page
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
|
||||
@@ -225,10 +226,8 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "1"
|
||||
p.column = "Country"
|
||||
p.set_name = "sovereign states in Europe"
|
||||
p.origin_question = kw.get("question", "")
|
||||
p.chosen = TableChoice(table_index=1, column="Country",
|
||||
set_name="sovereign states in Europe")
|
||||
return p
|
||||
|
||||
class FakeStore:
|
||||
@@ -286,10 +285,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "NONE"
|
||||
p.column = ""
|
||||
p.set_name = ""
|
||||
p.origin_question = ""
|
||||
p.chosen = None
|
||||
return p
|
||||
ke.select_table = FakeNonePicker()
|
||||
assert ke._list_from_page(page, "irrelevant", None) is None
|
||||
|
||||
Reference in New Issue
Block a user