-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathagent_middleware.py
More file actions
299 lines (241 loc) · 10.7 KB
/
agent_middleware.py
File metadata and controls
299 lines (241 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""
Middleware flow diagram:
agent.run("user message")
│
▼
┌─────────────────────────────────────────────┐
│ Agent Middleware │
│ (timing, blocking, logging) │
│ │
│ ┌───────────────────────────────────────┐ │
│ │ Chat Middleware │ │
│ │ (logging, message counting) │ │
│ │ │ │
│ │ ┌──────────────┐ │ │
│ │ │ AI Model │ │ │
│ │ └──────┬───────┘ │ │
│ │ │ tool calls │ │
│ │ ▼ │ │
│ │ ┌──────────────────────────────────┐ │ │
│ │ │ Function Middleware │ │ │
│ │ │ (logging, timing) │ │ │
│ │ │ │ │ │
│ │ │ get_weather(), get_date(), ... │ │ │
│ │ └──────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌──────────────┐ │ │
│ │ │ AI Model │ │ │
│ │ │ (final ans) │ │ │
│ │ └──────────────┘ │ │
│ └───────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
│
▼
response
"""
import asyncio
import logging
import os
import random
import sys
import time
from collections.abc import Awaitable, Callable
from datetime import datetime
from typing import Annotated
from agent_framework import (
AgentMiddleware,
AgentContext,
AgentResponse,
Agent,
ChatContext,
Message,
ChatMiddleware,
FunctionInvocationContext,
FunctionMiddleware,
tool,
)
from agent_framework.openai import OpenAIChatClient
from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
from dotenv import load_dotenv
from pydantic import Field
from rich import print
from rich.logging import RichHandler
# Setup logging
handler = RichHandler(show_path=False, rich_tracebacks=True, show_level=False)
logging.basicConfig(level=logging.WARNING, handlers=[handler], force=True, format="%(message)s")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Configure OpenAI client based on environment
load_dotenv(override=True)
API_HOST = os.getenv("API_HOST", "github")
async_credential = None
if API_HOST == "azure":
async_credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default")
client = OpenAIChatClient(
base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/",
api_key=token_provider,
model_id=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"],
)
elif API_HOST == "github":
client = OpenAIChatClient(
base_url="https://models.github.ai/inference",
api_key=os.environ["GITHUB_TOKEN"],
model_id=os.getenv("GITHUB_MODEL", "openai/gpt-4.1-mini"),
)
else:
client = OpenAIChatClient(api_key=os.environ["OPENAI_API_KEY"], model_id=os.environ.get("OPENAI_MODEL", "gpt-4o"))
# ---- Tools ----
@tool
def get_weather(
city: Annotated[str, Field(description="The city to get the weather for.")],
) -> dict:
"""Return weather data for a given city, a dictionary with temperature and description."""
logger.info(f"Getting weather for {city}")
if random.random() < 0.05:
return {"temperature": 72, "description": "Sunny"}
else:
return {"temperature": 60, "description": "Rainy"}
@tool
def get_current_date() -> str:
"""Get the current date from the system and return as a string in format YYYY-MM-DD."""
logger.info("Getting current date")
return datetime.now().strftime("%Y-%m-%d")
# ---- Function-based middleware ----
async def timing_agent_middleware(
context: AgentContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Agent middleware that logs execution timing."""
start = time.perf_counter()
logger.info("[⏲️ Timing][ Agent Middleware] Starting agent execution")
await call_next()
elapsed = time.perf_counter() - start
logger.info(f"[⏲️ Timing][ Agent Middleware] Execution completed in {elapsed:.2f}s")
async def logging_function_middleware(
context: FunctionInvocationContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Function middleware that logs function calls and results."""
logger.info(f"[🪵 Logging][ Function Middleware] Calling {context.function.name} with args: {context.arguments}")
await call_next()
logger.info(f"[🪵 Logging][ Function Middleware] {context.function.name} returned: {context.result}")
async def logging_chat_middleware(
context: ChatContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Chat middleware that logs AI interactions."""
logger.info(f"[💬 Logging][ Chat Middleware] Sending {len(context.messages)} messages to AI")
await call_next()
logger.info("[💬 Logging][ Chat Middleware] AI response received")
# ---- Class-based middleware ----
class BlockingAgentMiddleware(AgentMiddleware):
"""Agent middleware that blocks requests containing forbidden words."""
def __init__(self, blocked_words: list[str]) -> None:
"""Initialize with a list of words that should be blocked."""
self.blocked_words = blocked_words
async def process(
self,
context: AgentContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Check messages for blocked content and terminate if found."""
last_message = context.messages[-1] if context.messages else None
if last_message and last_message.text:
for word in self.blocked_words:
if word.lower() in last_message.text.lower():
logger.warning(f"[❌ Blocking][ Agent Middleware] Request blocked: contains '{word}'")
context.terminate = True
context.result = AgentResponse(
messages=[
Message(role="assistant", text=f"Sorry, I can't process requests about '{word}'.")
]
)
return
await call_next()
class TimingFunctionMiddleware(FunctionMiddleware):
"""Function middleware that tracks execution time of each function call."""
async def process(
self,
context: FunctionInvocationContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Time the function execution and log the duration."""
start = time.perf_counter()
logger.info(f"[⌚️ Timing][ Function Middleware] Starting {context.function.name}")
await call_next()
elapsed = time.perf_counter() - start
logger.info(f"[⌚️ Timing][ Function Middleware] {context.function.name} took {elapsed:.4f}s")
class MessageCountChatMiddleware(ChatMiddleware):
"""Chat middleware that tracks the total number of messages sent to the AI."""
def __init__(self) -> None:
"""Initialize the message counter."""
self.total_messages = 0
async def process(
self,
context: ChatContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Count messages and log the running total."""
self.total_messages += len(context.messages)
logger.info(
"[🔢 Message Count][ Chat Middleware] Messages in this request: %s, total so far: %s",
len(context.messages),
self.total_messages,
)
await call_next()
logger.info("[🔢 Message Count][ Chat Middleware] Chat response received")
# ---- Agent setup ----
# Instantiate class-based middleware
blocking_middleware = BlockingAgentMiddleware(blocked_words=["nuclear", "classified"])
timing_function_middleware = TimingFunctionMiddleware()
message_count_middleware = MessageCountChatMiddleware()
agent = Agent(
name="middleware-demo",
client=client,
instructions="You help users plan their weekends. Use the available tools to check the weather and date.",
tools=[get_weather, get_current_date],
middleware=[
# Agent-level middleware applied to ALL runs
timing_agent_middleware,
blocking_middleware,
logging_function_middleware,
timing_function_middleware,
logging_chat_middleware,
message_count_middleware,
],
)
async def main() -> None:
"""Run the agent with different inputs to demonstrate middleware behavior."""
# Normal request - all middleware fires
logger.info("=== Normal Request ===")
response = await agent.run("What's the weather like this weekend in San Francisco?")
print(response.text)
# Blocked request - blocking middleware terminates early
logger.info("\n=== Blocked Request ===")
response = await agent.run("Tell me about nuclear physics.")
print(response.text)
# Another normal request with run-level middleware
logger.info("\n=== Request with Run-Level Middleware ===")
async def extra_agent_middleware(
context: AgentContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
"""Run-level middleware that only applies to this specific run."""
logger.info("[🏃🏽♀️ Run-Level Middleware] This middleware only applies to this run")
await call_next()
logger.info("[🏃🏽♀️ Run-Level Middleware] Run completed")
response = await agent.run(
"What's the weather like in Portland?",
middleware=[extra_agent_middleware],
)
print(response.text)
if async_credential:
await async_credential.close()
if __name__ == "__main__":
if "--devui" in sys.argv:
from agent_framework.devui import serve
serve(entities=[agent], auto_open=True)
else:
asyncio.run(main())