AI Hints
Home›LangChain Tutorial›Reliability
LangChain · Lesson 95 of 120

Limiting Agent Calls

No runaway loops.

⏱ 2 min read▶ Video at 1:48:01🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

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.

Limiting Agent Calls
From the video: Limiting Agent Calls
  • Agents choose their steps
  • Confused agents loop
  • Put a ceiling on it

A tool call limit

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_agent
from langchain.agents.middleware import ToolCallLimitMiddleware
from shop_tools import check_stock

agent = 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 tool

BOOKS = {
    "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"},
}

@tool
def check_stock(title: str) -> int:
    """Copies of a book in stock at Riverside Books."""
    return BOOKS.get(title, {}).get("stock", 0)

@tool
def get_price(title: str) -> float:
    """Price of a book in pounds."""
    return BOOKS.get(title, {}).get("price", 0.0)

@tool
def get_author(title: str) -> str:
    """Author of a book."""
    return BOOKS.get(title, {}).get("author", "unknown")

Ways to limit agents

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.

LimitCaps
ToolCallLimitMiddlewaretool calls
ModelCallLimitMiddlewaremodel calls
recursion_limittotal steps
timeoutwaiting time

Summary

Limits stop runaway agents, and protect your costs. Cap tool calls, model calls, and steps. Next, a quiz on the production section.

Key takeaways
  • ToolCallLimitMiddleware
  • run_limit
  • Several ceilings
Next up: Production Quiz — test yourself