Debugging
Relevant source files
The following files were used as context for generating this wiki page:
LangChain provides a robust set of tools for debugging and tracing the execution of language model applications. The core of this system is built upon the Runnable interface and a powerful, extensible callback system. These features allow developers to gain deep visibility into the internal workings of their chains and agents, from simple function calls to complex, multi-step sequences. By leveraging these tools, developers can inspect intermediate results, trace errors, and monitor performance.
The primary mechanisms for debugging are the global debug flag, the callback system, and specialized streaming methods on Runnable objects. The global debug flag offers a quick way to enable verbose logging for all chains. For more granular control, the callback system allows for custom handlers to be attached to specific events during a Runnable's lifecycle. Finally, methods like astream_log and astream_events provide real-time streams of execution data, which are invaluable for debugging complex, asynchronous operations. For production-grade debugging, tracing, and monitoring, LangChain integrates with LangSmith.
Global Debug Mode
The simplest way to enable debugging across the entire LangChain application is by using the global debug flag. This is controlled by the set_debug function.
Sources: libs/core/langchain_core/globals.py
set_debug()
When set_debug(True) is called, a StdOutCallbackHandler is added to the global callback manager. This causes all events in the callback system (e.g., on_llm_start, on_chain_end) to be printed to standard output, providing a verbose log of the application's execution.
# libs/core/langchain_core/globals.py:21-32
def set_debug(value: bool) -> None:
"""Set the debug flag.
When the debug flag is set to True, a lot of verbose logging will be turned on.
Args:
value: The value to set the debug flag to.
"""
global _debug
_debug = value
if value:
from langchain_core.tracers.stdout import StdOutCallbackHandler
set_handler(StdOutCallbackHandler())
This function is a quick and effective way to get a high-level overview of what a chain is doing without needing to modify its invocation code.
Sources: libs/core/langchain_core/globals.py:21-32
The Callback System
The callback system is the cornerstone of LangChain's debugging and tracing capabilities. It allows for hooking into the lifecycle of any Runnable execution. The system is managed by CallbackManager and AsyncCallbackManager.
Sources: libs/core/langchain_core/callbacks/manager.py
Callback Managers
CallbackManager and its asynchronous counterpart, AsyncCallbackManager, are responsible for dispatching events to registered callback handlers. When a Runnable is invoked, it obtains a CallbackManager from its configuration and uses it to signal key events.
The Runnable base class uses helper methods like _call_with_config and _acall_with_config to wrap executions. These methods ensure that a run_manager is created and that events are fired at the appropriate times.
This diagram shows the typical flow within a Runnable.invoke call.
This flowchart illustrates how a Runnable's execution is wrapped with start, end, and error callbacks.
Sources: libs/core/langchain_core/runnables/base.py:1010-1045, libs/core/langchain_core/callbacks/manager.py
Callback Events
The callback system defines a series of events that handlers can subscribe to. These events provide detailed information about the execution state.
| Method Name | Description |
|---|---|
on_llm_start | Called when an LLM is about to be invoked. |
on_llm_new_token | Called when a new token is generated by a streaming LLM. |
on_llm_end | Called when an LLM has finished its invocation. |
on_llm_error | Called when an LLM invocation fails. |
on_chain_start | Called when a chain or runnable is about to be invoked. |
on_chain_end | Called when a chain or runnable has finished its invocation. |
on_chain_error | Called when a chain or runnable invocation fails. |
on_tool_start | Called when a tool is about to be used. |
on_tool_end | Called when a tool has finished its execution. |
on_tool_error | Called when a tool execution fails. |
on_retriever_start | Called when a retriever is about to be invoked. |
on_retriever_end | Called when a retriever has finished its invocation. |
on_retriever_error | Called when a retriever invocation fails. |
Sources: libs/core/langchain_core/callbacks/manager.py
Custom Callback Handlers
Developers can implement custom callback handlers to perform specific actions, such as logging to a file, sending data to a monitoring service, or collecting metrics. A good example is the OpenAIInfoCallbackHandler, which tracks token usage and cost for OpenAI model calls.
This diagram shows the structure of the OpenAIInfoCallbackHandler.
This class diagram shows how OpenAIInfoCallbackHandler inherits from BaseCallbackHandler and implements the on_llm_end method to collect token and cost information.
The handler accumulates token counts and calculates the total cost upon the on_llm_end event.
Sources: libs/langchain/langchain/callbacks/openai_info.py:16-77
Streaming for Debugging
The Runnable interface provides powerful streaming methods that are not only for delivering real-time output to end-users but also for debugging.
Sources: libs/core/langchain_core/runnables/base.py
astream_log
The astream_log method streams all intermediate steps from a Runnable's execution as RunLogPatch objects. Each patch represents a diff of the run state, allowing you to reconstruct the entire execution trace. This is particularly useful for understanding the flow of complex chains.
The method can be filtered to include or exclude events based on their name, type, or tags.
# libs/core/langchain_core/runnables/base.py:593-649
async def astream_log(
self,
input: Any,
config: Optional[RunnableConfig] = None,
*,
diff: bool = True,
with_streamed_output_list: bool = True,
include_names: Optional[Sequence[str]] = None,
include_types: Optional[Sequence[str]] = None,
include_tags: Optional[Sequence[str]] = None,
exclude_names: Optional[Sequence[str]] = None,
exclude_types: Optional[Sequence[str]] = None,
exclude_tags: Optional[Sequence[str]] = None,
**kwargs: Any,
) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]:
# ... implementation ...
astream_events
The astream_events method provides a higher-level stream of StreamEvent objects. These events are structured dictionaries that are easier to parse and handle than raw log patches. They provide real-time information about the progress of a Runnable and its children.
This method is the recommended way to get a real-time, structured view of a chain's execution for debugging or building UIs.
# libs/core/langchain_core/runnables/base.py:651-828
async def astream_events(
self,
input: Any,
config: Optional[RunnableConfig] = None,
*,
version: Literal["v1", "v2"] = "v2",
# ... filter arguments ...
**kwargs: Any,
) -> AsyncIterator[StreamEvent]:
# ... implementation ...
Configuration-Based Debugging
Instead of setting a global handler, you can pass callbacks directly into the config dictionary on any invoke, stream, or batch call. This allows for targeted debugging of specific parts of an application.
from langchain_core.tracers import ConsoleCallbackHandler
# chain is any Runnable instance
chain.invoke(
{"input": "some value"},
config={'callbacks': [ConsoleCallbackHandler()]}
)
The Runnable interface also provides the with_listeners and with_alisteners methods to bind lifecycle functions directly to a runnable, creating a new runnable with the attached listeners.
Sources: libs/core/langchain_core/runnables/base.py:1270-1327
Development and Testing Practices
Effective debugging starts with good development practices. The LangChain project emphasizes the following principles which aid in creating more debuggable code:
- Unit and Integration Tests: Every new feature or bugfix must be covered by tests. Unit tests in
tests/unit_tests/should not make network calls, while integration tests intests/integration_tests/can. This separation helps isolate issues. - Code Quality: All Python code must include type hints and return types. Descriptive variable names and breaking up complex functions are encouraged. This makes the code easier to follow and reason about during debugging.
- Security Best Practices: Avoid dangerous patterns like
eval()on user input and handle exceptions properly. This prevents a class of bugs and security vulnerabilities.
Sources: CLAUDE.md, SECURITY.md
Summary
Debugging in LangChain is a multi-faceted process supported by a flexible and powerful set of tools. Developers can choose the level of detail they need, from a high-level global debug log to fine-grained, real-time event streams. The core components are the Runnable interface, which standardizes execution, and the callback system, which provides hooks into the execution lifecycle. By combining these tools with good development practices, developers can effectively trace, inspect, and resolve issues within their LLM applications.