Merge pull request 'machine: robust INIT parsing + raw-response log (run I)' (#6) from feature/robust-init into main
This commit was merged in pull request #6.
This commit is contained in:
@@ -6,6 +6,8 @@ Every module's docstring is the draft prompt — kept minimal on purpose.
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
import dspy
|
import dspy
|
||||||
|
|
||||||
from .state import AnswerType
|
from .state import AnswerType
|
||||||
@@ -84,9 +86,13 @@ class FloopModules:
|
|||||||
self.missing = dspy.Predict(MissingSignature)
|
self.missing = dspy.Predict(MissingSignature)
|
||||||
self.answer = dspy.Predict(AnswerSignature)
|
self.answer = dspy.Predict(AnswerSignature)
|
||||||
|
|
||||||
def init_decompose(self, question: str) -> list[dict]:
|
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)
|
pred = self.init(question=question)
|
||||||
return parse_subquestions(pred.subquestions)
|
raw = pred.subquestions or ""
|
||||||
|
return parse_subquestions(raw), raw
|
||||||
|
|
||||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||||
pred = self.missing(goal=goal, evidence=evidence)
|
pred = self.missing(goal=goal, evidence=evidence)
|
||||||
@@ -111,17 +117,36 @@ class FloopModules:
|
|||||||
return pred.final_answer.strip()
|
return pred.final_answer.strip()
|
||||||
|
|
||||||
|
|
||||||
|
_LINE_NO = re.compile(r"\d{1,2}[.)]?")
|
||||||
|
_ENUM = re.compile(r"^\d{1,2}[.)]?\s*[-–:]?\s+")
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_qtext(t: str) -> str:
|
||||||
|
"""Strip a leading enumerator ('1.', '2)', '3 -') from a subquestion."""
|
||||||
|
return _ENUM.sub("", t.strip()).strip()
|
||||||
|
|
||||||
|
|
||||||
def parse_subquestions(raw: str) -> list[dict]:
|
def parse_subquestions(raw: str) -> list[dict]:
|
||||||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type."""
|
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type.
|
||||||
|
|
||||||
|
The piped format is the contract; models still decorate it (run I):
|
||||||
|
qwen wrote its own line numbers as an extra first pipe field
|
||||||
|
('1 | Who was the President before Pedro Sanchez? | none | OPEN') and
|
||||||
|
the naive parse took '1' as the text — Q1 routed as 'numeric' on the
|
||||||
|
literal question '1'. The parser now shifts the numbered form and
|
||||||
|
drops any field that is a bare number: a routable question is text."""
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
for line in (raw or "").strip().splitlines():
|
for line in (raw or "").strip().splitlines():
|
||||||
line = line.strip().lstrip("-•* ").strip()
|
line = line.strip().lstrip("-•* ").strip()
|
||||||
if not line or "|" not in line:
|
if not line or "|" not in line:
|
||||||
continue
|
continue
|
||||||
parts = [p.strip() for p in line.split("|")]
|
parts = [p.strip() for p in line.split("|")]
|
||||||
text = parts[0]
|
# qwen's line-number prefix: an extra first field, bare number
|
||||||
if not text:
|
if len(parts) >= 4 and _LINE_NO.fullmatch(parts[0]):
|
||||||
continue
|
parts = parts[1:]
|
||||||
|
text = _clean_qtext(parts[0])
|
||||||
|
if not text or _LINE_NO.fullmatch(text):
|
||||||
|
continue # a number is a line number, never a question
|
||||||
deps_raw = parts[1].lower() if len(parts) > 1 else "none"
|
deps_raw = parts[1].lower() if len(parts) > 1 else "none"
|
||||||
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
||||||
deps: list = []
|
deps: list = []
|
||||||
|
|||||||
+18
-1
@@ -49,6 +49,7 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
self._stack: list[str] = [] # nested module stages (innermost last)
|
self._stack: list[str] = [] # nested module stages (innermost last)
|
||||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||||
|
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||||
|
|
||||||
# -- dspy plumbing -------------------------------------------------------
|
# -- dspy plumbing -------------------------------------------------------
|
||||||
|
|
||||||
@@ -78,11 +79,13 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
fn = f"{n:02d}-{label}.txt"
|
fn = f"{n:02d}-{label}.txt"
|
||||||
pdir = streams.run_dir / "prompts"
|
pdir = streams.run_dir / "prompts"
|
||||||
pdir.mkdir(exist_ok=True)
|
pdir.mkdir(exist_ok=True)
|
||||||
(pdir / fn).write_text(
|
f = pdir / fn
|
||||||
|
f.write_text(
|
||||||
f"# stage={label} call_seq={n} chars={chars} "
|
f"# stage={label} call_seq={n} chars={chars} "
|
||||||
f"tokens~{chars // 4}\n\n" + text,
|
f"tokens~{chars // 4}\n\n" + text,
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
self._file_of[call_id] = f
|
||||||
streams.log(
|
streams.log(
|
||||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||||
f"-> prompts/{fn}"
|
f"-> prompts/{fn}"
|
||||||
@@ -95,7 +98,21 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
streams = self.streams
|
streams = self.streams
|
||||||
label = self._stage_of.pop(call_id, "lm")
|
label = self._stage_of.pop(call_id, "lm")
|
||||||
start = self._starts.pop(call_id, None)
|
start = self._starts.pop(call_id, None)
|
||||||
|
f = self._file_of.pop(call_id, None)
|
||||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
||||||
|
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
||||||
|
# the parsed OUTPUT can lie by omission (run I)
|
||||||
|
if f is not None:
|
||||||
|
raw = ""
|
||||||
|
if isinstance(outputs, list):
|
||||||
|
raw = "\n".join(str(o) for o in outputs)
|
||||||
|
elif outputs is not None:
|
||||||
|
raw = str(outputs)
|
||||||
|
with f.open("a", encoding="utf-8") as fh:
|
||||||
|
fh.write(
|
||||||
|
f"\n\n# RAW RESPONSE (after {dur}"
|
||||||
|
+ (f", exception={exception!r}" if exception else "")
|
||||||
|
+ ")\n" + (raw or "(empty)"))
|
||||||
if streams is not None:
|
if streams is not None:
|
||||||
streams.log(f"prompt {label} done in {dur}")
|
streams.log(f"prompt {label} done in {dur}")
|
||||||
|
|
||||||
|
|||||||
+14
-2
@@ -134,8 +134,20 @@ class FloopRun:
|
|||||||
self._charge()
|
self._charge()
|
||||||
self.streams.call("INIT", f"decompose: {self.query[:80]}",
|
self.streams.call("INIT", f"decompose: {self.query[:80]}",
|
||||||
think=self.tprefix + f"decomposing: {self.query[:100]}")
|
think=self.tprefix + f"decomposing: {self.query[:100]}")
|
||||||
subs = self.modules.init_decompose(self.query)
|
subs, raw = self.modules.init_decompose(self.query)
|
||||||
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
if not subs and (raw or "").strip():
|
||||||
|
# DEGRADE (run I): the model WROTE subquestions but none parsed
|
||||||
|
# (its numbered format beat the parser) — route the ORIGINAL
|
||||||
|
# question as one OPEN subquestion instead of routing garbage
|
||||||
|
# like a bare '1'. Deterministic, logged, budget-safe. The
|
||||||
|
# atomic case (empty raw) keeps the old stop-and-synthesize.
|
||||||
|
self.streams.output(
|
||||||
|
"INIT", f"(no parseable subquestions from {len(raw)} chars "
|
||||||
|
f"— degrading to the original question)", think=True)
|
||||||
|
subs = [{"text": self.query, "deps": [],
|
||||||
|
"answer_type": AnswerType.OPEN}]
|
||||||
|
else:
|
||||||
|
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
||||||
self._add_questions(subs, reason="init")
|
self._add_questions(subs, reason="init")
|
||||||
|
|
||||||
def _missing_round(self) -> None:
|
def _missing_round(self) -> None:
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ class FakeModules:
|
|||||||
|
|
||||||
def init_decompose(self, question):
|
def init_decompose(self, question):
|
||||||
self.calls.append(f"init:{question[:30]}")
|
self.calls.append(f"init:{question[:30]}")
|
||||||
return list(self.init_subs)
|
return list(self.init_subs), "" # (subs, raw) — atomic when empty
|
||||||
|
|
||||||
def missing_decompose(self, goal, evidence):
|
def missing_decompose(self, goal, evidence):
|
||||||
self.calls.append("missing")
|
self.calls.append("missing")
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I).
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.dspy_modules import parse_subquestions
|
||||||
|
from floop.state import AnswerType, Budget
|
||||||
|
from floop.machine import FloopRun
|
||||||
|
|
||||||
|
|
||||||
|
# --- 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)
|
||||||
|
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[1]["deps"] == [1]
|
||||||
|
print("ok: enumerator prefixes stripped from the text field")
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
|
# --- 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_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)
|
||||||
|
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 "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")
|
||||||
|
|
||||||
|
|
||||||
|
# --- 3) the raw-response log --------------------------------------------------
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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?")
|
||||||
|
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
|
||||||
|
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")
|
||||||
Reference in New Issue
Block a user