Files
floop/code/floop/llm.py
T
onibot 0ed26d3406 floop: anonymize named entities before INIT (his design)
The model was using its own knowledge of the people in the question
to decide decomposition (his qwen collapsed Pedro Sanchez to ONE
subquestion: 'the question is nearly atomic because I know who he
is'). Structural fix: INIT sees the question's SHAPE, not identity.

- EntityMaskSignature (typed NER proposal): entities as list[NamedEntity]
  (name verbatim + kind) — the typed-output law, no string parsing
- apply_mask/restore_mask: DETERMINISTIC code (LLMs propose, code
  applies): longest names first, one placeholder per surface text,
  typed prefixes PERSON_1/ORGANIZATION_1/..., restore longest-first
  (PERSON_10 never eaten by PERSON_1)
- init_decompose: mask -> INIT -> restore in each returned subquestion;
  MASK finding no entities OR dying (AdapterParseError) -> passthrough,
  never a dead run
- MASK stage in the prompt log (prompts/01-MASK.txt)

VERIFIED: tests/anonymize.py 4/4 (deterministic apply/restore, E2E
mask+restore, no-entity passthrough, mask-death passthrough); suite
15/15. Live E2E (glm-5.3-flash): MASK found exactly Pedro Sanchez
(reasoning explicitly excluded 'President' as a role, not entity);
INIT saw 'Who was the President before PERSON_1?' and returned FOUR
subquestions (identity, office, term start, predecessor) — the shape
split he wanted, plus a 'who is PERSON_1' question; run answers Rajoy
correctly (E1-E4).

OPEN (his question pending): the model now asks WHO the placeholder
is, spending one call per run. Options: (a) keep, (b) desc note that
placeholders are known entities, (c) give INIT the masked question PLUS
the original as context. Not decided — he answers when back.
2026-10-22 16:48:41 +02:00

220 lines
8.8 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.
RE-ASK METER (run L): dspy's chat adapter, on a parse failure, re-fires
the SAME module's LM call through its JSON fallback — an extra wire call
the budget counter never charged (9/80 logged, 10 on the wire, the
second burning 340s of GPU). The meter sees them (same module depth in
the stack twice), charges the budget via an optional meter hook, and
logs the line — dspy's BEHAVIOUR is untouched (his call: the fallback
stays; it is future self-improvement signal, not a bug to fix).
"""
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
self.reasks = 0 # LM calls the budget did not charge
self.meter = None # callable(str stage) -> None; budget charge
# -- 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)
self._fresh_forward = True # this forward's first LM call is not a re-ask
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)
# RE-ASK METER: a second LM call with NO new module forward between
# them is dspy's adapter fallback re-firing inside the same Predict
# (ChatAdapter catches AdapterParseError and re-calls via JSONAdapter)
# — an extra wire call the budget did not charge. Consecutive SAME-
# stage calls from DIFFERENT forwards (the ablation rounds) are NOT
# re-asks: each round opens its own module.
fresh = getattr(self, "_fresh_forward", False)
self._fresh_forward = False
self._lm_seen = getattr(self, "_lm_seen", 0) + 1
reask = self._lm_seen > 1 and not fresh
if reask:
self.reasks += 1
if streams is not None:
streams.log(f"re-ask detected: stage={label} "
f"(adapter parse-failure fallback, charged to budget)")
if self.meter is not None:
try:
self.meter(label)
except Exception: # noqa: BLE001 — metering must never kill a run
pass
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",
"EntityMaskSignature": "MASK",
"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