Callbacks and Debugging
What you'll learn: How to use callbacks to trace, log, and debug your LangChain workflows step-by-step.
What Are Callbacks?
When you build multi-step chains using LangChain (like sequential chains or LCEL pipelines), you often need to see what's happening inside each step—not just the final output. Callbacks are hooks that let you "listen in" on your chain's execution in real-time.
Think of callbacks like a flight tracker: instead of just knowing your plane took off and landed, you see every waypoint, altitude change, and delay along the route.
Why Use Callbacks?
Complex chains involving multiple LLM calls, retrieval steps, and transformations can fail mysteriously. Callbacks help you:
- Trace execution flow: See which components run and in what order
- Log intermediate outputs: Inspect what each step produces
- Debug failures: Identify exactly where and why something broke
- Monitor performance: Track token usage and latency per step
Basic Usage
LangChain provides built-in callback handlers you pass when invoking a chain:
from langchain.callbacks import StdOutCallbackHandler
# Your chain from previous lessons
chain = prompt | llm | parser
# Add callback to see execution details
result = chain.invoke(
{"topic": "callbacks"},
config={"callbacks": [StdOutCallbackHandler()]}
)
The StdOutCallbackHandler prints events like "Chain started", "LLM input received", "LLM output generated", making your black-box chain transparent.
Common Debugging Patterns
- Use
StdOutCallbackHandlerduring development to see everything - Create custom callbacks to log to files or monitoring systems
- Check intermediate outputs when chains produce unexpected results
- Verify token counts and API calls match expectations
Key Takeaway: Callbacks transform opaque chains into observable pipelines, letting you trace execution, log intermediate steps, and quickly diagnose issues in complex workflows.