What is Callback in Langchain: Explanation and Example
callback is a function or object that runs automatically during or after a process, like when a language model generates text. It helps you track progress, log events, or modify behavior without changing the main code flow.How It Works
Think of a callback in Langchain like a helper that listens quietly while your main program runs. When something important happens, like the language model finishing a task, the callback wakes up and does its job, such as logging the result or updating a progress bar.
This is similar to how a friend might remind you when a timer goes off while you are cooking. You don’t have to stop what you’re doing; the callback just reacts when needed. In Langchain, callbacks let you add extra features like tracking or debugging without changing the core logic.
Example
This example shows how to use a simple callback in Langchain to print messages when the language model starts and finishes generating text.
from langchain.callbacks.base import BaseCallbackHandler from langchain.llms import OpenAI class PrintCallback(BaseCallbackHandler): def on_llm_start(self, serialized, prompts, **kwargs): print("LLM started generating text...") def on_llm_end(self, response, **kwargs): print("LLM finished generating text.") llm = OpenAI(callbacks=[PrintCallback()]) result = llm("Say hello in a friendly way.") print("Output:", result)
When to Use
Use callbacks in Langchain when you want to monitor or react to events during language model operations without interrupting the main process. For example, you can log inputs and outputs for debugging, update user interfaces with progress, or collect usage statistics.
Callbacks are helpful in real-world applications like chatbots, where you want to show typing indicators or save conversation history automatically. They keep your code clean by separating core logic from side tasks.
Key Points
- Callbacks run automatically at specific events in Langchain processes.
- They help track progress, log data, or modify behavior without changing main code.
- Callbacks keep your code organized by separating side tasks from core logic.
- They are useful for debugging, UI updates, and analytics in language model applications.