AI AgentsLangChain
How do you implement tool-call limits with middleware?
Question 322 of 324 · Updated
On this page
Direct answer#
Use ToolCallLimitMiddleware in LangChain's create_agent to limit how many tool calls an agent can make. Configure a run_limit for one execution, a thread_limit for cumulative usage within a conversation, and optionally a tool_name to limit a specific tool.
This prevents an agent from repeatedly searching, querying a database or calling a paid API without making progress. A tool-call limit controls quantity; it does not replace tool authorization, a timeout or a spending limit.
1. Practical example: a research assistant#
Suppose your agent has two read-only tools: search and lookup. You want a maximum of five tool calls per run, 20 across a conversation, and no more than two search calls per run.
PYTHONfrom langchain.agents import create_agent from langchain.agents.middleware import ToolCallLimitMiddleware from langgraph.checkpoint.memory import InMemorySaver # search and lookup are already defined, approved tools. agent = create_agent( model="openai:gpt-4o-mini", tools=[search, lookup], middleware=[ ToolCallLimitMiddleware( run_limit=5, thread_limit=20, exit_behavior="continue", ), ToolCallLimitMiddleware( tool_name="search", run_limit=2, exit_behavior="continue", ), ], checkpointer=InMemorySaver(), )
Invoke the agent with an authorized thread_id in config["configurable"] so that conversation state is associated with the correct thread. The second middleware instance targets the registered name of the search tool.
This is an illustrative modern LangChain configuration. The installed SDK must support composition of global and named-tool limit instances; verify this, their counter semantics and exact constructor options in the pinned release. InMemorySaver is process-local, not durable production storage.
2. Run-level versus thread-level limits#
| Setting | Scope | Example |
|---|---|---|
| run_limit | Current agent run | Five calls before this execution exhausts its allowance |
| thread_limit | Cumulative calls across the thread | Twenty calls across several turns |
| tool_name | Named tool rather than all tools | Two search calls per run |
Under the intended policy above, a run with two search calls and three lookup calls exhausts its five-call global allowance. Another run can receive a fresh run allowance, but the thread's cumulative usage is still five. The two-call search limit resets with the run. A different authorized thread has its own cumulative allowance.
Checkpointing and correct thread identity matter for thread-level persistence. Verify the SDK's reset and resume behavior rather than treating a resumed interrupted run as automatically entitled to a fresh budget.
3. What happens when the limit is reached?#
Modern ToolCallLimitMiddleware exposes exit_behavior options commonly including:
| Behavior | Intended outcome |
|---|---|
| continue | Report a limit-related tool result and allow the agent to proceed |
| error | Raise a limit-related error |
| end | Terminate the agent execution where supported |
Choose continue when the model can use the remaining evidence or another eligible tool to answer. Choose error when your application must explicitly handle exhaustion. Choose end when stopping is the desired behavior, subject to the installed version's restrictions on pending or parallel tool calls.
Continue does not guarantee termination: a model might keep proposing blocked calls. Combine it with a model-call or graph-step limit and a deadline. Do not present an incomplete research result as verified.
This diagram describes the desired admission policy, not the SDK's internal implementation.
4. Tested example: reserve capacity before execution#
For strict application-side quotas, check and reserve all applicable budgets before a tool starts. The following small Python example models one thread, with a global run limit, a cumulative thread limit and cumulative per-tool limits.
PYTHONfrom threading import Lock from collections import Counter class Budget: def __init__(self, run_limit, thread_limit, per_tool): self.run_limit, self.thread_limit = run_limit, thread_limit self.per_tool = dict(per_tool) self.total = 0 self.runs, self.tools = Counter(), Counter() self.lock = Lock() def reserve(self, run_id, tool): with self.lock: if (self.total >= self.thread_limit or self.runs[run_id] >= self.run_limit or self.tools[tool] >= self.per_tool.get(tool, self.thread_limit)): return False self.total += 1 self.runs[run_id] += 1 self.tools[tool] += 1 return True
Create Budget(3, 5, {"search": 2}) to allow three reservations per run, five across the thread and two search reservations across the thread. Notice that this custom policy's per-tool limit is cumulative, unlike the per-run search setting in section 1.
Only execute the approved tool after reserve returns True. The lock ensures that two callers cannot both consume the same last slot within this process. A reservation consumes capacity even if the subsequent operation fails; no refund is implied.
Local verification: Twelve checks passed on Python 3.13.5, including run exhaustion, cumulative search exhaustion across runs, thread exhaustion and a concurrent fixture in which exactly three of 50 reservation attempts succeeded. This helper assumes trusted run IDs and validated configuration. It is an in-memory teaching example, not a distributed quota service or an implementation of LangChain middleware.
5. Practical safeguards#
- Parallel calls: Test a model response proposing more tools than the remaining allowance. If a strict no-overrun guarantee is required, enforce atomic admission at the actual tool boundary.
- Retries: A single logical tool call may make several HTTP requests. Count underlying attempts separately when controlling external API costs.
- Independent quotas: Use durable atomic counters for shared limits across workers, users or restarts. A process-local lock cannot coordinate separate processes.
- Authorization: A remaining allowance is not permission to access data or perform an action.
- Testing: Verify the actual agent's counters, blocked-call results, run resets, resumed execution and behavior at exact limit boundaries. Preserve tool-call/result correlation when rejecting calls.
Key takeaway#
Use ToolCallLimitMiddleware for agent-level tool-call budgets. Combine run, thread and named-tool limits where needed, choose explicit exhaustion behavior, and enforce strict external quotas independently when actual resource usage matters.
References
- 1.LangChain built-in middlewaredocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangGraph persistencedocs.langchain.com
- 4.Python threadingdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps