Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc1eceb720 | ||
|
|
4766b47127 | ||
|
|
56e3b22bbf | ||
|
|
0ed26d3406 | ||
|
|
4301277ccd | ||
|
|
c257e9fe88 | ||
|
|
12a1ffd77f | ||
|
|
65d42d1942 | ||
|
|
ce028b6973 | ||
|
|
a6453b0cb3 | ||
|
|
66e8bd4daa | ||
|
|
c3d1b5d6d3 | ||
|
|
f953778f0a | ||
|
|
c7bd010f47 | ||
|
|
2a515795e5 |
@@ -0,0 +1,99 @@
|
||||
"""Query anonymization before INIT (his design, 22/10): the model must
|
||||
decompose the question's SHAPE, not lean on its knowledge of the people in
|
||||
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
|
||||
...) before INIT sees the query; the placeholders are restored in the
|
||||
returned subquestions — deterministically, by exact string replacement.
|
||||
|
||||
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
|
||||
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class NamedEntity(BaseModel):
|
||||
"""One named entity found in the question."""
|
||||
name: str = dspy.OutputField(
|
||||
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
||||
kind: str = dspy.OutputField(
|
||||
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
||||
|
||||
|
||||
class EntityMaskSignature(dspy.Signature):
|
||||
"""You are the MASK step of a reasoning machine. Find the named entities
|
||||
in the question — people, organizations, places, titles of works, events.
|
||||
Copy each one's text exactly as it appears; do not add entities that are
|
||||
not explicitly named."""
|
||||
question: str = dspy.InputField()
|
||||
entities: list[NamedEntity] = dspy.OutputField(
|
||||
desc="the named entities found; empty when none")
|
||||
|
||||
|
||||
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
||||
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
||||
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
||||
|
||||
|
||||
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
||||
"""Mask the question deterministically. Longer names first (so
|
||||
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
||||
Returns (masked_question, restore_map placeholder -> original)."""
|
||||
restore: dict[str, str] = {}
|
||||
counters: dict[str, int] = {}
|
||||
masked = question
|
||||
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
|
||||
name = ent.name.strip()
|
||||
if not name or name not in masked:
|
||||
continue
|
||||
kind = ent.kind.strip().upper()
|
||||
prefix = _PREFIX.get(kind, "OTHER")
|
||||
counters[prefix] = counters.get(prefix, 0) + 1
|
||||
ph = f"{prefix}_{counters[prefix]}"
|
||||
if ph in restore: # same surface text twice: keep one mask
|
||||
continue
|
||||
masked = masked.replace(name, ph)
|
||||
restore[ph] = name
|
||||
return masked, restore
|
||||
|
||||
|
||||
def restore_mask(text: str, restore: dict[str, str]) -> str:
|
||||
"""Restore placeholders to the original names, longest first (so
|
||||
PERSON_10 is not eaten by PERSON_1)."""
|
||||
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
|
||||
reverse=True):
|
||||
text = text.replace(ph, name)
|
||||
return text
|
||||
|
||||
|
||||
# an identity question about ONE placeholder — the model asking who/what
|
||||
# the mask refers to. Detection lives in identity_answer: conservative
|
||||
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
|
||||
# text names the mask mechanism ('placeholder', 'refer(s) to').
|
||||
|
||||
|
||||
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
||||
"""If a subquestion only asks who/what one placeholder refers to, the
|
||||
answer is the mask map itself — no expert ever needed. None otherwise.
|
||||
|
||||
Conservative by law (never over-detect): exactly one placeholder in
|
||||
the text, and the question is literally 'who/what is <ph>' (ending
|
||||
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
||||
match) or it names the mask mechanism ('placeholder', 'refer(s) to')."""
|
||||
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
||||
masked_text)]
|
||||
if len(phs) != 1:
|
||||
return None
|
||||
ph = phs[0]
|
||||
t = masked_text.strip()
|
||||
literal = re.match(
|
||||
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"'])",
|
||||
t, flags=re.IGNORECASE)
|
||||
mechanism = any(k in t.casefold() for k in
|
||||
("placeholder", "refer to", "refers to"))
|
||||
if literal or mechanism:
|
||||
return restore[ph]
|
||||
return None
|
||||
+119
-21
@@ -7,24 +7,53 @@ Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .state import AnswerType
|
||||
|
||||
try:
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
except ImportError: # pragma: no cover — dspy <3.x
|
||||
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
||||
|
||||
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer,
|
||||
restore_mask)
|
||||
|
||||
|
||||
class Subquestion(BaseModel):
|
||||
"""One open subquestion in the goal's decomposition."""
|
||||
text: str = dspy.OutputField(desc="the subquestion, phrased as a question")
|
||||
depends_on: list[int] = dspy.OutputField(
|
||||
desc="1-based positions of the subquestions whose answers this one needs first; empty when none")
|
||||
answer_type: AnswerType = dspy.OutputField(
|
||||
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
||||
"CONSTANT for a universal constant, LIST for an enumeration of things")
|
||||
|
||||
|
||||
class InitSignature(dspy.Signature):
|
||||
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally
|
||||
present in the question plus a generic planning scaffold (number, method,
|
||||
machine, resources, dependencies), ask: what information or knowledge do I
|
||||
need to answer this? Write 1-4 open subquestions in dependency order.
|
||||
Use answer_type LIST when the subquestion asks for an enumeration of
|
||||
things (which countries, what rivers, list all members...)."""
|
||||
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED
|
||||
named entities from the question — treat each as a known specific entity;
|
||||
do not ask what or who the placeholder is."""
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated fields: "
|
||||
"text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT|LIST)"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-4 subquestions in dependency order; empty when the question is atomic")
|
||||
|
||||
|
||||
class Attendant(str, Enum):
|
||||
"""The closed set of attendants the ROUTE step may pick."""
|
||||
KNOWLEDGE = "knowledge"
|
||||
LOGIC = "logic"
|
||||
ANALYTIC = "analytic"
|
||||
NUMERIC = "numeric"
|
||||
FLOOP = "floop"
|
||||
USER = "user"
|
||||
|
||||
|
||||
class RouteSignature(dspy.Signature):
|
||||
@@ -33,10 +62,22 @@ class RouteSignature(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
catalog: str = dspy.InputField(desc="experts | floop | user, one per line with a summary")
|
||||
evidence: str = dspy.InputField(desc="relevant evidence rows, may be empty")
|
||||
attendant: str = dspy.OutputField(desc="one of: knowledge logic analytic numeric floop user")
|
||||
attendant: Attendant = dspy.OutputField(
|
||||
desc="knowledge: factual lookups from trusted sources; logic: deriving conclusions "
|
||||
"from provided premises, counting over evidence; analytic: equations/symbolic "
|
||||
"relations over provided quantities; numeric: closed arithmetic over provided "
|
||||
"numbers; floop: needs a sub-goal; user: nothing else plausibly answers it")
|
||||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""The expert's honest self-assessment (baseline draft — no engine
|
||||
verifies the expert yet)."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class ExpertSignature(dspy.Signature):
|
||||
"""You are an expert attendant answering a small, focused subquestion.
|
||||
Use the evidence rows when they answer it; otherwise answer from your own
|
||||
@@ -50,7 +91,9 @@ class ExpertSignature(dspy.Signature):
|
||||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||||
source_quote: str = dspy.OutputField(
|
||||
desc="VERBATIM text from the given evidence if the answer comes from it; EMPTY when answering from your own knowledge")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: the evidence or your knowledge settles it; medium: plausible "
|
||||
"but not fully settled; low: a guess you would verify first")
|
||||
|
||||
|
||||
class MissingSignature(dspy.Signature):
|
||||
@@ -60,9 +103,8 @@ class MissingSignature(dspy.Signature):
|
||||
the evidence."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated: text | depends_on ('none' or #E refs) | answer_type"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-3 subquestions that would close the gap; empty when nothing helps")
|
||||
|
||||
|
||||
class AnswerSignature(dspy.Signature):
|
||||
@@ -72,7 +114,8 @@ class AnswerSignature(dspy.Signature):
|
||||
marks verification status separately, do not hedge about it."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
unverified: str = dspy.InputField(desc="'true' if the prover could not verify derivability")
|
||||
unverified: bool = dspy.InputField(
|
||||
desc="True when the prover could not verify the answer's derivability from the evidence")
|
||||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||||
|
||||
|
||||
@@ -85,22 +128,76 @@ class FloopModules:
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
self.mask = dspy.Predict(EntityMaskSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||
"""(parsed subquestions, raw model output). The machine decides what
|
||||
an empty parse means: empty raw = the question is atomic; non-empty
|
||||
raw that parses to nothing = model garbage (run I) — degrade."""
|
||||
pred = self.init(question=question)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
raw that parses to nothing = model garbage (run I) — degrade.
|
||||
|
||||
Typed output: a response that violates the Subquestion schema raises
|
||||
AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
|
||||
the raw garbage — hand it back as the degrade signal.
|
||||
|
||||
ANONYMIZATION (his design): named entities are masked before INIT
|
||||
so the model decomposes shape, not identity — restored in the
|
||||
returned subquestions, deterministically. Identity questions about
|
||||
the placeholders (PR-16 live run: 'who is PERSON_1?') carry a
|
||||
KNOWN answer; the machine seeds them as evidence instead of
|
||||
routing them to an expert."""
|
||||
masked, restore = self.anonymize(question)
|
||||
try:
|
||||
pred = self.init(question=masked)
|
||||
except AdapterParseError as e:
|
||||
return [], (e.lm_response or "unparseable response")
|
||||
subs = []
|
||||
for s in self._subs_from_typed(pred.subquestions):
|
||||
# identity detection on the MASKED text (placeholders still
|
||||
# present); then restore for the machine's question text
|
||||
ans = identity_answer(s["text"], restore)
|
||||
text = restore_mask(s["text"], restore)
|
||||
if ans is not None:
|
||||
s = {**s, "known_answer": ans} # seeded by the machine
|
||||
subs.append({**s, "text": text})
|
||||
return subs, ""
|
||||
|
||||
def anonymize(self, question: str) -> tuple[str, dict]:
|
||||
"""Mask named entities to typed placeholders. No entity found (or the
|
||||
mask call dies) -> the question passes unchanged, mask map empty."""
|
||||
try:
|
||||
pred = self.mask(question=question)
|
||||
entities = pred.entities or []
|
||||
except AdapterParseError:
|
||||
return question, {}
|
||||
masked, restore = apply_mask(question, entities)
|
||||
return masked, restore
|
||||
|
||||
@staticmethod
|
||||
def _subs_from_typed(subs) -> list[dict]:
|
||||
"""Typed Subquestion objects -> machine dicts. A bare number is a
|
||||
line number, never a question (run I law kept)."""
|
||||
out = []
|
||||
for s in (subs or []):
|
||||
text = (s.text or "").strip()
|
||||
if not text or text.isdigit():
|
||||
continue
|
||||
out.append({"text": text, "deps": list(s.depends_on or []),
|
||||
"answer_type": s.answer_type})
|
||||
return out
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
try:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
except AdapterParseError:
|
||||
return []
|
||||
return self._subs_from_typed(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
"""Typed attendant: the enum is the closed contract. A response
|
||||
outside the set raises AdapterParseError after dspy's re-ask —
|
||||
the machine's invalid-attendant branch stays as a contract guard."""
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
return pred.attendant.strip().lower(), pred.reason.strip()
|
||||
return str(pred.attendant.value), pred.reason.strip()
|
||||
|
||||
def expert_draft(self, question: str, expert_kind: str, evidence: str,
|
||||
parent_question: str = "") -> dict:
|
||||
@@ -109,11 +206,12 @@ class FloopModules:
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"source_quote": pred.source_quote.strip(),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
|
||||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||||
pred = self.answer(goal=goal, evidence=evidence, unverified="true" if unverified else "false")
|
||||
pred = self.answer(goal=goal, evidence=evidence,
|
||||
unverified=unverified)
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
|
||||
@@ -156,6 +156,7 @@ _STAGE_BY_MODULE = {
|
||||
"Expert": "EXPERT",
|
||||
"Missing": "MISSING",
|
||||
"Answer": "ANSWER",
|
||||
"EntityMaskSignature": "MASK",
|
||||
"KnowledgeExpert": "knowledge",
|
||||
"InitSignature": "INIT",
|
||||
"RouteSignature": "ROUTE",
|
||||
|
||||
@@ -192,6 +192,20 @@ class FloopRun:
|
||||
if isinstance(tok, int) and 1 <= tok <= len(created):
|
||||
resolved.append(created[tok - 1].qid)
|
||||
q.deps = resolved
|
||||
# anonymization seeds (his design): identity questions the mask map
|
||||
# already answers land as evidence NOW — zero LLM calls
|
||||
for q, s in zip(created, subs):
|
||||
if s.get("known_answer"):
|
||||
self.table.append(EvidenceRow(
|
||||
qid=q.qid, answer_type=q.answer_type,
|
||||
payload={"value": s["known_answer"],
|
||||
"quote": f"{s['known_answer']} — named in the question itself"},
|
||||
engine="mask:seed", trace=["anonymization: placeholder resolved from the mask map"],
|
||||
provenance={}, verified=True))
|
||||
q.status = "answered"
|
||||
q.reason = "identity seeded from the mask map"
|
||||
self.notes.append(
|
||||
f"{q.qid}: seeded from anonymization — no expert call needed")
|
||||
|
||||
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
||||
|
||||
|
||||
+16
-31
@@ -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
|
||||
@@ -1003,7 +988,7 @@ 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 raw.stop:
|
||||
if raw.stop_table:
|
||||
stopped.add(frag["table_idx"])
|
||||
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
|
||||
f"({frag['caption'][:40]!r}) not relevant — "
|
||||
@@ -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),
|
||||
}
|
||||
+40
-18
@@ -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):
|
||||
@@ -39,7 +48,7 @@ class ExtractSignature(dspy.Signature):
|
||||
copied exactly (at least 10 characters). Only facts the text states;
|
||||
no inference.
|
||||
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.
|
||||
its subject is wrong for the question, set stop_table=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()
|
||||
@@ -47,7 +56,7 @@ class ExtractSignature(dspy.Signature):
|
||||
text: str = dspy.InputField()
|
||||
facts: list[Fact] = dspy.OutputField(
|
||||
desc="the extracted facts; empty list if none")
|
||||
stop: bool = dspy.OutputField(
|
||||
stop_table: bool = dspy.OutputField(
|
||||
desc="True when this table fragment's subject is wrong for the question")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -92,18 +92,18 @@ def test_process_page_fragments():
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
|
||||
# scripted extractor: world-table parts -> stop_table=True; Italy table -> one Fact
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts, stop=False):
|
||||
def __init__(self, facts, stop_table=False):
|
||||
self.facts = facts
|
||||
self.stop = stop
|
||||
self.stop_table = stop_table
|
||||
|
||||
def fake_extract(question, heading, text, _calls=calls):
|
||||
_calls.append((question, heading, text))
|
||||
if "World rivers" in text:
|
||||
return FakeOut([], stop=True)
|
||||
return FakeOut([], stop_table=True)
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
|
||||
@@ -191,7 +191,7 @@ def part_of(frag: dict) -> str:
|
||||
|
||||
def parse_stop_table(out_text: str) -> bool:
|
||||
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
|
||||
code reads the typed `stop: bool` field of ExtractSignature."""
|
||||
code reads the typed `stop_table: bool` field of ExtractSignature."""
|
||||
return "STOP_TABLE" in (out_text or "").upper()[:80]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Query anonymization tests (his design, 22/10): INIT must decompose the
|
||||
question's SHAPE, not lean on its knowledge of the named people in it.
|
||||
|
||||
Laws under test:
|
||||
1. MASK proposes entities; apply_mask/restore_mask are DETERMINISTIC —
|
||||
longer names first, one mask per surface text, typed placeholders.
|
||||
2. init_decompose masks before INIT and restores in the subquestions.
|
||||
3. No entities found -> the question reaches INIT unchanged.
|
||||
4. MASK dying (AdapterParseError) -> passthrough, never a dead run.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/anonymize.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
|
||||
|
||||
|
||||
def _lm(script: list[str]) -> None:
|
||||
"""An engine replaying a script: one raw response per LM call."""
|
||||
class RawEngine:
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
def complete(self, request):
|
||||
raw = script[min(self.i, len(script) - 1)]
|
||||
self.i += 1
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
Q = "Who was the President before Pedro Sanchez?"
|
||||
_MASKED_ENTS = '''[[ ## entities ## ]]
|
||||
[{"name": "Pedro Sanchez", "kind": "PERSON"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_TWO_SUBS = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which office does PERSON_1 hold as President?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before PERSON_1 took office?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_apply_restore_deterministic():
|
||||
ents = [NamedEntity(name="Pedro Sanchez", kind="PERSON")]
|
||||
masked, restore = apply_mask(Q, ents)
|
||||
assert masked == "Who was the President before PERSON_1?", masked
|
||||
assert restore == {"PERSON_1": "Pedro Sanchez"}
|
||||
# longer first: a full name is never half-masked by a shorter one
|
||||
ents2 = [NamedEntity(name="Pedro Sanchez", kind="PERSON"),
|
||||
NamedEntity(name="Pedro", kind="PERSON")]
|
||||
m2, r2 = apply_mask("Pedro Sanchez and Pedro", ents2)
|
||||
assert m2 == "PERSON_1 and PERSON_2", m2
|
||||
assert restore_mask(m2, r2) == "Pedro Sanchez and Pedro"
|
||||
# restore order: PERSON_10 before PERSON_1
|
||||
r3 = {f"PERSON_{i}": f"name{i}" for i in range(1, 11)}
|
||||
assert "name10" in restore_mask("PERSON_10", r3)
|
||||
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
|
||||
|
||||
|
||||
def test_init_decompose_masks_and_restores():
|
||||
# script: first call = MASK, second = INIT
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS])
|
||||
subs, raw = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2, subs
|
||||
assert "Pedro Sanchez" in subs[0]["text"] and "PERSON_1" not in subs[0]["text"], subs[0]
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: INIT sees the masked query; subquestions come back restored")
|
||||
|
||||
|
||||
def test_no_entities_passthrough():
|
||||
_lm(['''[[ ## entities ## ]]
|
||||
[]
|
||||
|
||||
[[ ## completed ## ]]''', _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: no entities found -> question reaches INIT unchanged")
|
||||
|
||||
|
||||
_TWO_SUBS_ID = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Which office does PERSON_1 hold as President?", "depends_on": [1], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before PERSON_1?", "depends_on": [2], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_identity_subquestion_seeded():
|
||||
# the live PR-16 shape: subquestion 1 asks who PERSON_1 is — the mask
|
||||
# map already knows. It must come back marked known_answer, never routed.
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS_ID])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 3, subs
|
||||
assert subs[0].get("known_answer") == "Pedro Sanchez", subs[0]
|
||||
assert not subs[1].get("known_answer") and not subs[2].get("known_answer")
|
||||
print("ok: identity subquestion carries known_answer (never routed)")
|
||||
|
||||
|
||||
def test_identity_detection_conservative():
|
||||
# 'who is PERSON_1's predecessor' is NOT an identity question
|
||||
r = {"PERSON_1": "Pedro Sanchez"}
|
||||
assert identity_answer("Who is PERSON_1?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
|
||||
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
|
||||
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
|
||||
assert identity_answer("What office does PERSON_1 hold?", r) is None
|
||||
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
|
||||
print("ok: identity detection conservative (possessives/comparatives not eaten)")
|
||||
|
||||
|
||||
def test_mask_death_passthrough():
|
||||
# MASK response violates the schema -> AdapterParseError -> passthrough
|
||||
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: MASK death -> passthrough, never a dead run")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_apply_restore_deterministic()
|
||||
test_init_decompose_masks_and_restores()
|
||||
test_no_entities_passthrough()
|
||||
test_identity_subquestion_seeded()
|
||||
test_identity_detection_conservative()
|
||||
test_mask_death_passthrough()
|
||||
print("\nanonymization tests passed")
|
||||
+144
-128
@@ -1,20 +1,24 @@
|
||||
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I).
|
||||
"""PR-10b tests: typed INIT via dspy native structured output.
|
||||
|
||||
Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM
|
||||
answered with its own line numbers as an extra pipe field
|
||||
('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1'
|
||||
and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and
|
||||
the machine burned 4 calls on garbage before luck produced the answer.
|
||||
Run I taught the pipe parser every defensive trick (line-number shifting,
|
||||
bare-number dropping). The typed migration removes the string contract
|
||||
entirely: dspy renders the Subquestion schema (enum answer_type,
|
||||
list[int] depends_on) into the prompt and parses responses back into
|
||||
typed objects — no Python string parsing on the production path.
|
||||
|
||||
Three laws under test:
|
||||
1. parse_subquestions shifts the numbered form and never accepts a bare
|
||||
number as a subquestion text.
|
||||
2. The machine degrades to the ORIGINAL question as one OPEN
|
||||
subquestion when nothing parses (a routable question is text).
|
||||
3. The prompt log appends the RAW LM response to the prompt file — the
|
||||
parsed OUTPUT line can lie by omission.
|
||||
Laws under test:
|
||||
1. The typed path E2E: a model response (raw text, through a REAL
|
||||
dspy.LM engine) parses into typed Subquestions; the machine dicts
|
||||
carry text, depends_on ints, and the AnswerType enum.
|
||||
2. Bare-number texts are still dropped (run-I law, now in
|
||||
_subs_from_typed).
|
||||
3. A schema-violating response (AdapterParseError, even after dspy's
|
||||
own JSON re-ask) becomes the degrade signal: (subs=[], raw) — the
|
||||
machine routes the ORIGINAL question, never garbage.
|
||||
4. The atomic case (empty subquestions list) stays atomic.
|
||||
|
||||
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py
|
||||
No network. The engine returns raw text — DummyLM would bypass the
|
||||
adapter and test nothing. Run: .venv/bin/python tests/robust_init.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,151 +27,163 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
import dspy
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from floop.dspy_modules import FloopModules, Subquestion
|
||||
from floop.state import AnswerType, Budget
|
||||
from floop.machine import FloopRun
|
||||
|
||||
import tempfile as tf
|
||||
from floop.stream import RunStreams
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
|
||||
# --- 1) the parser -----------------------------------------------------------
|
||||
|
||||
def test_parse_numbered_lines():
|
||||
# the exact run-I shape: model line numbers as an extra first field
|
||||
raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n"
|
||||
"2 | When did that president's term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
"""A dspy.LM whose engine returns raw text — the REAL wire shape.
|
||||
cache=False: dspy persists responses to disk keyed by (model, prompt)
|
||||
and would cross-contaminate tests sharing the fake model name."""
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(),
|
||||
cache=False))
|
||||
|
||||
|
||||
# a canonical typed response, markers and all
|
||||
_GOOD = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which presidency does Pedro Sanchez hold?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before him?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_typed_init_e2e():
|
||||
_lm(_GOOD)
|
||||
subs, raw = FloopModules().init_decompose(
|
||||
"Who was the President before Pedro Sanchez?")
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?"
|
||||
assert subs[0]["deps"] == []
|
||||
assert subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1], subs[1]
|
||||
print("ok: numbered-line form shifted (text, deps, type all intact)")
|
||||
|
||||
|
||||
def test_parse_bare_number_lines_dropped():
|
||||
# even if the number survives as text, it must be dropped — never routable
|
||||
raw = "1 | none | OPEN\n2 | none | OPEN"
|
||||
subs = parse_subquestions(raw)
|
||||
assert subs == [], subs
|
||||
print("ok: bare-number texts dropped (nothing routable = '1' or '2')")
|
||||
|
||||
|
||||
def test_parse_enumerator_prefix():
|
||||
# '1. Who was ...' inside the FIRST field — not a separate field
|
||||
raw = ("1. Who was the President before Pedro Sanchez? | none | OPEN\n"
|
||||
"2. When did his term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President before Pedro Sanchez?"
|
||||
assert subs[0]["text"] == "Which presidency does Pedro Sanchez hold?"
|
||||
assert subs[0]["deps"] == [] and subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: enumerator prefixes stripped from the text field")
|
||||
print("ok: typed INIT parses through the real adapter path (E2E)")
|
||||
|
||||
|
||||
def test_parse_happy_path_unchanged():
|
||||
# the old well-formed cases keep working (regression guard)
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||\n1 | none | OPEN") == []
|
||||
print("ok: well-formed lines parse exactly as before")
|
||||
def test_bare_number_text_dropped():
|
||||
raw = '''[[ ## subquestions ## ]]
|
||||
[{"text": "1", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before?", "depends_on": [], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
subs, _ = FloopModules().init_decompose("Who was the President before?")
|
||||
assert [s["text"] for s in subs] == ["Who held that office before?"], subs
|
||||
print("ok: bare-number texts dropped (run-I law survives typing)")
|
||||
|
||||
|
||||
# --- 2) the INIT degrade -----------------------------------------------------
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
# (subs, raw): nothing parses, but the model DID write — degrade
|
||||
return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"),
|
||||
"1 | none | OPEN\n2 | 1 | OPEN")
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
def test_garbage_degrades():
|
||||
# run-I shape: the model wrote its own line numbers, none parse to a
|
||||
# valid schema — after dspy's re-ask the AdapterParseError carries the
|
||||
# garbage; init_decompose must signal (subs=[], raw non-empty)
|
||||
garbage = "1\n2"
|
||||
_lm(garbage)
|
||||
subs, raw = FloopModules().init_decompose("Who was the President before?")
|
||||
assert subs == [] and raw and raw.strip(), (subs, raw)
|
||||
print(f"ok: schema-violating garbage -> degrade signal (raw: {raw[:20]!r})")
|
||||
|
||||
|
||||
def test_init_degrades_to_original_question():
|
||||
def test_garbage_machine_degrades_to_original():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
fm = GarbageInitModules()
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm)
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
return [], "1\n2" # garbage raw — degrade path
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [],
|
||||
"answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b,
|
||||
modules=GarbageInitModules())
|
||||
rep = run.run()
|
||||
# the machine must have routed the ORIGINAL question, not '1'/'2'
|
||||
assert rep is not None
|
||||
q1 = rep.questions[0]
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1
|
||||
assert "Pedro Sanchez" in q1[2]
|
||||
assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions
|
||||
print("ok: INIT degrade routes the original question as one OPEN subq")
|
||||
print("ok: INIT degrade routes the ORIGINAL question as one OPEN subq")
|
||||
|
||||
|
||||
# --- 3) the raw-response log --------------------------------------------------
|
||||
def test_empty_stays_atomic():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
def test_prompt_log_captures_raw_response():
|
||||
import dspy
|
||||
from dspy.utils.dummies import DummyLM
|
||||
import tempfile as tf
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
from floop.stream import RunStreams
|
||||
class AtomicModules:
|
||||
def init_decompose(self, question):
|
||||
return [], "" # truly empty — atomic
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "text"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "299792458", "source_quote": "", "confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "299792458"
|
||||
|
||||
rep = FloopRun("What is the speed of light?", b,
|
||||
modules=AtomicModules()).run()
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0"
|
||||
assert rep.questions[0][2] == "What is the speed of light?"
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
|
||||
def test_prompt_log_still_captures_raw():
|
||||
# PR-4/9 law: the RAW LM response is appended to the prompt file — now
|
||||
# for the typed path too (the engine's raw text is what gets logged)
|
||||
dspy.settings.configure(callbacks=[])
|
||||
streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=DummyLM([
|
||||
{"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"}
|
||||
]), callbacks=[cb])
|
||||
|
||||
class Sig(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField()
|
||||
|
||||
dspy.Predict(Sig)(question="Who was the President before Pedro Sanchez?")
|
||||
_lm(_GOOD)
|
||||
dspy.configure(callbacks=[cb])
|
||||
FloopModules().init_decompose("Who was the President before Pedro Sanchez?")
|
||||
f = next((streams.run_dir / "prompts").glob("01-*.txt"))
|
||||
content = f.read_text()
|
||||
assert "# RAW RESPONSE" in content, content
|
||||
assert "Who was Pedro Sanchez?" in content, content
|
||||
assert "presidency does Pedro Sanchez" in content, content
|
||||
print(f"ok: raw response appended to {f.name}")
|
||||
dspy.settings.configure(callbacks=[])
|
||||
|
||||
|
||||
|
||||
def test_empty_raw_stays_atomic():
|
||||
"""Empty RAW (the model truly returned nothing) keeps the old law: the
|
||||
goal is atomic — stop and synthesize, never fabricate a subquestion."""
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class AtomicModules(GarbageInitModules):
|
||||
def init_decompose(self, question):
|
||||
return [], ""
|
||||
|
||||
fm = AtomicModules()
|
||||
rep = FloopRun("What is the speed of light?", b, modules=fm).run()
|
||||
# atomic: INIT added no subquestions — only the goal's own Q0 remains
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0", rep.questions
|
||||
assert rep.questions[0][2] == "What is the speed of light?", rep.questions
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_parse_numbered_lines()
|
||||
test_parse_bare_number_lines_dropped()
|
||||
test_parse_enumerator_prefix()
|
||||
test_parse_happy_path_unchanged()
|
||||
test_init_degrades_to_original_question()
|
||||
test_empty_raw_stays_atomic()
|
||||
test_prompt_log_captures_raw_response()
|
||||
print("\nrobust_init tests passed")
|
||||
test_typed_init_e2e()
|
||||
test_bare_number_text_dropped()
|
||||
test_garbage_degrades()
|
||||
test_garbage_machine_degrades_to_original()
|
||||
test_empty_stays_atomic()
|
||||
test_prompt_log_still_captures_raw()
|
||||
print("\ntyped-INIT tests passed")
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Typed EXPERT + ANSWER tests (the last floop signatures): confidence is
|
||||
a closed enum; unverified is a real bool InputField.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/typed_expert.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_expert_confidence_enum():
|
||||
raw = '''[[ ## value ## ]]
|
||||
Mariano Rajoy
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
his predecessor Mariano Rajoy
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
high
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
out = FloopModules().expert_draft("Who was the President before Pedro Sanchez?",
|
||||
"knowledge", "E1: his predecessor Mariano Rajoy")
|
||||
assert out["value"] == "Mariano Rajoy" and out["confidence"] == "high", out
|
||||
print("ok: typed EXPERT parses confidence enum through the real path")
|
||||
|
||||
|
||||
def test_expert_bad_confidence_raises():
|
||||
raw = '''[[ ## value ## ]]
|
||||
42
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
certain
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().expert_draft("q", "knowledge", "")
|
||||
raise AssertionError("bad confidence parsed — enum broken")
|
||||
except AdapterParseError:
|
||||
print("ok: confidence outside the enum raises AdapterParseError")
|
||||
|
||||
|
||||
def test_answer_bool_input():
|
||||
# the bool InputField renders as a plain value in the prompt and the
|
||||
# string answer parses; synthesize passes a real bool now
|
||||
raw = '''[[ ## final_answer ## ]]
|
||||
Mariano Rajoy (E1).
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
ans = FloopModules().synthesize("Who was the President before Pedro Sanchez?",
|
||||
"E1: Mariano Rajoy", unverified=True)
|
||||
assert ans == "Mariano Rajoy (E1).", ans
|
||||
print("ok: ANSWER takes a bool unverified and parses through the real path")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_expert_confidence_enum()
|
||||
test_expert_bad_confidence_raises()
|
||||
test_answer_bool_input()
|
||||
print("\ntyped EXPERT+ANSWER tests passed")
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Typed ROUTE tests: the attendant is a closed enum — invalid picks are
|
||||
impossible by schema (a response outside the set raises AdapterParseError
|
||||
after dspy's own re-ask).
|
||||
|
||||
No network; the engine returns raw text (DummyLM bypasses the adapter —
|
||||
useless here). Run: .venv/bin/python tests/typed_route.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_route_valid_enum():
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
knowledge
|
||||
|
||||
[[ ## reason ## ]]
|
||||
A factual lookup of who held the office before.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
attendant, reason = FloopModules().route_question(
|
||||
"Who was the President before Pedro Sanchez?", "catalog", "")
|
||||
assert attendant == "knowledge", attendant
|
||||
assert reason.startswith("A factual")
|
||||
print("ok: typed ROUTE parses through the real adapter path")
|
||||
|
||||
|
||||
def test_route_invalid_attendant_raises():
|
||||
# outside the closed set -> schema violation -> AdapterParseError
|
||||
# (dspy's JSON re-ask gets the same bad value back and gives up)
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
wikipedia
|
||||
|
||||
[[ ## reason ## ]]
|
||||
It's an encyclopedia.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().route_question("q", "catalog", "")
|
||||
raise AssertionError("invalid attendant parsed — enum contract broken")
|
||||
except AdapterParseError:
|
||||
print("ok: attendant outside the enum raises AdapterParseError (schema holds)")
|
||||
|
||||
|
||||
def test_route_enum_compatibility():
|
||||
# the machine's comparisons survive typing: Attendant mixes str
|
||||
from floop.machine import EXPERT_ENGINES
|
||||
from floop.dspy_modules import Attendant
|
||||
assert Attendant.FLOOP == "floop"
|
||||
assert Attendant.KNOWLEDGE in EXPERT_ENGINES
|
||||
assert Attendant.USER not in EXPERT_ENGINES
|
||||
print("ok: enum is str-compatible — machine comparisons unchanged")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_route_valid_enum()
|
||||
test_route_invalid_attendant_raises()
|
||||
test_route_enum_compatibility()
|
||||
print("\ntyped-ROUTE tests passed")
|
||||
Reference in New Issue
Block a user