Module 12 Lesson 2: Implementing Callbacks in Chains
·LangChain

Module 12 Lesson 2: Implementing Callbacks in Chains

Connecting the Hearths. How to pass your custom handlers to models, tools, and executors to start capturing events.

Using Callbacks: Passing the Hooks

Creating a handler (Lesson 1) is only half the work. You must now tell LangChain to Use it. You can do this at the Constructor level (permanent) or the Invoke level (temporary).

1. Constructor Level (Always On)

If you want a model to always log its results, pass the callback when you initialize it.

handler = MyCustomHandler()
model = ChatOpenAI(model="gpt-4o", callbacks=[handler])

# Every call to this model will trigger the handler
model.invoke("Hi")

2. Request Level (One-Time)

If you only want to log a specific request (e.g., for a "Debug" button in your UI), pass the callback to .invoke().

# The model doesn't have a handler, but this SPECIFIC call does
model.invoke("What happened?", config={"callbacks": [handler]})

3. Propagation: How events travel

When you call a Chain, the events travel from the top to the bottom.

  1. Chain Start
  2. Prompt Start
  3. LLM Start
  4. LLM End
  5. Chain End

Important: A callback passed to a Chain will automatically "Inherit" into every model and tool inside that chain.


4. Visualizing Propagation

graph TD
    User["chain.invoke(..., config={callbacks:[H]})"] --> C[Chain Object]
    C -->|Inherit H| M[Model]
    C -->|Inherit H| T[Tool]
    M -->|Trigger| H[Handler]
    T -->|Trigger| H

5. Engineering Tip: StdOutCallbackHandler

Don't write your own logging code for basic debugging. LangChain has a built-in one called StdOutCallbackHandler. In fact, when you set verbose=True in an agent, you are actually just adding this handler automatically!

from langchain.callbacks import StdOutCallbackHandler
# This will print the internal thoughts of your chain in beautiful colors
model.invoke("Hi", config={"callbacks": [StdOutCallbackHandler()]})

Key Takeaways

  • Callbacks can be permanent (Constructor) or temporary (Config).
  • Propagation ensures your logs capture the entire nested history.
  • verbose=True is a shortcut for the StdOutCallbackHandler.
  • Passing callbacks via config is the standard for production web apps.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn