Learn to use callbacks in LangChain for custom logging, monitoring, and integrations during chain events.
In this guide, you’ll learn how to use callbacks in LangChain to hook into chain events—such as chain start, prompt formatting, and chain completion—to enable custom logging, monitoring, and integrations.
Start with a minimal example that formats a system and user prompt, sends it to the LLM, and returns the result:
Copy
Ask AI
from langchain.prompts import ChatPromptTemplatefrom langchain_openai import ChatOpenAIfrom langchain.chains import LLMChainllm = ChatOpenAI()prompt = ChatPromptTemplate.from_messages([ ("system", "You are a {subject} teacher"), ("human", "Tell me about {concept}")])chain = LLMChain(llm=llm, prompt=prompt)response = chain.invoke({"subject": "physics", "concept": "galaxy"})print(response)
Example response:
Copy
Ask AI
{ "subject": "physics", "concept": "galaxy", "text": "A galaxy is a vast system of stars, gas, dust, and dark matter bound together by gravity. It is the basic building block of the universe..."}
Below, we register LangChain’s standard stdout handler so that chain events are logged to the console.
Copy
Ask AI
from langchain.prompts import ChatPromptTemplatefrom langchain_openai import ChatOpenAIfrom langchain.chains import LLMChainfrom langchain.callbacks import StdOutCallbackHandler# 1. Create the callback handlerhandler = StdOutCallbackHandler()# 2. Initialize the LLM and promptllm = ChatOpenAI()prompt = ChatPromptTemplate.from_messages([ ("system", "You are a {subject} teacher"), ("human", "Tell me about {concept}")])# 3. Register the handler with the chainchain = LLMChain( llm=llm, prompt=prompt, callbacks=[handler])# 4. Invoke the chain; events will be printed to stdoutresponse = chain.invoke({"subject": "physics", "concept": "galaxy"})print(response)
Example console output:
Copy
Ask AI
> Entering new LLMChain chain...Prompt after formatting:System: You are a physics teacherHuman: Tell me about galaxy> Finished chain.{'subject': 'physics', 'concept': 'galaxy', 'text': "A galaxy is a massive, gravitationally bound system..."}
With callbacks, you can replace or extend StdOutCallbackHandler to:
Format events as HTML or JSON
Write logs to files or databases
Integrate with external monitoring or alerting services
Custom callback handlers must implement the BaseCallbackHandler interface to ensure compatibility.