How to monitor LangChain and CrewAI agents in production

Updated 4 min read

On this page
  1. What the frameworks give you, and what they don't
  2. Step 1: Create a monitor
  3. Step 2: A ping helper
  4. Step 3a: Wrap a CrewAI crew
  5. Step 3b: Wrap a LangChain agent
  6. Step 4: Turn on the rules that fit
  7. What this doesn't do
  8. FAQ
  9. Sources

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:

Python · stallbell_ping.py
# 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:

Python · run_crew.py
# 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])
    raise

If 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:

Python · run_agent.py
# 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])
    raise

Hitting 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

RuleWhat it catches hereSetting
Missed runThe scheduler didn't start the agentGrace period (default 5 minutes)
Failed runAn exception, a rate limit, a recursion or iteration limitFailures in a row (default 1)
Stuck runinvoke() or kickoff() never returnedStuck after (default 1 hour)
Empty outputThe answer was empty or only whitespaceFlag empty output (on by default)
LoopThe agent is being restarted again and againLoop window and thresholds
Cost spike, capsA run or a day cost far more than usualCost 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:

Stallbell's side comes from the docs.