Velamuvi AIAcademy

Lesson 21 of 39 · Control, Safety and Quality

Middleware

Wrap agent runs, tool calls and model calls with middleware in Agent Framework: logging, limits, guards, MiddlewareTermination and the right kind for each job.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain how middleware wraps a call with call_next()
  • Log every agent run with AgentMiddleware and AgentContext
  • Check, change or block tool calls with function middleware
  • Watch each model call with chat middleware
  • Stop a run early with MiddlewareTermination, and choose the right kind of middleware

Code that runs around every call

Logging, limits, safety checks and caching apply to every request. Instead of repeating them in every tool and every prompt, you write them once as middleware: a function that wraps a call, can look at it before and after, and decides whether it happens at all.

The whole pattern in plain Python:

Try it yourselfPython
# Middleware in plain Python: each layer gets the context and a call_next() that runs the rest.
def run_pipeline(middleware, handler, context):
    def call(i):
        if i == len(middleware):
            handler(context)
        else:
            middleware[i](context, lambda: call(i + 1))
    call(0)
    return context


def log(context, call_next):
    print("log: question =", context["question"])
    call_next()
    print("log: answer =", context["answer"])


def keep_it_friendly(context, call_next):
    if "stupid" in context["question"]:
        context["answer"] = "Let's keep it friendly."   # answer here and skip the agent
        return
    call_next()


def agent(context):
    print("agent: running")
    context["answer"] = "A City E costs 35 EUR a day."


run_pipeline([log, keep_it_friendly], agent, {"question": "How much is a City E?"})
print()
run_pipeline([log, keep_it_friendly], agent, {"question": "Is your stupid bike any good?"})

The first middleware in the list is the outermost one, and a middleware that doesn't call call_next() stops everything inside it.

Three kinds of middleware

Agent Framework has a middleware kind for each layer of a run:

KindRuns aroundContextTypical jobs
Agent middlewareeach agent.run()AgentContextlogging, input checks, final answers
Function middlewareeach tool callFunctionInvocationContextlimits, approvals, caching tool results
Chat middlewareeach model callChatContextcounting calls, editing prompts, usage

All three go in the same list: Agent(..., middleware=[...]). Pass middleware=[...] to agent.run() as well to add middleware for one run only; it runs inside the agent's own middleware.

Agent middleware

Subclass AgentMiddleware and write process(context, call_next). The AgentContext holds the agent, the messages, the session and, after call_next(), the result: the AgentResponse the caller will get.

import asyncio

from agent_framework import Agent, AgentContext, AgentMiddleware
from agent_framework.openai import OpenAIChatClient


class LogRuns(AgentMiddleware):
    """Agent middleware: wraps every agent.run()."""

    async def process(self, context: AgentContext, call_next) -> None:
        print("→ customer:", context.messages[-1].text)
        await call_next()                       # run the agent and any inner middleware
        print("← agent:", context.result.text)


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
        middleware=[LogRuns()],
    )
    await agent.run("How much does a City E cost?")


asyncio.run(main())
Output
→ customer: How much does a City E cost?
← agent: A City E costs 35 EUR a day.

For a short middleware, a function is enough: decorate it with @agent_middleware.

Function middleware: guard your tools

Function middleware runs around every tool call. The FunctionInvocationContext has the function (its .name), the arguments as a dictionary and, after call_next(), the result. Here a refund limit stops large refunds without touching the tool itself:

import asyncio

from agent_framework import Agent, FunctionInvocationContext, function_middleware, tool
from agent_framework.openai import OpenAIChatClient


@tool
def refund(booking_id: str, amount_eur: float) -> str:
    """Refund money for a booking."""
    return f"Refunded {amount_eur:.0f} EUR for {booking_id}."


@function_middleware
async def refund_limit(context: FunctionInvocationContext, call_next) -> None:
    print(f"  tool call: {context.function.name}({context.arguments})")
    if context.function.name == "refund" and context.arguments["amount_eur"] > 100:
        context.result = "Refunds over 100 EUR need a manager. A manager will call the customer today."
        return                                  # no call_next(): the tool never runs
    await call_next()


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. Use refund() for refunds.",
        tools=[refund],
        middleware=[refund_limit],
    )
    for text in ["Please refund 35 EUR for booking B-1042.", "Please refund 250 EUR for booking B-2077."]:
        print((await agent.run(text)).text)


asyncio.run(main())
Output
  tool call: refund({'booking_id': 'B-1042', 'amount_eur': 35.0})
Done. Refunded 35 EUR for B-1042.
  tool call: refund({'booking_id': 'B-2077', 'amount_eur': 250.0})
Sorry, I couldn't do that: Refunds over 100 EUR need a manager. A manager will call the customer today.

The @function_middleware decorator marks the function's kind. Setting context.result and returning without call_next() skips the tool: the model gets your text as the tool's result and explains it to the customer. To use a class instead, subclass FunctionMiddleware.

Chat middleware: see every model call

A single run can call the model several times: once to choose a tool and once more to answer with its result. @chat_middleware (or a ChatMiddleware subclass) runs around each of those calls, and its ChatContext holds the exact messages sent to the model.

import asyncio

from agent_framework import Agent, ChatContext, chat_middleware, tool
from agent_framework.openai import OpenAIChatClient


@tool
def refund(booking_id: str, amount_eur: float) -> str:
    """Refund money for a booking."""
    return f"Refunded {amount_eur:.0f} EUR for {booking_id}."


@chat_middleware
async def show_model_calls(context: ChatContext, call_next) -> None:
    print("  model call with:", [message.role for message in context.messages])
    await call_next()


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. Use refund() for refunds.",
        tools=[refund],
        middleware=[show_model_calls],
    )
    print((await agent.run("Please refund 35 EUR for booking B-1042.")).text)


asyncio.run(main())
Output
  model call with: ['user']
  model call with: ['user', 'assistant', 'tool']
Done. Refunded 35 EUR for B-1042.

One question, two model calls: the second one carries the tool call and its result. This is the place to count calls, measure usage, or change the messages before the model sees them.

Stopping a run early

To end a run from inside a middleware, raise MiddlewareTermination with the result the caller should get. Here a guard stops card numbers before they ever reach the model or your logs:

import asyncio
import re

from agent_framework import (
    Agent,
    AgentContext,
    AgentMiddleware,
    AgentResponse,
    ChatContext,
    Message,
    MiddlewareTermination,
    chat_middleware,
)
from agent_framework.openai import OpenAIChatClient

CARD_NUMBER = re.compile(r"\b(?:\d[ -]?){13,19}\b")


class BlockCardNumbers(AgentMiddleware):
    async def process(self, context: AgentContext, call_next) -> None:
        if CARD_NUMBER.search(context.messages[-1].text):
            reply = Message("assistant", ["Please don't send card numbers in chat. You can pay safely at the shop."])
            raise MiddlewareTermination(result=AgentResponse(messages=[reply]))
        await call_next()


@chat_middleware
async def show_model_calls(context: ChatContext, call_next) -> None:
    print("  (model called)")
    await call_next()


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
        middleware=[BlockCardNumbers(), show_model_calls],
    )
    print((await agent.run("How much does a City E cost?")).text)
    print((await agent.run("My card is 4111 1111 1111 1111. Please book a City E.")).text)


asyncio.run(main())
Output
  (model called)
A City E costs 35 EUR a day.
Please don't send card numbers in chat. You can pay safely at the shop.

The second question never reached the model: no (model called) line appears. Setting context.result and returning without call_next() works too; MiddlewareTermination is handy deeper in your code, where returning is awkward.

For policy checks that follow the open agent-hooks standard, create_agent_hooks_middleware(...) builds one bundle of agent, chat and function middleware from a list of interceptors. It needs the extra agent-hooks-sdk package; without it, the call raises a ModuleNotFoundError that tells you to run pip install agent-hooks-sdk.

Common mistakes

Practice exercise

Write function middleware that caches tool results: the second call with the same arguments returns the saved result, and the tool doesn't run again.

Your solutionPython
def run_tool(middleware, tool, arguments):
    context = {"arguments": arguments, "result": None}

    def call_next():
        context["result"] = tool(**arguments)

    middleware(context, call_next)
    return context["result"]


calls = []


def price(bike):
    calls.append(bike)
    return {"City E": 35, "Trail X": 50}[bike]


cache = {}


def cache_results(context, call_next):
    # If these arguments are already in the cache, put the cached value in
    # context["result"] and return without calling call_next().
    # Otherwise call call_next() and save context["result"] in the cache.
    call_next()


print(run_tool(cache_results, price, {"bike": "City E"}))
print(run_tool(cache_results, price, {"bike": "City E"}))
print(run_tool(cache_results, price, {"bike": "Trail X"}))
print("the tool ran for:", calls)
Knowledge check

Which kind of middleware runs once for every tool call?

Summary

  • Middleware wraps a call: code before call_next(), the rest of the chain, then code that sees the result.
  • Agent middleware (AgentMiddleware, @agent_middleware) wraps each run; function middleware wraps each tool call; chat middleware wraps each model call.
  • Set context.result and skip call_next(), or raise MiddlewareTermination, to answer without running what's inside.
  • An ordinary exception in function middleware becomes a tool error; raise MiddlewareFailure to abort the run.

Next: Security: Prompt Injection and Governance.

Finished reading? Tick it off to track your progress.