Lesson 5 of 5 Human Oversight, Caching, Scaling and Middleware

Implementing Middleware for Logging, Authorization and Exceptions

This lesson explains middleware in Agent Framework, which implements cross-cutting concerns such as logging, authorization checks and error handling once and applies them around every agent run, model call or tool call, and how to design a reusable middleware stack.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish agent, function and chat middleware.
  • Design a shared middleware package of reusable capabilities.
  • Order and test middleware.

Middleware types in Agent Framework

Agent Framework supports three middleware types. Agent middleware wraps an agent run and sees the input messages and the final response. Function middleware wraps each tool invocation and sees the function and its arguments. Chat middleware wraps each call to the model. A middleware receives a context and a call_next function; it can inspect or modify the context, call call_next() to continue, or skip it to stop the pipeline and set its own result. Middleware is registered on the agent or for a single run.

from agent_framework import FunctionInvocationContext, AgentContext

async def authorize_tools(context: FunctionInvocationContext, call_next):
    user = context.kwargs.get("user")                                  # set by the host from the token
    if context.function.name in WRITE_TOOLS and "Approver" not in user.roles:
        context.result = {"error": "not_authorized", "message": "This action needs an approver."}
        return                                                         # do not call the tool
    await call_next()

async def log_runs(context: AgentContext, call_next):
    start = time.perf_counter()
    try:
        await call_next()
    except Exception:
        logger.exception("agent_failed", extra={"agent": context.agent.name})
        raise
    finally:
        logger.info("agent_run", extra={"agent": context.agent.name, "ms": int((time.perf_counter() - start) * 1000)})

agent = Agent(client=client, name="orders", instructions=..., tools=[...], middleware=[log_runs, authorize_tools])

The following diagram nests the three middleware types.

The three middleware types in Agent Framework. Agent middleware wraps a whole agent run and sees the input messages and the final response, suiting logging and exception handling. Chat middleware wraps each call to the model. Function middleware wraps each tool invocation and sees the function and its arguments, suiting authorization checks. Each middleware calls call_next() to continue, or sets its own result and skips it to stop the pipeline.
Middleware adds shared capabilities without changing agent code.
Sort into groups

Which middleware type?

Exam skills 2.4.8

Choose the Agent Framework middleware type for each cross-cutting concern.

Log in to try this activity Interactive activities are free with an account.

Reusable capabilities

A shared middleware package gives every agent the same baseline. The following list describes typical components.

  • Logging and telemetry: structured logs with correlation IDs, agent and tool names, durations and token counts.
  • Authorization: checks that the current user may call a tool with the given arguments, using claims from the token.
  • Exception handling: converts exceptions into safe, structured results, retries transient failures and hides internal details from users.
  • Policy enforcement: PII redaction, argument limits and domain rules applied before tools run.
  • Budget enforcement: counts tokens and tool calls per run and stops when limits are reached.
Match the pairs

A shared middleware package

Exam skills 2.4.8

Match each reusable middleware component with what it does.

Log in to try this activity Interactive activities are free with an account.

Ordering and testing

Middleware runs in registration order, each wrapping the next. Logging usually wraps everything so that it records blocked calls too; authorization runs before policy checks that might modify arguments; exception handling sits close to the tool so that it can retry. Middleware is plain code, so it is unit tested without a model, and it is versioned and released as a shared package used by all agents. LangChain and LangGraph offer comparable hooks through middleware and callbacks.

True or false

Ordering and testing middleware

Exam skills 2.4.8

Check how middleware is ordered, tested and shared.

Log in to try this activity Interactive activities are free with an account.
Worked example

Inconsistent authorization

An audit finds that three of nine agents check the user's role before calling write tools, and the others rely on instructions. Each agent logs in a different format.

A shared function middleware that enforces role checks on write tools, and an agent middleware that logs in a common structured format, applied to all nine agents, fix both findings with one implementation. Adding authorization instructions to each agent would not enforce anything, and copying code into each agent would drift again.

Check yourself

How does middleware block an action?

Show answer

It does not call call_next() and sets the result itself, so the wrapped run or tool call never happens.

Exam Tips

Remember for the exam

  • Agent middleware wraps runs; function middleware wraps tool calls; chat middleware wraps model calls.
  • Skip call_next() and set a result to block an action.
  • One shared, tested middleware package keeps all agents consistent.