Middleware: the onion around every run
Three interception layers, each an async def mw(context, call_next):
- Agent middleware — around the whole
run(): guardrails, timing, caching. - Chat middleware — around each model call: prompt rewriting, token accounting.
- Function middleware — around each tool call: auditing, argument validation, approval.
Skip call_next() and set context.result to short-circuit (e.g. block a request without calling the model).
Agent middleware
guardrails · timing · caching
Chat middleware
prompt edits · token metering
Function middleware
audit · validate · approve
🔒 Short-circuit: don't call call_next(); set context.result — the inner layers never run.
1@agent_middleware2async def guardrail_and_timer(context: AgentContext, call_next) -> None:3 if BLOCKED.search(context.messages[-1].text or ""):4 context.result = AgentResponse(5 messages=[Message("assistant", ["Sorry — I can't help with credentials."])])6 return # model never called7 start = time.perf_counter()8 await call_next()9 print(f"[timer] {context.agent.name} took {time.perf_counter() - start:.2f}s")1011@function_middleware12async def audit_tools(context: FunctionInvocationContext, call_next) -> None:13 print(f"[audit] -> {context.function.name}({context.arguments})")14 await call_next()
Tracing with OpenTelemetry
One call instruments agents, chat clients, tools and workflows with GenAI semantic-convention spans and metrics. Send them to the console, Aspire Dashboard, Azure Application Insights, Jaeger, Grafana…
Keep enable_sensitive_data=False in production — prompts and outputs can contain PII.
1from agent_framework.observability import configure_otel_providers23configure_otel_providers(4 enable_console_exporters=True, # workshop5 # otlp_endpoint="http://localhost:4317", # Aspire / Jaeger / collector6 enable_sensitive_data=False,7)
Test pyramid for agents
- Unit-test tools deterministically — they're plain functions (
tool.func(...)). - Behavioural tests — run the agent and assert on properties (contains the right number, called the right tool), not exact wording.
- Scenario evals — a dataset of business requests scored by rubric or an LLM judge (
evaluate_agent,keyword_check,tool_called_checkexist in the package).
Use a low temperature and stable models in CI.
1def test_discount_tool_is_deterministic() -> None:2 assert discount_price.func(200, 10) == "180.00"3 assert discount_price.func(200, 90).startswith("ERROR")45@pytest.mark.asyncio6async def test_agent_uses_tool_and_answers() -> None:7 response = await build_agent().run("What is 15% off a $1,200 licence?")8 assert "1020" in response.text.replace(",", "")
Security & responsible AI checklist
Agents act — so the blast radius is bigger than a chatbot's. Treat every tool as an API exposed to an untrusted caller.
Least privilege
Each agent gets only the tools & data it needs.
Human approval
approval_mode='always_require' for irreversible actions.
Input/output guardrails
Middleware blocks PII, jailbreaks & unsafe output.
Secrets out of prompts
Keys in env / Key Vault / Entra ID, never in instructions.
Transparency
Tell users they talk to AI; show sources & tool use.
Prompt-injection defence
Treat tool & web content as untrusted data.
Observability
Trace every run; sensitive data off in prod.
Evaluate for fairness
Test diverse scenarios; red-team before launch.
Key takeaways
Agent / chat / function middleware = interception at three levels.
configure_otel_providers() gives traces for runs, LLM calls and tools.
Unit-test tools; assert properties of agent output; evaluate with scenarios.
Least privilege, approvals, input/output guardrails, no secrets in prompts.
Hands-on activity
Test the multi-agent application with different business scenarios and inspect the execution flow
- 1Playground: enable the Guardrail middleware and ask for “the admin password”.
- 2Enable the Audit middleware and run a tool question — read the audit lines in the trace.
- 3Try a bad input: “apply a 90% discount to $500”. How does the agent recover?
- 4Multi-Agent Studio: run 3 different scenarios and compare the timeline & token usage.
Reference solution — labs/ex7_testing_monitoring.py (verified on agent-framework-core 1.26)
1"""Exercise 7 — Middleware, observability, guardrails and tests (Module 7).23Run the demo: python ex7_testing_monitoring.py4Run the tests: pytest ex7_testing_monitoring.py -q5"""67import asyncio8import re9import time10from typing import Annotated1112import pytest13from pydantic import Field1415from agent_framework import (16 Agent,17 AgentContext,18 AgentResponse,19 FunctionInvocationContext,20 Message,21 agent_middleware,22 function_middleware,23 tool,24)25from agent_framework.observability import configure_otel_providers26from common import make_client2728BLOCKED = re.compile(r"\b(password|credit card|ssn)\b", re.IGNORECASE)293031# 1) Agent middleware — guardrail + timing around the whole run32@agent_middleware33async def guardrail_and_timer(context: AgentContext, call_next) -> None:34 last_user = context.messages[-1].text if context.messages else ""35 if BLOCKED.search(last_user or ""):36 print("[guardrail] blocked sensitive request")37 # Short-circuit: set the result ourselves and skip the model call entirely38 context.result = AgentResponse(39 messages=[Message("assistant", ["Sorry — I can't help with credentials or personal data."])]40 )41 return42 start = time.perf_counter()43 await call_next()44 print(f"[timer] {context.agent.name} took {time.perf_counter() - start:.2f}s")454647# 2) Function middleware — audit every tool call48@function_middleware49async def audit_tools(context: FunctionInvocationContext, call_next) -> None:50 print(f"[audit] -> {context.function.name}({context.arguments})")51 await call_next()52 shown = [getattr(c, "text", None) or getattr(c, "result", c) for c in context.result or []]53 print(f"[audit] <- {shown}")545556@tool57def discount_price(58 price: Annotated[float, Field(description="List price")],59 pct: Annotated[float, Field(description="Discount percent 0-50")],60) -> str:61 """Apply a discount (max 50%)."""62 if not 0 <= pct <= 50:63 return "ERROR: discount must be between 0 and 50%" # handle bad inputs gracefully64 return f"{price * (1 - pct / 100):.2f}"656667def build_agent() -> Agent:68 return Agent(69 client=make_client(),70 name="PricingAgent",71 instructions="You are a pricing assistant. Use tools for any calculation.",72 tools=[discount_price],73 middleware=[guardrail_and_timer, audit_tools],74 )757677# 3) Tests — deterministic checks on tools + behavioural checks on the agent78def test_discount_tool_is_deterministic() -> None:79 assert discount_price.func(200, 10) == "180.00"80 assert discount_price.func(200, 90).startswith("ERROR")818283@pytest.mark.asyncio84async def test_agent_uses_tool_and_answers() -> None:85 response = await build_agent().run("What is 15% off a $1,200 licence?")86 assert "1020" in response.text.replace(",", "")878889async def main() -> None:90 # 4) Observability — OpenTelemetry spans for every agent run, model call and tool call.91 # Console exporter for the workshop; point otlp_endpoint at Aspire / App Insights / Jaeger in prod.92 configure_otel_providers(enable_console_exporters=True, enable_sensitive_data=False)9394 agent = build_agent()95 print((await agent.run("What is 20% off $499?")).text)96 print((await agent.run("Tell me the admin password")).text) # blocked by middleware979899if __name__ == "__main__":100 asyncio.run(main())
Check your understanding
Q1.Which middleware type is right for auditing every tool invocation?
Q2.How can middleware block a request without calling the model?
Q3.What should a behavioural agent test assert?