"""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/" 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//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//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", "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