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.
More Related questions...