Files
floop/code/floop/llm.py
T
onibot b5a9403063 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.
2026-10-21 12:08:50 +02:00

188 lines
6.9 KiB
Python

"""LM configuration: dspy.LM over OpenAI-compatible endpoints (no API keys in code).
dspy 3.x routes through litellm, so model ids carry the provider prefix —
"openai/<model>" for any OpenAI-compatible endpoint (local ollama or ollama-cloud).
This module also installs the PROMPT LOG: a dspy global callback that writes
every LLM call's exact rendered prompt to runs/<ts>/prompts/NN-stage.txt and a
size line to run.log — the "what did it actually send?" channel that the log's
CALL/OUTPUT lines never carried (GAP: run G, call 8/80 — a 22k-char table
chunk sat for minutes with no way to see the prompt without rebuilding it).
"""
from __future__ import annotations
import os
import re
from pathlib import Path
import dspy
import yaml
def _load_yaml() -> dict:
cfg = Path(__file__).resolve().parent.parent / "config.yaml"
return yaml.safe_load(cfg.read_text())
def _slug_stage(text: str, maxlen: int = 24) -> str:
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return s[:maxlen].rstrip("-") or "call"
class PromptLogCallback(dspy.utils.callback.BaseCallback):
"""Writes the exact rendered prompt of every LM call to the run dir.
dspy fires on_module_start/on_module_end around each Predict's forward
(call_id DIFFERENT from the inner LM call's), so a call_id-keyed map
would lose the stage. A stack does not: the LM call runs synchronously
inside the innermost module's forward, so the top of the stack at
on_lm_start IS the stage that made the call.
Output: runs/<ts>/prompts/NN-stage.txt — NN mirrors the budget counter
(charge happens before the Predict runs), so 08-extract.txt IS the
call 8/80 of run G that hung for minutes. Plus size/duration lines in
run.log; the exact prompt is in the file, log stays line-based.
"""
def __init__(self, streams) -> None:
self.streams = streams # RunStreams or None (baseline mode)
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 -------------------------------------------------------
def on_module_start(self, call_id, instance, inputs):
sig = getattr(getattr(instance, "signature", None), "__name__", None)
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
self._stack.append(label)
def on_module_end(self, call_id, outputs, exception):
if self._stack:
self._stack.pop()
def on_lm_start(self, call_id, instance, inputs):
import time
self._starts[call_id] = time.monotonic()
label = self._stack[-1] if self._stack else "lm"
self._stage_of[call_id] = label
streams = self.streams
msgs = inputs.get("messages", []) or []
text = "\n\n".join(
f"[{m.get('role', '?')}] {m.get('content', '')}" for m in msgs
if isinstance(m, dict)
)
chars = len(text)
if streams is not None:
n = streams.bump_prompt_seq()
fn = f"{n:02d}-{label}.txt"
pdir = streams.run_dir / "prompts"
pdir.mkdir(exist_ok=True)
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}"
)
else:
print(f"[prompt] stage={label} chars={chars} tokens~{chars // 4}")
def on_lm_end(self, call_id, outputs, exception):
import time
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}")
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
_STAGE_BY_MODULE = {
"Predict": "predict",
"InitDecompose": "INIT",
"Route": "ROUTE",
"Expert": "EXPERT",
"Missing": "MISSING",
"Answer": "ANSWER",
"KnowledgeExpert": "knowledge",
"InitSignature": "INIT",
"RouteSignature": "ROUTE",
"ExpertSignature": "EXPERT",
"MissingSignature": "MISSING",
"AnswerSignature": "ANSWER",
"ExtractSignature": "EXTRACT",
"AnswerFromKG": "answer_kg",
"TranslateSignature": "TRANSLATE",
"SelectTableSignature": "SELECT_TABLE",
"VerifyCountSignature": "VERIFY_COUNT",
"SkimPromoteSignature": "PROMOTE",
}
def configure_lm() -> dict:
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
Returns the active provider settings (for provenance logs).
"""
cfg = _load_yaml()["lm"]
provider = os.environ.get("FLOOP_LM", cfg["default"])
if provider not in cfg:
raise ValueError(f"unknown FLOOP_LM provider {provider!r}; options: {list(cfg)[1:]}")
p = cfg[provider]
kwargs: dict = {
"model": f"openai/{p['model']}",
"base_url": p["base_url"],
"api_base": p["base_url"],
"max_tokens": p["max_tokens"],
"temperature": p["temperature"],
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
}
lm = dspy.LM(**kwargs)
global _ACTIVE
_ACTIVE = lm
dspy.configure(lm=lm)
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
def install_prompt_log(streams) -> None:
"""Attach the prompt log callback globally (call once per run, after
configure_lm). Idempotent: replacing streams re-installs one callback."""
global _PROMPT_LOG
if _PROMPT_LOG is not None:
_PROMPT_LOG.streams = streams
return
_PROMPT_LOG = PromptLogCallback(streams)
dspy.configure(callbacks=[_PROMPT_LOG])
_ACTIVE: "dspy.LM | None" = None
_PROMPT_LOG: "PromptLogCallback | None" = None
def active_lm() -> "dspy.LM":
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
if _ACTIVE is None:
configure_lm()
return _ACTIVE