In this guide, you’ll learn how to use callbacks in LangChain to hook into chain events—such as chain start, prompt formatting, and chain completion—to enable custom logging, monitoring, and integrations.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Table of Contents
- What Are Callbacks?
- Basic LLMChain without Callbacks
- Adding a Callback Handler
- Recap of Logging Techniques
- Links and References
What Are Callbacks?
A callback is a function that runs automatically when specific events occur in a LangChain component. With callbacks you can:- Log events to stdout, files, or cloud services
- Track prompts and responses for auditing
- Integrate with monitoring platforms (e.g., LangSmith)
- Execute custom logic on chain events
Callbacks provide fine-grained control over how your application logs, monitors, and reacts to chain activities.
Basic LLMChain without Callbacks
Start with a minimal example that formats a system and user prompt, sends it to the LLM, and returns the result:Adding a Callback Handler
Below, we register LangChain’s standard stdout handler so that chain events are logged to the console.StdOutCallbackHandler to:
- Format events as HTML or JSON
- Write logs to files or databases
- Integrate with external monitoring or alerting services
Custom callback handlers must implement the
BaseCallbackHandler interface to ensure compatibility.Recap of Logging Techniques
When building production-grade LangChain systems, consider these three approaches:| Technique | Scope | Configuration Example |
|---|---|---|
| Global debug flag | Entire langchain | export LANGCHAIN_DEBUG=true |
| Component-level verbosity | Individual chains | LLMChain(..., verbose=True) |
| Callback handlers | Fine-grained events | LLMChain(..., callbacks=[StdOutCallbackHandler()]) |