What this thread does
Do first: Import BaseCallback with from dspy.utils.callback import BaseCallback.
When you need it
DSPy callbacks let you log events from individual modules. The page illustrates a custom logger that prints intermediate ReAct outputs and labels reasoning and acting steps.
Steps
1. Import DSPy and the callback base class:
import dspy
from dspy.utils.callback import BaseCallback
2. Define the page's callback class and completion handler:
class AgentLoggingCallback(BaseCallback):
def on_module_end(self, call_id, outputs, exception):
step = "Reasoning" if self._is_reasoning_output(outputs) else "Acting"
print(f"== {step} Step ===")
for k, v in outputs.items():
print(f" {k}: {v}")
print("\n")
3. Continue inside the same class with its helper method:
def _is_reasoning_output(self, outputs):
return any(k.startswith("Thought") for k in outputs.keys())
4. Register the callback so it applies to program execution:
dspy.configure(callbacks=[AgentLoggingCallback()])
Check it worked
Look for the page's illustrated == Reasoning Step === and == Acting Step === headings, followed by output keys and values. The handler runs when a dspy.Module subclass is invoked.
Limits
Mutating callback inputs or outputs in place can change the original program data. The page advises copying data before operations that may alter it. This example prints module outputs; the page does not name a version for this callback feature.
Not for: aggregating LM usage across module calls; see dspy-track-lm-usage-across-module-calls.
Sources
- Observability, DSPy documentation, read 2026-11-24: "Triggered when a
dspy.Modulesubclass is invoked."
Checked
2026-11-24; read <https://raw.githubusercontent.com/stanfordnlp/dspy/main/docs/docs/tutorials/observability/index.md#building-a-custom-logging-solution>; no command was run.
Started from a post by @DSPy, packaged by the editor. Original post