An agent decides for itself how many tools to call. Usually that's great. But a confused agent can call tools again and again, costing money, and keeping the customer waiting. Limits put a ceiling on it.
Tool call limit middleware caps how many tool calls one run can make. Here, two. We ask the agent to check four books, one call each. Run it. The first two calls return stock counts. The third is blocked by the middleware, and the agent explains it hit its limit, instead of carrying on.
tool_limit.pypython
from langchain.agents import create_agentfrom langchain.agents.middleware import ToolCallLimitMiddlewarefrom shop_tools import check_stockagent = create_agent( "google_genai:gemini-flash-lite-latest", tools=[check_stock], middleware=[ToolCallLimitMiddleware(run_limit=2)],)q = "Check stock for The Hobbit, Dune, Circe and Emma. One call each, one at a time."out = agent.invoke({"messages": [{"role": "user", "content": q}]})for m in out["messages"]: if m.type == "tool": print("tool:", m.text[:70])print("agent:", out["messages"][-1].text[:120])
Output
tool: 7
tool: 3
tool: Tool call limit exceeded. Do not make additional tool calls.
agent: The Hobbit: 7 copies in stock.
Dune: 3 copies in stock.
Circe: and Emma could not be checked due to the tool call limit.
Also uses shop_tools.py
from langchain.tools import toolBOOKS = { "The Hobbit": {"stock": 7, "price": 8.99, "author": "J.R.R. Tolkien"}, "Dune": {"stock": 3, "price": 9.99, "author": "Frank Herbert"}, "Circe": {"stock": 0, "price": 10.99, "author": "Madeline Miller"},}@tooldef check_stock(title: str) -> int: """Copies of a book in stock at Riverside Books.""" return BOOKS.get(title, {}).get("stock", 0)@tooldef get_price(title: str) -> float: """Price of a book in pounds.""" return BOOKS.get(title, {}).get("price", 0.0)@tooldef get_author(title: str) -> str: """Author of a book.""" return BOOKS.get(title, {}).get("author", "unknown")
You have several ceilings. Tool call limit caps tool calls, overall, or for one tool. Model call limit caps model calls. The recursion limit, set in the config, caps the total number of steps. And a timeout caps the time. Use more than one.