floop: typed INIT+MISSING via dspy structured output (Subquestion) #11
+47
-14
@@ -9,22 +9,34 @@ from __future__ import annotations
|
||||
import re
|
||||
|
||||
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": ""})
|
||||
|
||||
|
||||
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...)."""
|
||||
need to answer this? Write 1-4 open subquestions in dependency order."""
|
||||
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 RouteSignature(dspy.Signature):
|
||||
@@ -60,9 +72,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):
|
||||
@@ -89,14 +100,36 @@ class FloopModules:
|
||||
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."""
|
||||
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."""
|
||||
try:
|
||||
pred = self.init(question=question)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
except AdapterParseError as e:
|
||||
return [], (e.lm_response or "unparseable response")
|
||||
return self._subs_from_typed(pred.subquestions), ""
|
||||
|
||||
@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]:
|
||||
try:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
except AdapterParseError:
|
||||
return []
|
||||
return self._subs_from_typed(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
|
||||
+129
-113
@@ -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,69 +27,91 @@ 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 -----------------------------------------------------
|
||||
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_garbage_machine_degrades_to_original():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
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")
|
||||
return [], "1\n2" # garbage raw — degrade path
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
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}"
|
||||
@@ -98,76 +124,66 @@ class GarbageInitModules:
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
|
||||
|
||||
def test_init_degrades_to_original_question():
|
||||
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)
|
||||
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")
|
||||
Reference in New Issue
Block a user