Files
floop/code/floop/llm.py
T
onibotandClaude 1af308ae60 feat: named inputs/outputs in traces + clickable prompts + expert names
Owner's 27/10 review of the OTel export, four asks, all landed:

1. NAMED IN/OUT PER FUNCTION: fn.done events (fn, in, out) at the
   knowledge pipeline's main functions - search (in.query -> out.titles),
   fetch, skim, compose, chunk_gate, serve_set, list_ingest, harvest,
   promote, check, judge - rendered as spans with in.<arg>/out.<arg>
   attributes. "wiki search ('Pedro date take'): [...]" is now
   knowledge.search with in.query and out.titles as data.
2. SIGNATURE IN/OUT: the dspy prompt-log callback emits sig.start/sig.done
   - the typed fields of every dspy call (in.question, out.entities,
   out.facts...). The LLM span and the sig span are one node.
3. CLICKABLE PROMPT: every LLM span carries a child 'prompt' span with
   the exact prompt + raw response read from prompts/NN-stage.txt at
   export time - retroactive for old runs (the Pedro run re-exports with
   128 prompt children).
4. EXPERT NAMES: EXPERT comp spans carry expert= (EXPERT knowledge);
   nested spans prefix with the expert (knowledge.search,
   knowledge.state, knowledge.TranslateToDSL); each expert exports its
   spans under its own OTel service so Jaeger groups by component.

Live-verified end to end: smoke run (glm-5.3-flash) exported while
running - MASK shows in.question -> out.entities [{France, PLACE}],
EXPERT knowledge nests knowledge.TranslateToDSL under service
knowledge; read back via Jaeger's own API. Suite: traces 7/7, all
floop + knowledge test files green (guards/value_clean caught two bugs
in the new emissions before commit: a wrong-scope variable and a
use-before-define; _rec now reads getattr(streams) so __new__ test
fakes survive).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-27 14:27:56 +01:00

400 lines
17 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._seq_of: dict[str, int] = {} # lm call_id -> prompt seq (budget mirror)
self._fname_of: dict[str, str] = {} # lm call_id -> prompt file name
self._sig_call_id: str | None = None # innermost module call_id (sig events)
self._sig_stage_of: dict[str, str] = {} # module call_id -> stage label
self.reasks = 0 # LM calls the budget did not charge
self.meter = None # callable(str stage) -> None; budget charge
# -- dspy plumbing -------------------------------------------------------
@staticmethod
def _jsonable(v) -> object:
"""Signature field values -> JSON-safe primitives (recorder law:
small structured payloads; the exact prompt lives in the file)."""
try:
import pydantic
if isinstance(v, pydantic.BaseModel):
return v.model_dump()
except Exception: # noqa: BLE001 — best effort, never raises
pass
if isinstance(v, (str, int, float, bool)) or v is None:
return v
if isinstance(v, (list, tuple)):
return [PromptLogCallback._jsonable(x) for x in v]
if isinstance(v, dict):
return {str(k): PromptLogCallback._jsonable(x) for k, x in v.items()}
return str(v)
def _emit_sig_start(self, call_id: str, instance, inputs) -> None:
"""Signature inputs (owner 27/10): what the call receives, named.
dspy 3.4 hands the raw *args/**kwargs — the named form is inside
the kwargs repr; unknown shapes degrade to the repr itself
(honest, never a crash)."""
streams = self.streams
if streams is None:
return
try:
import ast
kw = (inputs or {}).get("kwargs", "")
named = ast.literal_eval(kw) if isinstance(kw, str) and kw.strip() \
else dict(kw or {})
if not isinstance(named, dict):
named = {"input": self._jsonable(inputs)}
except Exception: # noqa: BLE001 — observability never breaks a call
named = {"input": str(inputs)[:500]}
sig = getattr(getattr(instance, "signature", None), "__name__", None)
streams.recorder.emit("sig.start", stage=sig or "Predict",
call_id=call_id,
**{f"in.{k}": self._jsonable(v)
for k, v in named.items()})
def _emit_sig_done(self, call_id: str, outputs, exception) -> None:
"""Signature outputs (owner 27/10): the typed fields the call
produced, named — the Prediction's own attributes (only ones the
module's signature declares; dspy appends 'reasoning' internals)."""
streams = self.streams
if streams is None:
return
try:
named: dict[str, object] = {}
if isinstance(outputs, dict):
named = {k: self._jsonable(v) for k, v in outputs.items()
if k not in ("reasoning", "reasoning_model_response")}
elif outputs is not None:
for k in (getattr(outputs, "_store", None) or {}):
if k in ("reasoning", "reasoning_model_response"):
continue
named[k] = self._jsonable(outputs[k])
streams.recorder.emit("sig.done", stage=self._sig_stage_of.pop(call_id, "?"),
call_id=call_id,
exception=repr(exception)[:120] if exception else None,
**{f"out.{k}": v for k, v in named.items()})
except Exception: # noqa: BLE001 — observability never breaks a call
pass
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._sig_call_id = call_id
self._sig_stage_of[call_id] = label
self._fresh_forward = True # this forward's first LM call is not a re-ask
self._emit_sig_start(call_id, instance, inputs)
def on_module_end(self, call_id, outputs, exception):
if self._stack:
self._stack.pop()
if call_id == self._sig_call_id:
self._emit_sig_done(call_id, outputs, exception)
self._sig_call_id = None
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
self._seq_of[call_id] = n
self._fname_of[call_id] = fn
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)
n = self._seq_of.pop(call_id, None)
fn = self._fname_of.pop(call_id, None)
dur_s = (time.monotonic() - start) if start is not None else None
dur = f"{dur_s:.1f}s" if dur_s 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}")
try:
streams.recorder.emit(
"llm.done", stage=label, call_seq=n,
dur_s=(round(dur_s, 2) if dur_s is not None else None),
file=f"prompts/{fn}" if fn is not None else None,
exception=repr(exception)[:120] if exception else None)
except Exception: # noqa: BLE001
pass
# 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",
"ExtractClaims": "CLAIMS",
"TypeClaim": "TYPE",
"AnswerFromKG": "answer_kg",
"SelectTableSignature": "SELECT_TABLE",
"VerifyCountSignature": "VERIFY_COUNT",
"SkimPromoteSignature": "PROMOTE",
"SkimTableSignature": "SKIM_TABLE",
}
def configure_lm(no_cache: bool = False) -> dict:
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
no_cache=True builds the LM with dspy's response cache DISABLED for this
process (his ruling 25/10: the cache is caching doing its job — the
default stays cache=True; the flag exists for A/B and freshness testing
so a repeated question is a real run, not a byte-identical replay).
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"),
}
# transport ceiling (fix: EXTRACT hangs on slow local models): the
# config's read_timeout_s becomes the lm15 Timeouts(read=) via the
# `timeout=` kwarg (a plain number of seconds bounds read/write/
# pool — dspy 3.4.1 execution.py routes it as RouterConfig timeouts;
# the default is 600s, the wall your 2407.3s EXTRACT call died on,
# 4 attempts x 600s + backoff). num_retries feeds dspy's retry loop
# (LMTransportError IS retryable — execution.py is_retryable_lm_error).
# Unset -> dspy defaults (600s / retries 3), nothing invented.
if p.get("read_timeout_s"):
kwargs["timeout"] = float(p["read_timeout_s"])
if p.get("num_retries") is not None:
kwargs["num_retries"] = int(p["num_retries"])
if no_cache:
kwargs["cache"] = False
lm = dspy.LM(**kwargs)
global _ACTIVE
_ACTIVE = lm
dspy.configure(lm=lm)
return {"provider": provider, "model": p["model"], "base_url": p["base_url"],
"read_timeout_s": p.get("read_timeout_s"),
"num_retries": p.get("num_retries")}
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
# per-signature dedicated LMs (lm[<SigName>] blocks with a model override),
# keyed f"{provider}:{model}" — ONE LM per provider+model, built once
_SIGNATURE_LMS: dict[str, "dspy.LM"] = {}
def _signature_settings(sig) -> dict:
"""The lm[<SignatureName>] block for a signature, or {} when absent."""
name = getattr(sig, "__name__", None) or str(sig)
return _load_yaml().get(f"lm[{name}]") or {}
def signature_overrides() -> dict[str, dict]:
"""Every lm[<SigName>] block in config.yaml, by signature name.
For the run.log provenance line: which stages run with dedicated
settings today, visible at startup.
"""
return {k[3:-1]: v for k, v in _load_yaml().items()
if k.startswith("lm[") and k.endswith("]")}
def predict(signature, **extra_config):
"""dspy.Predict construction honoring per-signature config blocks.
A `lm[<SignatureName>]:` block in config.yaml (sibling of `lm:`) may
carry: provider (which provider block to inherit base_url + transport
ceiling from — defaults to the active provider), model, max_tokens,
temperature, and any other dspy.LM kwarg. Settings WITHOUT a model
travel as per-call lm_kwargs through Predict's own config (dspy 3.4.1
merges self.config into the request — verified on the wire); a model:
override builds ONE dedicated cached dspy.LM (same provider ceiling,
its own model id) bound to the Predict instance. No block -> a plain
dspy.Predict with the run defaults, untouched.
This is the ONE construction door: swapping dspy.Predict(...) for
predict(...) here means a signature's model/settings change by
editing config alone — no call-site ifs, now or ever after.
"""
import dspy
block = _signature_settings(signature)
if not block:
return dspy.Predict(signature, **extra_config)
cfg = _load_yaml()["lm"]
provider = block.get("provider") or cfg.get("default")
base = cfg[provider]
settings = {k: v for k, v in block.items() if k != "provider"}
model = settings.pop("model", None)
if model is None:
return dspy.Predict(signature, **settings, **extra_config)
key = f"{provider}:{model}"
if key not in _SIGNATURE_LMS:
kwargs: dict = {
"model": f"openai/{model}",
"base_url": base["base_url"],
"api_base": base["base_url"],
"max_tokens": settings.pop("max_tokens", base["max_tokens"]),
"temperature": settings.pop("temperature", base["temperature"]),
"api_key": os.environ.get(base.get("api_key_env", ""), "empty"),
}
if base.get("read_timeout_s"):
kwargs["timeout"] = float(base["read_timeout_s"])
if base.get("num_retries") is not None:
kwargs["num_retries"] = int(base["num_retries"])
kwargs.update(settings) # any other block keys pass through
_SIGNATURE_LMS[key] = dspy.LM(**kwargs)
inst = dspy.Predict(signature, **extra_config)
inst.lm = _SIGNATURE_LMS[key]
return inst
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