Callbacks and Tracing
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/callbacks/base.py
- libs/core/langchain_core/callbacks/manager.py
- libs/core/langchain_core/tracers/base.py
- libs/core/langchain_core/tracers/langchain.py
- libs/core/langchain_core/tracers/schemas.py
- libs/core/langchain_core/runnables/config.py
- libs/core/langchain_core/runnables/base.py
The Callbacks and Tracing system in LangChain provides a mechanism for monitoring, logging, and instrumenting the execution of different components like LLMs, Chains, and Tools. It is built around a system of event handlers that are triggered at various points in a component's lifecycle (e.g., start, end, error). This allows developers to hook into the execution flow for purposes such as logging, streaming output, and sending detailed traces to platforms like LangSmith.
The system is designed to be modular and extensible. The core components are the BaseCallbackHandler, which defines the interface for handling events, and the CallbackManager, which orchestrates the invocation of these handlers. Tracing is implemented as a specialized type of callback, with BaseTracer extending BaseCallbackHandler to manage and persist structured run data.
Core Components
The callback system is fundamentally composed of handlers, which listen for events, and managers, which dispatch events to the handlers.
BaseCallbackHandler
The BaseCallbackHandler is an abstract base class that defines the interface for all callback handlers. Any class that needs to react to LangChain events must inherit from this class and implement the relevant event methods (e.g., on_llm_start, on_chain_end).
Key properties of a BaseCallbackHandler:
ignore_llm: A boolean to control whether LLM-related events are ignored.ignore_chain: A boolean to control whether Chain-related events are ignored.ignore_agent: A boolean to control whether Agent-related events are ignored.ignore_retriever: A boolean to control whether Retriever-related events are ignored.ignore_tool: A boolean to control whether Tool-related events are ignored.ignore_chat_model: A boolean to control whether Chat Model-related events are ignored.
These properties allow for fine-grained control over which events a specific handler will process.
Sources: libs/core/langchain_core/callbacks/base.py:202-243
CallbackManager
The CallbackManager is responsible for managing a collection of BaseCallbackHandler instances and dispatching events to them. It is instantiated for each run of a Runnable and ensures that all registered handlers receive the appropriate event notifications.
The manager maintains a list of handlers and inheritable_handlers. It also has a special parent_run_id to link nested runs.
The diagram below illustrates the structure of the CallbackManager and its relationship with BaseCallbackHandler.
This class diagram shows that a CallbackManager contains multiple BaseCallbackHandler instances and is responsible for invoking their event methods.
Sources: libs/core/langchain_core/callbacks/manager.py:129-150
AsyncCallbackHandler
For asynchronous operations, the AsyncCallbackHandler provides an equivalent interface to BaseCallbackHandler but with async methods (e.g., on_llm_start is an async def). This ensures that callbacks do not block the event loop in async applications. The CallbackManager is designed to work with both synchronous and asynchronous handlers seamlessly.
Sources: libs/core/langchain_core/callbacks/base.py:117-199
Callback Event Lifecycle
When a LangChain component (like an LLM or a Chain) is executed, the CallbackManager dispatches a series of events to all its registered handlers. The typical lifecycle for any given operation is on_..._start, followed by either on_..._end on success or on_..._error on failure.
The following sequence diagram shows the invocation of an LLM and the corresponding events fired by the CallbackManager.
This diagram illustrates how the CallbackManager dispatches start and end/error events to its handlers during an LLM call within a Runnable.
Sources: libs/core/langchain_core/callbacks/manager.py:195-220, libs/core/langchain_core/runnables/base.py:2311-2327
Common Callback Events
The BaseCallbackHandler interface defines methods for various events. The most common ones are listed below.
| Method Name | Triggered When... |
|---|---|
on_llm_start | An LLM run is about to start. |
on_llm_new_token | A new token is generated by a streaming LLM. |
on_llm_end | An LLM run has successfully completed. |
on_llm_error | An LLM run has failed. |
on_chain_start | A Chain run is about to start. |
on_chain_end | A Chain run has successfully completed. |
on_chain_error | A Chain run has failed. |
on_tool_start | A Tool is about to be used. |
on_tool_end | A Tool has successfully completed its run. |
on_tool_error | A Tool has failed. |
on_retriever_start | A Retriever is about to start fetching documents. |
on_retriever_end | A Retriever has finished fetching documents. |
on_retriever_error | A Retriever run has failed. |
on_text | Arbitrary text is passed to the callback. |
on_agent_action | An Agent decides on an action. |
on_agent_finish | An Agent has finished its run. |
Sources: libs/core/langchain_core/callbacks/base.py:25-114
Integration with Runnables
The callback system is deeply integrated into the Runnable interface, which is the core abstraction in LangChain. Callbacks for a specific execution are passed via the RunnableConfig object.
# libs/core/langchain_core/runnables/config.py:111-120
class RunnableConfig(TypedDict, total=False):
"""Configuration for a Runnable."""
tags: list[str]
"""Tags for this call and any sub-calls."""
metadata: dict[str, Any]
"""Metadata for this call and any sub-calls."""
callbacks: Callbacks
"""Callbacks for this call and any sub-calls."""
When a Runnable method like invoke, stream, or batch is called, a CallbackManager is created from the callbacks specified in the RunnableConfig. This manager is then used to instrument the entire execution, including any nested calls.
Sources: libs/core/langchain_core/runnables/config.py:111-120, libs/core/langchain_core/runnables/base.py:431-440
Tracing System
Tracing is a specialized application of the callback system, designed to create a structured, hierarchical log of events for observability and debugging. The BaseTracer class is the foundation of this system.
BaseTracer
BaseTracer inherits from BaseCallbackHandler and is responsible for managing the lifecycle of a Run object. A Run represents a single execution of a component (e.g., one LLM call).
The key responsibilities of a BaseTracer are:
- Trace Creation: On a
_startevent, it creates a newRunobject and adds it to a dictionary of runs, keyed by arun_id. - Trace Updates: It handles
_endand_errorevents to update the state of the correspondingRunobject (e.g., setting its end time, output, or error message). - Persistence: It defines an abstract
_persist_runmethod, which subclasses must implement to save the completedRunobject to a backend store like LangSmith.
This diagram shows the inheritance hierarchy where BaseTracer extends BaseCallbackHandler and is itself subclassed by concrete implementations like LangChainTracer.
Sources: libs/core/langchain_core/tracers/base.py:19-114
The Run Object
The Run object is a Pydantic model that captures all information about a single execution.
| Field | Type | Description |
|---|---|---|
id | UUID | Unique identifier for the run. |
name | str | The name of the object being run. |
run_type | str | The type of the object being run (e.g., "llm", "chain"). |
start_time | datetime | The time the run started. |
end_time | datetime | The time the run ended. |
extra | Dict | Extra metadata. |
error | str | Error message if the run failed. |
inputs | Dict | The inputs to the run. |
outputs | Dict | The outputs of the run. |
parent_run_id | Optional[UUID] | ID of the parent run, for nesting. |
child_runs | List[Run] | A list of child runs. |
Sources: libs/core/langchain_core/tracers/schemas.py:101-158
LangChainTracer
LangChainTracer is the concrete implementation of BaseTracer used to send traces to the LangSmith platform. It handles authenticating with the LangSmith service and uses a Client to post Run objects to the API.
Its _persist_run method implements the logic to create or update runs via HTTP requests to the LangSmith backend. It also manages a TracerSession to group related runs together.
Sources: libs/core/langchain_core/tracers/langchain.py:44-149
Conclusion
The Callbacks and Tracing system is a cornerstone of LangChain's architecture, providing essential observability into the behavior of LLM applications. By offering a simple yet powerful event-driven model, it allows developers to easily integrate logging, streaming, and advanced tracing with platforms like LangSmith. The tight integration with the Runnable interface ensures that this instrumentation is available throughout the framework, making it easier to debug, monitor, and optimize complex chains and agents.