Here are some of the most useful. Summarization shrinks long conversations, by summarising old messages. Model call limit stops runaway agents after a set number of calls. Tool call limit does the same for tools. Model retry and tool retry try again after failures. PII middleware hides personal data. And human in the loop pauses for approval.
Let's see a limit in action. We cap the agent at two model calls per run. Then we ask for something that would need many steps, checking six books, one at a time. Run it. The agent stops early, after checking only a couple of the books, instead of looping on and on. In real apps, limits like this protect your costs.
limit.pypython
from langchain.agents import create_agentfrom langchain.agents.middleware import ModelCallLimitMiddlewarefrom shop_tools import check_stocklimit = ModelCallLimitMiddleware(run_limit=2, exit_behavior="end")agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[check_stock], system_prompt="Check one book per step.", middleware=[limit])ask = "Check stock for Dune, Circe, The Hobbit, Emma, Ulysses and Beloved, one at a time."out = agent.invoke({"messages": [{"role": "user", "content": ask}]})checked = [c["args"]["title"] for m in out["messages"] for c in getattr(m, "tool_calls", [])]print("books checked before the limit:", checked)
Output
books checked before the limit: ['Dune', 'Circe']
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")
Built in middleware handles summaries, limits, retries, personal data, and approvals. Add them to the middleware list. Next, changing the system prompt for each request.