AI Hints
Home›LangChain Tutorial›Inside Chains and Practice
LangChain · Lesson 25 of 120

Seeing Inside a Chain

Callbacks.

⏱ 2 min read▶ Video at 26:22🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

When a chain gives a strange answer, you want to see what happened inside. What prompt was sent? What came back? Callbacks let you watch every step, as it runs.

Seeing Inside a Chain
From the video: Seeing Inside a Chain
  • A strange answer
  • What was sent?
  • Watch every step

A logging callback

A callback handler is a class with methods that LangChain calls at key moments. On chat model start receives the messages being sent. On LLM end receives the result. We pass our handler in the config. Run it. We see the exact prompt the template produced, and the number of output tokens, without changing the chain at all.

callbacks.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.callbacks import BaseCallbackHandler

class Logger(BaseCallbackHandler):
    def on_chat_model_start(self, serialized, messages, **kw):
        print("SENT:", messages[0][-1].content)
    def on_llm_end(self, response, **kw):
        usage = response.generations[0][0].message.usage_metadata
        print("OUTPUT TOKENS:", usage["output_tokens"])

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
chain = ChatPromptTemplate.from_template("Name a poet from {country}. Name only.") | model
reply = chain.invoke({"country": "Chile"}, config={"callbacks": [Logger()]})
print("ANSWER:", reply.text)
Output
SENT: Name a poet from Chile. Name only.
OUTPUT TOKENS: 3
ANSWER: Pablo Neruda

What callbacks are for

Callbacks are useful for logging every prompt and answer, measuring time and tokens, streaming progress to a user interface, and sending traces to monitoring tools. LangSmith, which we'll meet later, works through the same mechanism, so you get all of this without writing handlers yourself.

keyvalue
Loggingevery prompt and answer
Metricstime and tokens
UIstream progress
TracingLangSmith uses them

Summary

Callbacks hook into every step of a chain, so you can log, measure, and debug. Pass them in the config. Next, let's practise what we've built so far.

Key takeaways
  • BaseCallbackHandler
  • on_chat_model_start
  • config={'callbacks': [...]}
Next up: Practice: Review Summariser — a small chain