Author SHA1 Message Date
onibot 66e8bd4daa Merge pull request 'floop: typed ROUTE attendant (closed enum) via dspy structured output' (#12) from feature/typed-route into main 2026-10-22 15:03:54 +02:00
onibot c3d1b5d6d3 floop: typed ROUTE attendant (closed enum) via dspy structured output
ROUTE migrates to the typed-output law: the attendant is a closed enum
rendered into the prompt's JSON schema — an invalid pick is impossible
by contract (AdapterParseError after dspy's own re-ask).

- Attendant(str, Enum): knowledge logic analytic numeric floop user
  (str mixin keeps the machine's == and `in EXPERT_ENGINES` intact)
- The per-field desc now carries the routing guidance (what each
  attendant is FOR) — replacing the 'one of: ...' list in the old
  string contract
- The machine's invalid-attendant branch stays as a contract guard
- New tests/typed_route.py: enum parses through the real adapter path
  (RawEngine + cache=False), out-of-set attendant raises, str
  compatibility holds

VERIFIED: suite 13/13 green; wire test with real glm-5.3-flash routes
all three probes correctly (knowledge / numeric / knowledge).
2026-10-22 15:03:48 +02:00
onibot f953778f0a Merge pull request 'floop: typed INIT+MISSING via dspy structured output (Subquestion)' (#11) from feature/typed-init into main 2026-10-22 15:02:21 +02:00
onibot c7bd010f47 floop: typed INIT+MISSING via dspy structured output (Subquestion)
The typed-output migration starts with the machine's decomposition step:
the pipe contract ('text | deps | answer_type' lines) is gone — dspy
renders the Subquestion schema natively.

- Subquestion(BaseModel): text + depends_on: list[int] +
  answer_type: AnswerType (enum rendered into the prompt's JSON schema)
- InitSignature/MissingSignature.subquestions: list[Subquestion]
- init_decompose keeps the (subs, raw) machine contract: a
  schema-violating response raises AdapterParseError after dspy's own
  JSON re-ask; its lm_response becomes the degrade signal so the
  run-I law survives typing — the machine still routes the ORIGINAL
  question, never garbage
- bare-number texts still dropped (now in _subs_from_typed)
- parse_subquestions kept as LEGACY for tests

Tests rewritten for the REAL adapter path (RawEngine + cache=False):
DummyLM bypasses the adapter; and dspy's disk cache (~/.dspy_cache)
cross-contaminates scripted tests sharing a fake model name — both
pitfalls found while migrating.

VERIFIED:
- suite 12/12 green (robust_init rewritten: 6/6 — E2E typed parse,
  bare-number drop, garbage degrade, machine degrade, atomic case,
  raw-response prompt log)
- live E2E (ollama-cloud glm-5.3-flash): INIT renders the enum schema,
  glm returns depends_on ints + valid enums, machine dicts clean,
  full run answers Rajoy with citations. NOTE: dspy's disk cache made
  the second run's INIT a 0.2s cache hit — runs share the cache.
2026-10-22 15:02:12 +02:00
onibot 2a515795e5 Merge pull request 'knowledge: typed Fact extraction via dspy native structured output' (#10) from feature/typed-facts into main 2026-10-22 14:22:04 +02:00
3 changed files with 298 additions and 146 deletions
+69 -18
View File
@@ -7,24 +7,47 @@ 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": ""})
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 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,7 +56,11 @@ 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")
@@ -60,9 +87,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,18 +115,43 @@ 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."""
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."""
try:
pred = self.init(question=question)
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]:
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:
+144 -128
View File
@@ -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")
+85
View File
@@ -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")