machine: robust INIT parsing + raw-response log (run I fixes)
Run I ('Who was the President before Pedro Sanchez?'): the INIT LM wrote
its own line numbers as an extra first pipe field ('1 | Who was... |
none | OPEN'), the naive parse took '1' as the subquestion text, ROUTE
classified Q1='1' as numeric, and the machine burned four calls on
garbage before luck produced the answer. Two of the fixes close the same
observability gap that hid the root cause for a day.
1. PARSER (parse_subquestions): shifts the numbered form (>=4 fields
with a bare number first) and drops any text that is a bare number —
a routable question is text, never '1'. Enumerator prefixes ('1.')
inside the text field are stripped. Well-formed lines parse exactly
as before (regression-tested).
2. INIT DEGRADE (machine): init_decompose now returns (subs, raw).
Non-empty raw that parses to nothing = model garbage — degrade to
the ORIGINAL question as one OPEN subquestion (routable, logged,
budget-safe). Empty raw keeps the old law: the question is atomic,
stop and synthesize — never fabricate a subquestion.
3. RAW RESPONSE LOG (the ask behind the ask): prompts/NN-stage.txt now
carries the exact LM response after the prompt. Run I's parsed
'OUTPUT INIT: 1\n2' could not show what the model actually wrote —
the raw text is in the file from now on; the log stays line-based.
Tests: tests/robust_init.py — the numbered form, bare-number drop,
enumerator strip, happy-path regression, the degrade, the atomic stop,
raw-response capture. Suite 59/59. Smoke: the exact run-I transcript
replayed through the real machine (DummyLM) parses to Q1/Q2 real
subquestions and answers Mariano Rajoy.
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
|
||||
|
||||
import re
|
||||
|
||||
import dspy
|
||||
|
||||
from .state import AnswerType
|
||||
@@ -84,9 +86,13 @@ class FloopModules:
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
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)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
@@ -111,17 +117,36 @@ class FloopModules:
|
||||
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]:
|
||||
""">> 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] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip().lstrip("-•* ").strip()
|
||||
if not line or "|" not in line:
|
||||
continue
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
text = parts[0]
|
||||
if not text:
|
||||
continue
|
||||
# qwen's line-number prefix: an extra first field, bare number
|
||||
if len(parts) >= 4 and _LINE_NO.fullmatch(parts[0]):
|
||||
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"
|
||||
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
||||
deps: list = []
|
||||
|
||||
+18
-1
@@ -49,6 +49,7 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
self._stack: list[str] = [] # nested module stages (innermost last)
|
||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||
|
||||
# -- dspy plumbing -------------------------------------------------------
|
||||
|
||||
@@ -78,11 +79,13 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
fn = f"{n:02d}-{label}.txt"
|
||||
pdir = streams.run_dir / "prompts"
|
||||
pdir.mkdir(exist_ok=True)
|
||||
(pdir / fn).write_text(
|
||||
f = pdir / fn
|
||||
f.write_text(
|
||||
f"# stage={label} call_seq={n} chars={chars} "
|
||||
f"tokens~{chars // 4}\n\n" + text,
|
||||
encoding="utf-8",
|
||||
)
|
||||
self._file_of[call_id] = f
|
||||
streams.log(
|
||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||
f"-> prompts/{fn}"
|
||||
@@ -95,7 +98,21 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
streams = self.streams
|
||||
label = self._stage_of.pop(call_id, "lm")
|
||||
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 "?"
|
||||
# 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:
|
||||
streams.log(f"prompt {label} done in {dur}")
|
||||
|
||||
|
||||
+14
-2
@@ -134,8 +134,20 @@ class FloopRun:
|
||||
self._charge()
|
||||
self.streams.call("INIT", f"decompose: {self.query[:80]}",
|
||||
think=self.tprefix + f"decomposing: {self.query[:100]}")
|
||||
subs = self.modules.init_decompose(self.query)
|
||||
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
||||
subs, raw = self.modules.init_decompose(self.query)
|
||||
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")
|
||||
|
||||
def _missing_round(self) -> None:
|
||||
|
||||
Reference in New Issue
Block a user