How to monitor LangChain and CrewAI agents in production
On this page
To monitor a LangChain or CrewAI agent in production, wrap the call that runs it, agent.invoke() or crew.kickoff(), with a start ping and a finish ping. The finish ping carries the exit status, the agent's answer and the token usage the framework already reports. An outside monitor can then alert you when a run doesn't happen, fails, hangs, returns an empty answer, loops or costs far more than usual, without adding a tracing SDK to the agent.
What the frameworks give you, and what they don't
Both frameworks report what happened inside a run you're watching: CrewAI returns a CrewOutput and keeps usage_metrics on the crew, and LangChain reports token usage through callbacks. Neither one notices a run that never started, because the scheduler that should have started it is outside the framework. And neither library's docs, as we read them, describe paging you when a run hangs or comes back with an empty answer. That's the job of a check outside the process.
Step 1: Create a monitor
Create a monitor in Stallbell for the agent and set its schedule to match how the agent is started: a fixed interval, or On a cron schedule with the same cron expression. Copy its ping URL, https://stallbell.com/p/TOKEN. Keep it in an environment variable rather than in code.
Step 2: A ping helper
Both wrappers below use this helper. It uses only the Python standard library and never raises, so a monitoring problem can't break the agent:
# stallbell_ping.py
import json, os, sys, urllib.request
PING = os.environ.get("STALLBELL_PING_URL", "https://stallbell.com/p/TOKEN")
def ping(path, run_id, **fields):
body = json.dumps({"run_id": run_id, **fields}).encode()
req = urllib.request.Request(PING + path, data=body, method="POST",
headers={"content-type": "application/json"})
try:
urllib.request.urlopen(req, timeout=10).read()
except Exception as exc:
print("stallbell ping failed:", exc, file=sys.stderr)Step 3a: Wrap a CrewAI crew
crew.kickoff() returns a CrewOutput whose raw attribute is the final answer as a string. After the run, crew.usage_metrics holds prompt_tokens and completion_tokens summed over every model call the crew made:
# run_crew.py
import uuid
from stallbell_ping import ping
from my_project.crew import build_crew # your crew
run_id = str(uuid.uuid4())
crew = build_crew()
ping("/start", run_id)
try:
result = crew.kickoff(inputs={"topic": "new leads"})
usage = crew.usage_metrics
ping("/0", run_id,
output=(result.raw or "")[:2000],
model="gpt-4.1-mini", # the model your agents use
input_tokens=usage.prompt_tokens,
output_tokens=usage.completion_tokens)
except Exception as exc:
ping("/fail", run_id, msg=str(exc)[:500])
raiseIf your agents use different models, work out the cost yourself and send cost_usd instead of model and the token counts. Stallbell prices one model per report.
Put a step limit on each agent too: max_iter (default 20) caps iterations, and max_execution_time sets a time limit in seconds.
Step 3b: Wrap a LangChain agent
An agent made with create_agent runs on LangGraph, so it takes a recursion_limit in its config and raises GraphRecursionError when a run goes past it. UsageMetadataCallbackHandler collects token usage per model name across the run:
# run_agent.py
import uuid
from langchain.agents import create_agent
from langchain_core.callbacks import UsageMetadataCallbackHandler
from stallbell_ping import ping
agent = create_agent(model="openai:gpt-4.1-mini", tools=[]) # your tools here
run_id = str(uuid.uuid4())
usage = UsageMetadataCallbackHandler()
ping("/start", run_id)
try:
state = agent.invoke(
{"messages": [{"role": "user", "content": "Summarise today's new leads"}]},
config={"callbacks": [usage], "recursion_limit": 25},
)
answer = state["messages"][-1].content
if not isinstance(answer, str):
answer = str(answer)
totals = list(usage.usage_metadata.values())
ping("/0", run_id,
output=answer[:2000],
model="gpt-4.1-mini",
input_tokens=sum(t.get("input_tokens", 0) for t in totals),
output_tokens=sum(t.get("output_tokens", 0) for t in totals))
except Exception as exc:
ping("/fail", run_id, msg=str(exc)[:500])
raiseHitting the recursion limit raises, so it reaches Stallbell as a Failed run with the error text in msg. The LangGraph docs give the default limit as 10,007 super-steps from version 1.1.4, which is why it's worth setting your own.
Step 4: Turn on the rules that fit
| Rule | What it catches here | Setting |
|---|---|---|
| Missed run | The scheduler didn't start the agent | Grace period (default 5 minutes) |
| Failed run | An exception, a rate limit, a recursion or iteration limit | Failures in a row (default 1) |
| Stuck run | invoke() or kickoff() never returned | Stuck after (default 1 hour) |
| Empty output | The answer was empty or only whitespace | Flag empty output (on by default) |
| Loop | The agent is being restarted again and again | Loop window and thresholds |
| Cost spike, caps | A run or a day cost far more than usual | Cost spike (default 3), Per-run and Per-day cost caps |
If the agent should return JSON, turn on Output must be JSON. If every good answer contains a known phrase, put it in Output must contain.
What this doesn't do
- It isn't a tracer. Stallbell sees the start, the finish and the fields you send. It doesn't record prompts, tool calls or the steps inside a run. Use a tracing tool for that, and Stallbell for the alert that something went wrong.
- It doesn't judge quality. The output checks are empty, whitespace, a required phrase and valid JSON.
- It doesn't stop the agent. Alerts don't cancel runs. The step and recursion limits in your code do that.
FAQ
Do I need a Stallbell SDK? No. Both wrappers send plain HTTP requests with the standard library.
What if the agent runs inside a web request, not on a schedule? Give the monitor the longest gap between runs that is still normal, and rely on the run rules: Failed run, Stuck run, Empty output, Loop and the cost rules work on each run whenever it happens.
Does it work with LangGraph graphs I build myself? Yes. Wrap graph.invoke() the same way and pass recursion_limit in its config.
Related: Detect an agent stuck in a loop · Runaway LLM cost alerts · Alert on empty LLM output · How to monitor AI agents that run on a schedule
Sources
Framework behaviour on this page comes from each framework's own docs, read on 9 November 2026:
- CrewAI Crews (
kickoff(),CrewOutputandusage_metrics) - CrewAI Agents (
max_iterandmax_execution_time) - LangChain Agents (
create_agentandinvoke()) - LangChain Models (
UsageMetadataCallbackHandler) - LangGraph Graph API: recursion limit (
recursion_limit)
Stallbell's side comes from the docs.