MAF AcademyLearnCapstoneSandbox
MAF Academy · Microsoft Agent Framework hands-on workshop · labs verified on agent-framework-core 1.26
← All modules
MODULE 7 OF 8 6 minutes

Testing, Monitoring and Responsible AI

Middleware for control, OpenTelemetry for visibility, tests and guardrails for trust.

1.Testing agent responses and execution
2.Debugging agent behaviour
3.Understanding middleware and execution controls
4.Introduction to observability and tracing
5.Monitoring agent and workflow execution
6.Handling errors and unexpected outputs
7.Security considerations and responsible AI practices

On this page

Middleware: the onion around every runTracing with OpenTelemetryTest pyramid for agentsSecurity & responsible AI checklistKey takeawaysHands-on activityQuiz
1Execution controls

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).

LLM / toolAgent middlewareChat middlewareFunction middleware

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.

Each layer is async def mw(context, call_next). Code before call_next() runs on the way in, code after on the way out.
ex7_testing_monitoring.py
1@agent_middleware
2async 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 called
7 start = time.perf_counter()
8 await call_next()
9 print(f"[timer] {context.agent.name} took {time.perf_counter() - start:.2f}s")
10
11@function_middleware
12async def audit_tools(context: FunctionInvocationContext, call_next) -> None:
13 print(f"[audit] -> {context.function.name}({context.arguments})")
14 await call_next()
2Observability

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.

invoke_agent PricingAgent
└ chat llama-3.3-70b (1)
in 212 · out 31 tok
└ execute_tool discount_price
1200, 15 → 1020.00
└ chat llama-3.3-70b (2)
in 260 · out 48 tok
0 ms≈ 1.2 s
What an OpenTelemetry trace of one tool-using agent run looks like (GenAI semantic conventions).
observability
1from agent_framework.observability import configure_otel_providers
2
3configure_otel_providers(
4 enable_console_exporters=True, # workshop
5 # otlp_endpoint="http://localhost:4317", # Aspire / Jaeger / collector
6 enable_sensitive_data=False,
7)
3Testing

Test pyramid for agents

  1. Unit-test tools deterministically — they're plain functions (tool.func(...)).
  2. Behavioural tests — run the agent and assert on properties (contains the right number, called the right tool), not exact wording.
  3. Scenario evals — a dataset of business requests scored by rubric or an LLM judge (evaluate_agent, keyword_check, tool_called_check exist in the package).

Use a low temperature and stable models in CI.

pytest
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")
4
5@pytest.mark.asyncio
6async 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(",", "")
4Responsible AI

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

01

Agent / chat / function middleware = interception at three levels.

02

configure_otel_providers() gives traces for runs, LLM calls and tools.

03

Unit-test tools; assert properties of agent output; evaluate with scenarios.

04

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

  1. 1Playground: enable the Guardrail middleware and ask for “the admin password”.
  2. 2Enable the Audit middleware and run a tool question — read the audit lines in the trace.
  3. 3Try a bad input: “apply a 90% discount to $500”. How does the agent recover?
  4. 4Multi-Agent Studio: run 3 different scenarios and compare the timeline & token usage.
Open Agent Playground Exercise 7 in Code Lab

Reference solution — labs/ex7_testing_monitoring.py (verified on agent-framework-core 1.26)

ex7_testing_monitoring.py
1"""Exercise 7 — Middleware, observability, guardrails and tests (Module 7).
2
3Run the demo: python ex7_testing_monitoring.py
4Run the tests: pytest ex7_testing_monitoring.py -q
5"""
6
7import asyncio
8import re
9import time
10from typing import Annotated
11
12import pytest
13from pydantic import Field
14
15from 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_providers
26from common import make_client
27
28BLOCKED = re.compile(r"\b(password|credit card|ssn)\b", re.IGNORECASE)
29
30
31# 1) Agent middleware — guardrail + timing around the whole run
32@agent_middleware
33async 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 entirely
38 context.result = AgentResponse(
39 messages=[Message("assistant", ["Sorry — I can't help with credentials or personal data."])]
40 )
41 return
42 start = time.perf_counter()
43 await call_next()
44 print(f"[timer] {context.agent.name} took {time.perf_counter() - start:.2f}s")
45
46
47# 2) Function middleware — audit every tool call
48@function_middleware
49async 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}")
54
55
56@tool
57def 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 gracefully
64 return f"{price * (1 - pct / 100):.2f}"
65
66
67def 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 )
75
76
77# 3) Tests — deterministic checks on tools + behavioural checks on the agent
78def test_discount_tool_is_deterministic() -> None:
79 assert discount_price.func(200, 10) == "180.00"
80 assert discount_price.func(200, 90).startswith("ERROR")
81
82
83@pytest.mark.asyncio
84async 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(",", "")
87
88
89async 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)
93
94 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 middleware
97
98
99if __name__ == "__main__":
100 asyncio.run(main())

Check your understanding

0/3

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?

M6 · WorkflowsM8 · Recap