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>
This commit is contained in:
@@ -60,20 +60,93 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user