AI Hints
Home›LangChain Tutorial›Structured Answers and Middleware
LangChain · Lesson 51 of 120

Built-in Middleware

Limits and summaries.

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

LangChain comes with ready made middleware for common needs. You don't have to write these yourself. Just add them to the list.

Built-in Middleware
From the video: Built-in Middleware
  • Ready-made
  • Common needs
  • Add to the list

Useful built-ins

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.

MiddlewareDoes
SummarizationMiddlewaresummarises old messages
ModelCallLimitMiddlewarecaps model calls
ToolCallLimitMiddlewarecaps tool calls
ModelRetryMiddlewareretries failed calls
PIIMiddlewarehides personal data
HumanInTheLoopMiddlewarepauses for approval

A call limit

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

limit = 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 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")

Summary

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.

Key takeaways
  • Summarization
  • Call limits
  • Retries, PII, approvals
Next up: Dynamic Prompts — changing per request