AI Hints
Home›LangChain Tutorial›Cost, Logging and Tracing
LangChain · Lesson 86 of 120

Callbacks for Logging

A record of every call.

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

In production, you want a record of every model call. When it started, what it was asked, and how many tokens it used. Callbacks let you run your own code at each of these moments, without changing the chain.

Callbacks for Logging
From the video: Callbacks for Logging
  • Record every call
  • Start, prompt, tokens
  • Callbacks hook in

A logging callback

We subclass base callback handler. On chat model start runs before the call, and on LLM end runs after it. We pass the handler in the config, so the chain itself doesn't change. Run it. Our log lines appear around the call, showing the start, and the tokens used.

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

class Logger(BaseCallbackHandler):
    def on_chat_model_start(self, serialized, messages, **kwargs):
        print("[log] model call with", len(messages[0]), "message(s)")

    def on_llm_end(self, response, **kwargs):
        usage = response.generations[0][0].message.usage_metadata
        print("[log] finished, tokens used:", usage["total_tokens"])

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
reply = model.invoke("Name one poet. Name only.", config={"callbacks": [Logger()]})
print(reply.text.strip())
Output
[log] model call with 1 message(s)
[log] finished, tokens used: 10
Rumi

Useful callback hooks

There are hooks for almost every moment. Chat model start, and LLM end, for model calls. Tool start, and tool end, for tools. Chain start, and chain end, for whole chains. And error hooks, for when anything fails.

HookRuns when
on_chat_model_starta model call begins
on_llm_enda model call ends
on_tool_start / enda tool runs
on_chain_start / enda chain runs
on_*_errorsomething fails

Summary

Callbacks run your code at each step, without changing the chain. Pass them in the config. Next, a tool that records every step for you, LangSmith.

Key takeaways
  • BaseCallbackHandler
  • config={'callbacks': [...]}
  • on_llm_end
Next up: Tracing with LangSmith — seeing every step