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

Middleware

Hooks around the model.

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

Sometimes you want to change what happens inside the agent loop. Log every model call. Trim long histories. Block certain requests. Middleware lets you hook into the loop, at well defined points.

Middleware
From the video: Middleware
  • Change the inside of the loop
  • Log, trim, block
  • Hooks at fixed points

Where middleware runs

Middleware can run at several points. Before the agent starts. Before each model call. Around the model call itself, which lets you change the request or the response. After each model call. And around each tool call. You pick only the hooks you need.

  1. before_agent
  2. before_model
  3. wrap_model_call
  4. after_model
  5. wrap_tool_call
Where middleware runs
From the video: Where middleware runs

A logging middleware

Here we write two small hooks, using decorators. Before model prints how many messages are about to be sent. Wrap tool call prints the tool and its arguments, then runs it. We pass both in the middleware list. Run it. We can now see inside the loop, every model call, and every tool call.

middleware.pypython
from langchain.agents import create_agent
from langchain.agents.middleware import before_model, wrap_tool_call
from shop_tools import check_stock

@before_model
def log_model(state, runtime):
    print(f"model call with {len(state['messages'])} messages")

@wrap_tool_call
def log_tool(request, handler):
    print("tool:", request.tool_call["name"], request.tool_call["args"])
    return handler(request)

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[check_stock],
                     middleware=[log_model, log_tool])
out = agent.invoke({"messages": [{"role": "user", "content": "Is Dune in stock?"}]})
print("answer:", out["messages"][-1].text)
Output
model call with 1 messages
tool: check_stock {'title': 'Dune'}
model call with 3 messages
answer: Yes, there are 3 copies of *Dune* in stock.
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

Middleware hooks into the agent loop, before and after model calls, and around tool calls. Decorators make simple hooks easy. Next, the ready made middleware LangChain provides.

Key takeaways
  • @before_model
  • @wrap_tool_call
  • middleware=[...]
Next up: Built-in Middleware — limits and summaries