
Minimal LangChain example
This minimal program creates an LLM chain that formats a prompt and invokes an LLM:What are callbacks and why use them?
A callback is a function or handler that the LangChain runtime invokes at specific lifecycle events — for example when a prompt is formatted, when an LLM call starts or ends, when a chain begins or finishes, or when tools are invoked. Callbacks allow you to:- Record runtime events (console, files, or structured logs).
- Route events to observability systems (Datadog, Splunk, CloudWatch, etc.).
- Transform or post-process outputs (HTML, structured JSON).
- Aggregate metrics and implement custom telemetry.
- Debug and trace execution across chains and tools.
- Print LLM/chains events to stdout while developing.
- Save inputs/outputs into structured logs for later analysis.
- Emit metrics for latency, token usage, or error rates.
Built-in stdout handler example
This example imports and uses the built-in StdOutCallbackHandler to print lifecycle messages to the console. Note how we pass the handler via thecallbacks parameter to the chain.
Key differences and control points
Use the right mechanism depending on environment and goals. The table below summarizes the options and when to use them.
Example combining verbose and callbacks:
Creating custom handlers when you need more control
For production use cases you’ll often want to implement a custom callback handler to format events, emit structured JSON, or push telemetry to a remote service. The handler receives lifecycle events and can perform any custom action required by your app. Skeleton example (implement the methods you need):Best practices
- Use callback handlers for production logging, metrics, and observability.
- Keep stdout handlers for local development or CI debugging.
- Implement only the callback methods you need to minimize overhead.
- Ensure sensitive data (API keys, PII) is redacted before sending logs to third-party systems.
- Combine
verboseon specific components with callbacks to get granular insight without overwhelming global logging.
Callbacks are a flexible and powerful mechanism for observability and production-grade telemetry. Prefer callback handlers over global debug for routing structured logs, metrics, or formatted outputs to external systems.
Summary
- Callbacks are invoked at key lifecycle events during chain execution.
StdOutCallbackHandleris useful for quick, readable runtime output to the console.- For production use, implement or reuse custom handlers to send structured logs, metrics, or trace data to files or cloud services.
- Combine component
verboseflags with callbacks for targeted, flexible observability.
Links and references
- LangChain Documentation
- OpenAI API Documentation
- Observability and logging references: