LangChain Integration Guide
Use LangChain callbacks to automatically report token usage and costs to OpsViz.
How it works in 30 seconds
- 1.Create an agent in OpsViz → get your webhook URL (10 seconds)
- 2.Add one step to your LangChain workflow → paste the URL (2 minutes)
- 3.See costs, tokens, and alerts in real time (instantly)
Privacy note: OpsViz receives only operational metadata — event type, token counts, model name, cost, and duration. Your prompts, responses, user data, and AI provider credentials are never sent to OpsViz.
Set up with AI — copy and paste
The fastest way to add OpsViz monitoring is to paste this prompt into your AI coding assistant. It sets everything up automatically.
Using Claude Code or ChatGPT
Paste this prompt into Claude Code or ChatGPT with your LangChain code attached:
I have a LangChain application and want to add OpsViz monitoring to track costs and token usage. Add a callback handler that fires a non-blocking HTTP POST to [WEBHOOK_URL] after each LLM call completes. The payload should include: event_type ("task.completed" or "task.failed"), agent_name (a label for this app), model name from the response, token counts from llm_output.token_usage, calculated cost_usd, and duration_ms. Use langchain_core.callbacks.BaseCallbackHandler. Show me the complete callback class and how to attach it.Prerequisites
- LangChain installed (langchain-core>=0.1.0)
- An OpsViz account with an agent created
- Your OpsViz webhook URL
1
Create an OpsViz callback handler
import requests
import time
from langchain_core.callbacks import BaseCallbackHandler
class OpsVizCallback(BaseCallbackHandler):
def __init__(self, webhook_url: str, agent_name: str = "LangChain App"):
self.webhook_url = webhook_url
self.agent_name = agent_name
self.start_time = None
def on_llm_start(self, serialized, prompts, **kwargs):
self.start_time = time.time()
def on_llm_end(self, response, **kwargs):
duration_ms = int((time.time() - self.start_time) * 1000)
usage = response.llm_output.get("token_usage", {})
model = response.llm_output.get("model_name", "unknown")
try:
requests.post(self.webhook_url, json={
"event_type": "task.completed",
"agent_name": self.agent_name,
"model": model,
"tokens_in": usage.get("prompt_tokens"),
"tokens_out": usage.get("completion_tokens"),
"duration_ms": duration_ms,
}, timeout=5)
except Exception:
pass # Never let monitoring block your agent
def on_llm_error(self, error, **kwargs):
try:
requests.post(self.webhook_url, json={
"event_type": "task.failed",
"agent_name": self.agent_name,
"status": "error",
"metadata": {"error": str(error)},
}, timeout=5)
except Exception:
pass2
Attach the callback to your LLM
from langchain_openai import ChatOpenAI
OPSVIZ_URL = "[WEBHOOK_URL]"
llm = ChatOpenAI(
model="gpt-4o",
callbacks=[OpsVizCallback(OPSVIZ_URL, agent_name="Support Bot")]
)
# Use .invoke() — not .run() or .call() (those are deprecated)
response = llm.invoke([{"role": "user", "content": "Hello"}])3
Attach to a chain
from langchain_core.prompts import ChatPromptTemplate
callback = OpsVizCallback(OPSVIZ_URL, agent_name="My Chain")
prompt = ChatPromptTemplate.from_messages([("user", "{input}")])
chain = prompt | llm
# Pass callback at invocation time
response = chain.invoke(
{"input": "Summarise this report..."},
config={"callbacks": [callback]}
)That's it!
Events will appear on your OpsViz dashboard as they arrive. Check the webhook reference for full payload options.