Skip to main content
← Back to Blog
2026-02-22 · 8 min readAI AgentsPythonAI AutomationDev ToolsUpdated Oct 29, 2026

Unmasking the Black Box: Mastering LangChain Callbacks for Debugging

A hands-on guide to LangChain callbacks for debugging. You attach StdOutCallbackHandler to a current create_agent agent, write a custom handler that logs every tool call to JSON, count tokens with get_usage_metadata_callback, learn how handlers behave in async code, and turn on LangSmith tracing. The handlers are tested with a fake model.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
36 views
Unmasking the Black Box: Mastering LangChain Callbacks for Debugging

This guide is for developers whose LangChain agent gives a wrong answer and who can't see why. You will use callbacks to watch every step: the prompt the model got, each tool call and how many tokens a run used. You will build a custom audit handler, learn how handlers behave in async code and switch on hosted tracing. The handlers are tested with a fake model, so you can check them without an API key.

Key takeaways

  • A callback handler is a class whose on_* methods LangChain calls at each step of a run. Pass handlers in config={"callbacks": [...]} so they also see every child step.
  • Write a custom handler when you need structured data, such as a JSON log of every tool call. Count tokens with get_usage_metadata_callback.
  • In async code, a sync handler runs in a thread pool, so keep it thread-safe. Errors inside handlers are only logged unless you set raise_error = True.

The black box problem

You run an agent with a few tools. It thinks for six seconds and returns the wrong answer. Did the retrieval step fail? Did the model invent a tool argument? Did a long tool result push your instructions out of focus?

Adding print() calls all over the code works once, but it is messy, and you must remove them later. A better way is to listen to the events LangChain already emits.

LangChain callbacks are hooks that LangChain calls at each stage of a run: when a model starts or ends, when a tool runs or fails, and when a chain begins. A handler subscribes to these events without changing your agent's code. It is the observer pattern, much like event listeners in JavaScript.

This post is part 12 of the LLM & LangChain Fundamentals series. In part 11 you built custom tools in LangChain. Here you watch those tools run.

The events you can hook

BaseCallbackHandler in langchain_core defines the methods. You override only the ones you need. The most useful for debugging:

Event When it fires Use it to
on_chat_model_start A chat model receives its messages See the exact prompt after templates run
on_llm_new_token A token arrives, only when streaming is on Stream text to a UI
on_llm_end The model finishes Read the reply and token usage
on_chain_start / on_chain_end A chain or graph step begins or ends Follow the flow through the agent
on_tool_start / on_tool_end A tool is called or returns Log tool names, inputs and outputs
on_tool_error A tool raises an error Catch failures the agent may hide

Each method also gets a run_id and a parent_run_id. They let you rebuild the tree of nested calls in one run.

Set up

You need Python 3.10 or newer:

pip install -U langchain langchain-openai

Quick win: StdOutCallbackHandler

The built-in StdOutCallbackHandler prints chain starts and ends, tool outputs and agent steps to the console. Create callbacks_demo.py with a small agent and one tool:

# callbacks_demo.py
import asyncio
import json
import os
import threading
import time

from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler, StdOutCallbackHandler

@tool
def power(base: float, exponent: float) -> float:
    """Raise base to the power of exponent."""
    return base**exponent

def build_agent(model):
    return create_agent(model, tools=[power])

def ask(agent, question, callbacks):
    result = agent.invoke(
        {"messages": [{"role": "user", "content": question}]},
        config={"callbacks": callbacks},
    )
    return result["messages"][-1].text

Checked against langchain@1.4.7, langchain-core@1.7.1 and langchain-openai@1.7.3, 2026-10-29.

Build the agent with agent = build_agent(model), where model is any chat model (the main block below shows a real one). Then call ask(agent, "What is 10 to the power of 2.5?", [StdOutCallbackHandler()]) and the console shows each step.

Pass handlers at call time, in config, rather than when you create the model. The RunnableConfig source in langchain-core describes callbacks as callbacks "for this call and any sub-calls", so one handler sees the whole agent run. In a test with the versions above, a handler set on the model object saw only that model's own events:

# Not this: the handler sees model calls, but never the tools or the agent steps.
# model = init_chat_model("openai:gpt-6-luna", callbacks=[StdOutCallbackHandler()])

# This: the handler sees the whole run, and you can swap it per environment.
# ask(agent, "What is 10 to the power of 2.5?", [StdOutCallbackHandler()])

The earlier version of this post used initialize_agent and load_tools. Those helpers are gone from the langchain package, and create_agent is the current way to build an agent.

Build a custom audit handler

The console output is noisy, and you can't query it later. Say you want a JSON record of every tool the agent called, with inputs, outputs, errors and timings. Subclass BaseCallbackHandler:

class AuditLogHandler(BaseCallbackHandler):
    """Records every tool call as a structured entry."""

    def __init__(self):
        self.entries = []
        self._lock = threading.Lock()  # handlers can run on worker threads

    def _add(self, **entry):
        with self._lock:
            self.entries.append({**entry, "ts": time.time()})

    def on_tool_start(self, serialized, input_str, *, run_id, inputs=None, **kwargs):
        self._add(event="tool_start", tool=serialized.get("name"), input=inputs or input_str, run_id=str(run_id))

    def on_tool_end(self, output, *, run_id, **kwargs):
        self._add(event="tool_end", output=str(getattr(output, "content", output)), run_id=str(run_id))

    def on_tool_error(self, error, *, run_id, **kwargs):
        self._add(event="tool_error", error=repr(error), run_id=str(run_id))

    def save(self, path):
        with open(path, "w") as f:
            json.dump(self.entries, f, indent=2)

Pass [AuditLogHandler()] to ask, then call save("audit.json"). The run_id links each start to its end, even when tools run in parallel. With this log you can see when an agent loops on the same tool or passes a bad argument.

Count tokens per run

To track cost, you don't need a custom handler. get_usage_metadata_callback from langchain_core.callbacks adds up token usage for every model call inside a with block:

from langchain_core.callbacks import get_usage_metadata_callback

def ask_with_usage(agent, question):
    with get_usage_metadata_callback() as usage:
        answer = ask(agent, question, callbacks=[])
    return answer, usage.usage_metadata  # {model_name: {"input_tokens": ..., "output_tokens": ...}}

The totals are grouped by model name, so a run that uses two models shows both. They come from the usage data the provider returns, so a provider that reports no usage shows nothing.

Callbacks in async code

If you serve the agent from an async app, such as a FastAPI endpoint, you call await agent.ainvoke(...). The langchain-core source shows what happens to each handler then:

  • A handler whose methods are async def (an AsyncCallbackHandler) is awaited on the event loop.
  • A plain sync handler runs in a thread pool via run_in_executor, unless it sets run_inline = True.

So a sync handler does not block your event loop. But its methods may run on other threads, which is why AuditLogHandler uses a lock. For slow I/O, such as writing to a database, use an async handler and keep it short:

class QueueHandler(AsyncCallbackHandler):
    """Pushes tool events to a queue; a separate worker does the slow writing."""

    def __init__(self, queue: asyncio.Queue):
        self.queue = queue

    async def on_tool_end(self, output, *, run_id, **kwargs):
        await self.queue.put({"run_id": str(run_id), "output": str(getattr(output, "content", output))})

async def ask_async(agent, question, queue):
    result = await agent.ainvoke(
        {"messages": [{"role": "user", "content": question}]},
        config={"callbacks": [QueueHandler(queue)]},
    )
    return result["messages"][-1].text

The handler only puts the event on a queue. A separate task or worker reads the queue and does the heavy logging, so a slow database never slows the user's reply. As a rule of thumb, a handler should finish in milliseconds.

Handler errors are silent by default

If your handler raises an exception, LangChain logs a warning and carries on, according to the callback manager source. That keeps a logging bug from crashing your app, but it can hide the bug. Set raise_error = True on the handler class while you develop it.

Run it with a real model

Keep the real model under a main guard, so tests can import the file without an API key:

if __name__ == "__main__":
    from langchain.chat_models import init_chat_model

    # Needs OPENAI_API_KEY. Check the provider's models page for current ids.
    agent = build_agent(init_chat_model(os.getenv("CHAT_MODEL", "openai:gpt-6-luna")))
    audit = AuditLogHandler()
    print(ask(agent, "What is 10 to the power of 2.5?", [StdOutCallbackHandler(), audit]))
    audit.save("audit.json")

On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model. Model ids change often, so check that page and set CHAT_MODEL to switch providers or models.

Test your handlers without an API key

A fake model that "calls" the tool lets you check the handler for free. The LangChain unit-testing docs use GenericFakeChatModel with a small subclass, so create_agent can bind tools to it:

# test_callbacks.py
import asyncio

from langchain.messages import AIMessage, ToolCall
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel

from callbacks_demo import AuditLogHandler, ask, ask_async, ask_with_usage, build_agent

class FakeToolModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

def scripted_model():
    usage = {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}
    meta = {"model_name": "fake-model"}
    return FakeToolModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="power", args={"base": 10, "exponent": 2}, id="c1")],
                  usage_metadata=usage, response_metadata=meta),
        AIMessage(content="10 to the power of 2 is 100.", usage_metadata=usage, response_metadata=meta),
    ]))

audit = AuditLogHandler()
answer = ask(build_agent(scripted_model()), "What is 10 to the power of 2?", [audit])
events = [e["event"] for e in audit.entries]
assert events == ["tool_start", "tool_end"], events
assert audit.entries[0]["tool"] == "power" and audit.entries[1]["output"] == "100.0"

answer, usage = ask_with_usage(build_agent(scripted_model()), "What is 10 to the power of 2?")
assert usage["fake-model"]["total_tokens"] == 30

queue = asyncio.Queue()
asyncio.run(ask_async(build_agent(scripted_model()), "What is 10 to the power of 2?", queue))
assert queue.qsize() == 1
print("callbacks work")

If the audit test fails, print audit.entries. An empty list usually means the handler was not passed in config.

Send traces to LangSmith or Phoenix

Local handlers suit development. In production you need traces you can search later, without logging in to a server. Hosted tracing tools plug into the same callback system.

For LangSmith, the docs list two environment variables:

export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=your-langsmith-key

With these set, LangChain sends each run as a trace, with no code changes. In Python, the tracer sends data from a background thread. The LangSmith docs explain how to wait for traces to finish before a short-lived process exits.

Arize Phoenix is an open-source option. Its docs install openinference-instrumentation-langchain and call register(auto_instrument=True) from phoenix.otel, which traces LangChain runs automatically. phoenix.otel comes from the arize-phoenix-otel package.

Under the hood, a tracer is the same idea you just built: a handler that sends events to an API instead of the console.

Frequently asked questions

How do I stream LLM tokens to a frontend?

For a create_agent agent, the LangChain streaming docs use agent.stream(..., stream_mode="messages"), which yields tokens with metadata. A custom handler with on_llm_new_token also works, but that event only fires when the model is streaming.

Can I use several callback handlers at once?

Yes. callbacks takes a list, so you can pass [StdOutCallbackHandler(), AuditLogHandler()] together, and every handler receives each event. Keep each handler independent, because one handler should not rely on another having run first.

Why are my callbacks not firing?

Check three things. First, pass the handler in config={"callbacks": [...]} at call time, so child steps see it. Second, check which model event you hooked. If your handler overrides on_chat_model_start, on_llm_start no longer fires for chat models. Without that override, langchain-core falls back to on_llm_start with the messages as text. Third, set raise_error = True, because a handler that crashes only logs a warning by default.

Should I use callbacks or LangSmith?

Use both for different jobs. Custom callbacks suit small, specific needs, such as an audit log or a cost check in your own database. LangSmith or Phoenix give you a searchable trace of every run without writing that code.

Debug with data, not guesses

When a chain acts randomly, stop rewording the prompt for a moment. Attach a handler, log the exact messages and tool calls, and read them. The bug is often in context you didn't know you were sending.

Next in the series, you will use these tools on bigger jobs in building autonomous agents for complex tasks.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. LangChain reference: BaseCallbackHandler
  2. LangChain reference: AsyncCallbackHandler
  3. langchain-core source: RunnableConfig (runnables/config.py)
  4. langchain-core source: callbacks/manager.py
  5. LangChain docs: Streaming
  6. LangChain docs: Unit testing (fake chat models)
  7. LangSmith docs: Trace LangChain agents
  8. Arize Phoenix docs: LangChain tracing
  9. arize-phoenix-otel on PyPI
  10. langchain-core source: callbacks/base.py
  11. OpenAI API: Models
  12. langchain-core on PyPI
All 14 parts in this series
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.