Short answer
LangChain's built-in ModelCallLimitMiddleware and ToolCallLimitMiddleware cap how many calls a run makes, and LangGraph's recursion_limit caps steps, but none of them caps dollars. For a spend limit, add a callback that adds up the cost of each model call from its token usage and refuses the next call once the run's budget is used.
Ten calls to a small model cost a fraction of a cent. Ten calls with a long context to a large model can cost dollars. If what you care about is the bill, you need a limit in dollars. Here is what LangChain has built in, what it does not cover, and how to add a real spend limit.
What LangChain and LangGraph give you
LangChain agents come with built-in middleware that counts calls. ModelCallLimitMiddleware caps model calls and ToolCallLimitMiddleware caps tool calls, per run or per thread. The tool limit can also target a single tool by name:
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[search, send_email],
middleware=[
ModelCallLimitMiddleware(run_limit=20, exit_behavior="end"),
ToolCallLimitMiddleware(run_limit=30),
ToolCallLimitMiddleware(tool_name="send_email", run_limit=1),
],
)A few details worth knowing, from LangChain's own docs. Thread limits need a checkpointer. The model limit defaults to ending the run gracefully. The tool limit defaults to continue, which blocks the extra tool calls with an error message but lets the model keep going. Set exit_behavior="error" if you want the run to stop.
If you build with LangGraph directly, the backstop is the recursion limit:
# LangGraph: cap the number of super-steps for one run
result = graph.invoke(inputs, config={"recursion_limit": 40})
# Going over raises langgraph.errors.GraphRecursionErrorThese are good limits and you should use them. But every one of them counts calls. None of them knows what a call costs.
Why call limits are not a budget
- Calls cost different amounts. A call with a long conversation history costs many times more than the first call of the run.
- Models cost different amounts. Switch to a bigger model and the same call limit allows a much bigger bill.
- Context grows as the run goes on. So the last calls in a long run are the most expensive ones, and a call limit treats them like the first.
Setting a call limit low enough to be safe on cost means setting it too low for normal work. A dollar limit avoids that trade-off.
A spend limit in about 25 lines
LangChain callbacks see every model call they are passed to. This one adds up the cost of each call from the token usage the model reports, and refuses the next call once the budget is used:
from langchain_core.callbacks import BaseCallbackHandler
class BudgetExceeded(Exception):
pass
class RunBudget(BaseCallbackHandler):
raise_error = True # without this, LangChain logs the error and keeps going
def __init__(self, max_usd, usd_per_1m_in, usd_per_1m_out):
self.max_usd = max_usd
self.price_in = usd_per_1m_in / 1_000_000
self.price_out = usd_per_1m_out / 1_000_000
self.spent = 0.0
def on_chat_model_start(self, serialized, messages, **kwargs):
if self.spent >= self.max_usd:
raise BudgetExceeded(f"run budget of ${self.max_usd} used (${self.spent:.4f})")
def on_llm_end(self, response, **kwargs):
for gen in response.generations:
for g in gen:
usage = getattr(getattr(g, "message", None), "usage_metadata", None) or {}
self.spent += usage.get("input_tokens", 0) * self.price_in
self.spent += usage.get("output_tokens", 0) * self.price_out
budget = RunBudget(max_usd=0.50, usd_per_1m_in=0.15, usd_per_1m_out=0.60)
result = agent.invoke(inputs, config={"callbacks": [budget]})The line people miss is raise_error = True. By default LangChain catches errors raised inside a callback, logs them, and carries on. Without that line, your budget check prints a warning and the agent keeps spending.
We ran this on 24 November 2026 with gpt-4o-mini, a tool that always fails and an agent told to keep retrying, with a budget of $0.0003. The run was stopped after 8 model calls. With raise_error left off, the same run ignored the error and finished, spending almost four times the budget.
Things this simple version does not cover:
- Pass it on the call, not on the model. A callback set on the model alone does not see the tools. Pass it in
configso it reaches everything in the run. - Prices change. You have to keep the per-token prices up to date for every model you use.
- Models that report no usage cost $0 here. Check that yours returns
usage_metadata. - One run at a time. Create a new budget object for each run, or the totals carry over.
Doing it with SteerPlane
SteerPlane's LangChain handler does the counting for you, with prices for over 100 models, and adds a step limit, a time limit and deny rules on tool names. Install it with pip install steerplane:
from steerplane.integrations.langchain import SteerPlaneCallbackHandler
handler = SteerPlaneCallbackHandler(
agent_name="support_agent",
model="gpt-4o-mini",
max_cost_usd=0.50,
max_steps=50,
max_runtime_sec=300,
denied_actions=["delete_*", "drop_*"],
)
try:
result = agent.invoke(inputs, config={"callbacks": [handler]})
finally:
handler.finish()Each model call and each tool call counts as one step. A call that would go past a limit is refused, and the refusal ends the run. On version 1.1.5, the same retrying agent with max_cost_usd=0.0003 was ended with a cost limit error you can catch and alert on (tested 24 November 2026). Every run, with its steps, cost and the reason it stopped, shows up in the dashboard.
Loop detection is off by default in this handler, because it matches on tool names and would stop a healthy run that calls the same tool over a list. Turn it on with detect_loops=True if your agent never does that. If you need every call limited whatever the agent structure, the SteerPlane gateway does that from outside the agent by changing one base_url. Setup steps are on the setup page.
A checklist for LangChain agents
- A model call limit and a tool call limit on every agent.
- A tighter limit on any tool that sends, pays or deletes.
- A dollar limit per run, checked before each model call.
- Limits passed on the call, so they reach tools as well as the model.
- A test run with an agent built to overspend, to prove the limit stops it.
Questions people ask
Does LangChain have a built-in cost limit?
No. Its built-in middleware limits the number of model calls and tool calls per run or per thread. It does not limit spend in dollars.
What is LangGraph's recursion_limit?
The maximum number of super-steps a graph may take. You pass it as a top-level config key. When it is hit, LangGraph raises GraphRecursionError.
Can I limit one specific tool in LangChain?
Yes. ToolCallLimitMiddleware takes a tool_name, so you can cap a single tool, such as search, separately from the rest.