AI / LangGraph LangChain Interview questions
How do callbacks work in LangChain?
Callbacks in LangChain are hooks that fire at specific lifecycle events during chain, model, and agent execution. You implement a BaseCallbackHandler subclass and override only the methods you care about. Each method receives context about what just happened — which model was called, what the prompt was, what the response was, and how long it took.
Key callback methods (all have async equivalents prefixed with a):
on_llm_start(serialized, prompts)— fired before an LLM callon_llm_end(response)— fired after an LLM call completeson_chain_start(serialized, inputs)— fired when a chain beginson_chain_end(outputs)— fired when a chain finisheson_tool_start(serialized, input_str)— fired before a tool executeson_tool_end(output)— fired after a tool returnson_agent_action(action)— fired each time an agent decides to use a tool
from langchain_core.callbacks import BaseCallbackHandler
class TokenLogger(BaseCallbackHandler):
def on_llm_end(self, response, **kwargs):
usage = response.llm_output.get('token_usage', {})
print(f"Tokens used: {usage}")
chain.invoke({"input": "hello"}, config={"callbacks": [TokenLogger()]})
Callbacks can be attached per-invocation via config={"callbacks": [...]}, per-component via constructor arguments, or globally with set_global_handler(). LangSmith tracing itself is implemented as a callback handler.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
