"""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. 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.""" 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") 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 ' 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 ' 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