Files
floop/code/knowledge/extract.py
T
onibot 1ebb4cfc0d knowledge: PR-3 skim notices to the loop + bounded lead promotion
PR-1 made the skim SEE (surfaces + signals); PR-2 made it HARVEST
deterministically. PR-3 closes the loop (KNOWLEDGE.md §7):

- Skim notices: every knowledge answer's stats carry what the fetched
  articles contained beyond the answer (table identities, infobox
  quantities, link candidates, goal-filtered). The engine copies them
  into payload['skim']; the machine renders them to the ROUTER context
  ('seen in passing (E1): ...') and to the run notes — later steps know
  what exists and where it lives instead of re-searching blind. A notice
  is a pointer, never evidence: it answers nothing by itself.
- Bounded lead promotion (Emili's 'deterministic + LLM fallback'):
  quantity tables that match NO goal word are queued as leads (PR-2);
  now ONE dspy call (SkimPromoteSignature) decides over the tables'
  IDENTITY lines (caption/headers/rows/quantities — never the rows),
  per fetched page with leads, only when leads exist. The LLM proposes;
  fixed code disposes: a promoted table still passes the entity-overlap
  check (a world discharge table is refused for Po/Adige/Tiber), the
  named column must exist, and ingestion goes through the same
  containment-checked _ingest_scalar_table as the deterministic path.
- Refactor: row ingestion extracted to _ingest_scalar_table (shared by
  harvest + promotion); _entity_overlap_count shared; skim state
  (_skim_notices/_skim_leads/_current_goal_question) reset per call.
- find_quantities: fix plain-digit quantities ('1540 m3/s', '1000 m3/s')
  — the thousands-separator-only regex missed them, and caption+header
  now join with a space ('m3/sRiver' broke the unit boundary).

Live smoke (real Wikipedia, scripted decision): goal terms without
'flow' queue both Italy tables as leads; the promoted 'Flow at the
mouth' table ingests all 27 rivers (Po 1540, Adige 235, Tiber 239
m3/s) containment-checked; promotion of the length table with a
'Flow' column name is refused (column does not exist).

Tests: 4 new (knowledge/tests/promote.py); suite 43/43 green.
2026-10-20 16:24:43 +02:00

117 lines
6.2 KiB
Python

"""LLM extraction per chunk (map) — dspy Signatures, minimal per floop convention.
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
VERBATIM spans. The containment check (checks.py) validates every span against
the FULL document text — so chunking can never fake a quote.
"""
from __future__ import annotations
import dspy
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: 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")
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,
copied exactly (at least 10 characters). Only facts the text states;
no inference."""
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")
class AnswerFromKG(dspy.Signature):
"""You are the ANSWER step of a knowledge machine. Answer the question using
ONLY the given knowledge-graph rows, each with its quote and source. Cite
rows by id. If the rows do not answer it, say UNKNOWN."""
question: str = dspy.InputField()
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")
class VerifyCountSignature(dspy.Signature):
"""You are the VERIFY step of a knowledge machine. A list answer has been
ingested from a table in one article (set_name, N elements). Find ONE
sentence in the article prose that states the expected count of that set
(independently of the table). Quote it VERBATIM. If no such sentence
exists, write NOQUOTE.
Example:
set_name: European Union member states
count: 27
GOOD quote: "The European Union (EU) is a supranational union of 27
member states that are party to the EU's founding treaties"
BAD (not a count statement): a row of the table itself."""
set_name: str = dspy.InputField()
count: str = dspy.InputField()
text: str = dspy.InputField(desc="the article prose WITHOUT the tables")
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
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."""
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")
class SkimPromoteSignature(dspy.Signature):
"""You are the SKIM PROMOTE step of a knowledge machine. While fetching
articles for one question, tables were seen in passing that carry
quantity data but match none of the goal's words (the goal's vocabulary
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."""
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'")
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%')."""
out: list[dict] = []
for line in (raw or "").strip().splitlines():
line = line.strip()
if not line or "|" not in line:
continue
parts = [p.strip() for p in line.split("|", 3)]
if len(parts) < 4:
continue
subject, relation, obj, quote = parts
if not (subject and relation and obj and quote):
continue
out.append({"subject": subject, "relation": relation,
"object": obj, "quote": quote})
return out