-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathhost_agent_server.py
More file actions
335 lines (278 loc) · 12.5 KB
/
host_agent_server.py
File metadata and controls
335 lines (278 loc) · 12.5 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# Copyright (c) Microsoft. All rights reserved.
"""Generic Agent Host Server - Hosts agents implementing AgentInterface"""
# --- Imports ---
import logging
import os
import socket
from os import environ
from aiohttp.web import Application, Request, Response, json_response, run_app
from aiohttp.web_middlewares import middleware as web_middleware
from dotenv import load_dotenv
from agent_interface import AgentInterface, check_agent_inheritance
from microsoft_agents.activity import load_configuration_from_env, Activity, ActivityTypes
from microsoft_agents.authentication.msal import MsalConnectionManager
from microsoft_agents.hosting.aiohttp import (
CloudAdapter,
jwt_authorization_middleware,
start_agent_process,
)
from microsoft_agents.hosting.core import (
AgentApplication,
AgentAuthConfiguration,
AuthenticationConstants,
Authorization,
ClaimsIdentity,
MemoryStorage,
TurnContext,
TurnState,
)
from microsoft_agents_a365.notifications.agent_notification import (
AgentNotification,
NotificationTypes,
AgentNotificationActivity,
ChannelId,
)
from microsoft_agents_a365.notifications import EmailResponse
from microsoft_agents_a365.observability.core.config import configure
from microsoft_agents_a365.observability.core.middleware.baggage_builder import (
BaggageBuilder,
)
from microsoft_agents_a365.runtime.environment_utils import (
get_observability_authentication_scope,
)
from token_cache import cache_agentic_token
# --- Configuration ---
ms_agents_logger = logging.getLogger("microsoft_agents")
ms_agents_logger.addHandler(logging.StreamHandler())
ms_agents_logger.setLevel(logging.INFO)
observability_logger = logging.getLogger("microsoft_agents_a365.observability")
observability_logger.setLevel(logging.ERROR)
logger = logging.getLogger(__name__)
load_dotenv()
agents_sdk_config = load_configuration_from_env(environ)
# --- Public API ---
def create_and_run_host(
agent_class: type[AgentInterface], *agent_args, **agent_kwargs
):
"""Create and run a generic agent host"""
if not check_agent_inheritance(agent_class):
raise TypeError(
f"Agent class {agent_class.__name__} must inherit from AgentInterface"
)
configure(
service_name="AgentFrameworkTracingWithAzureOpenAI",
service_namespace="AgentFrameworkTesting",
)
host = GenericAgentHost(agent_class, *agent_args, **agent_kwargs)
auth_config = host.create_auth_configuration()
host.start_server(auth_config)
# --- Generic Agent Host ---
class GenericAgentHost:
"""Generic host for agents implementing AgentInterface"""
# --- Initialization ---
def __init__(self, agent_class: type[AgentInterface], *agent_args, **agent_kwargs):
if not check_agent_inheritance(agent_class):
raise TypeError(
f"Agent class {agent_class.__name__} must inherit from AgentInterface"
)
self.auth_handler_name = "AGENTIC"
self.agent_class = agent_class
self.agent_args = agent_args
self.agent_kwargs = agent_kwargs
self.agent_instance = None
self.storage = MemoryStorage()
self.connection_manager = MsalConnectionManager(**agents_sdk_config)
self.adapter = CloudAdapter(connection_manager=self.connection_manager)
self.authorization = Authorization(
self.storage, self.connection_manager, **agents_sdk_config
)
self.agent_app = AgentApplication[TurnState](
storage=self.storage,
adapter=self.adapter,
authorization=self.authorization,
**agents_sdk_config,
)
self.agent_notification = AgentNotification(self.agent_app)
self._setup_handlers()
logger.info("✅ Notification handlers registered successfully")
# --- Observability ---
async def _setup_observability_token(
self, context: TurnContext, tenant_id: str, agent_id: str
):
try:
exaau_token = await self.agent_app.auth.exchange_token(
context,
scopes=get_observability_authentication_scope(),
auth_handler_id=self.auth_handler_name,
)
cache_agentic_token(tenant_id, agent_id, exaau_token.token)
except Exception as e:
logger.warning(f"⚠️ Failed to cache observability token: {e}")
async def _validate_agent_and_setup_context(self, context: TurnContext):
tenant_id = context.activity.recipient.tenant_id
agent_id = context.activity.recipient.agentic_app_id
if not self.agent_instance:
logger.error("Agent not available")
await context.send_activity("❌ Sorry, the agent is not available.")
return None
await self._setup_observability_token(context, tenant_id, agent_id)
return tenant_id, agent_id
# --- Handlers (Messages & Notifications) ---
def _setup_handlers(self):
"""Setup message and notification handlers"""
handler = [self.auth_handler_name]
async def help_handler(context: TurnContext, _: TurnState):
await context.send_activity(
f"👋 **Hi there!** I'm **{self.agent_class.__name__}**, your AI assistant.\n\n"
"How can I help you today?"
)
self.agent_app.conversation_update("membersAdded", auth_handlers=handler)(help_handler)
self.agent_app.message("/help", auth_handlers=handler)(help_handler)
@self.agent_app.activity("message", auth_handlers=handler)
async def on_message(context: TurnContext, _: TurnState):
try:
result = await self._validate_agent_and_setup_context(context)
if result is None:
return
tenant_id, agent_id = result
with BaggageBuilder().tenant_id(tenant_id).agent_id(agent_id).build():
user_message = context.activity.text or ""
if not user_message.strip() or user_message.strip() == "/help":
return
logger.info(f"📨 {user_message}")
response = await self.agent_instance.process_user_message(
user_message, self.agent_app.auth, self.auth_handler_name, context
)
await context.send_activity(response)
except Exception as e:
logger.error(f"❌ Error: {e}")
await context.send_activity(f"Sorry, I encountered an error: {str(e)}")
@self.agent_notification.on_agent_notification(
channel_id=ChannelId(channel="agents", sub_channel="*"),
auth_handlers=handler,
)
async def on_notification(
context: TurnContext,
state: TurnState,
notification_activity: AgentNotificationActivity,
):
try:
result = await self._validate_agent_and_setup_context(context)
if result is None:
return
tenant_id, agent_id = result
with BaggageBuilder().tenant_id(tenant_id).agent_id(agent_id).build():
logger.info(f"📬 {notification_activity.notification_type}")
if not hasattr(
self.agent_instance, "handle_agent_notification_activity"
):
logger.warning("⚠️ Agent doesn't support notifications")
await context.send_activity(
"This agent doesn't support notification handling yet."
)
return
response = (
await self.agent_instance.handle_agent_notification_activity(
notification_activity, self.agent_app.auth, self.auth_handler_name, context
)
)
if notification_activity.notification_type == NotificationTypes.EMAIL_NOTIFICATION:
response_activity = EmailResponse.create_email_response_activity(response)
await context.send_activity(response_activity)
return
await context.send_activity(response)
except Exception as e:
logger.error(f"❌ Notification error: {e}")
await context.send_activity(
f"Sorry, I encountered an error processing the notification: {str(e)}"
)
# --- Agent Initialization ---
async def initialize_agent(self):
if self.agent_instance is None:
logger.info(f"🤖 Initializing {self.agent_class.__name__}...")
self.agent_instance = self.agent_class(*self.agent_args, **self.agent_kwargs)
await self.agent_instance.initialize()
# --- Authentication ---
def create_auth_configuration(self) -> AgentAuthConfiguration | None:
client_id = environ.get("CLIENT_ID")
tenant_id = environ.get("TENANT_ID")
client_secret = environ.get("CLIENT_SECRET")
if client_id and tenant_id and client_secret:
logger.info("🔒 Using Client Credentials authentication")
return AgentAuthConfiguration(
client_id=client_id,
tenant_id=tenant_id,
client_secret=client_secret,
scopes=["5a807f24-c9de-44ee-a3a7-329e88a00ffc/.default"],
)
if environ.get("BEARER_TOKEN"):
logger.info("🔑 Anonymous dev mode")
else:
logger.warning("⚠️ No auth env vars; running anonymous")
return None
# --- Server ---
def start_server(self, auth_configuration: AgentAuthConfiguration | None = None):
async def entry_point(req: Request) -> Response:
return await start_agent_process(
req, req.app["agent_app"], req.app["adapter"]
)
async def health(_req: Request) -> Response:
return json_response(
{
"status": "ok",
"agent_type": self.agent_class.__name__,
"agent_initialized": self.agent_instance is not None,
}
)
middlewares = []
if auth_configuration:
middlewares.append(jwt_authorization_middleware)
@web_middleware
async def anonymous_claims(request, handler):
if not auth_configuration:
request["claims_identity"] = ClaimsIdentity(
{
AuthenticationConstants.AUDIENCE_CLAIM: "anonymous",
AuthenticationConstants.APP_ID_CLAIM: "anonymous-app",
},
False,
"Anonymous",
)
return await handler(request)
middlewares.append(anonymous_claims)
app = Application(middlewares=middlewares)
app.router.add_post("/api/messages", entry_point)
app.router.add_get("/api/messages", lambda _: Response(status=200))
app.router.add_get("/api/health", health)
app["agent_configuration"] = auth_configuration
app["agent_app"] = self.agent_app
app["adapter"] = self.agent_app.adapter
app.on_startup.append(lambda app: self.initialize_agent())
app.on_shutdown.append(lambda app: self.cleanup())
desired_port = int(environ.get("PORT", 3978))
port = desired_port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
if s.connect_ex(("127.0.0.1", desired_port)) == 0:
port = desired_port + 1
# Detect production environment (Azure App Service sets WEBSITE_SITE_NAME)
is_production = os.getenv("WEBSITE_SITE_NAME") is not None
host = "0.0.0.0" if is_production else "localhost"
print("=" * 80)
print(f"🏢 {self.agent_class.__name__}")
print("=" * 80)
print(f"🔒 Auth: {'Enabled' if auth_configuration else 'Anonymous'}")
print(f"🚀 Server: {host}:{port}")
print(f"📚 Endpoint: http://localhost:{port}/api/messages")
print(f"❤️ Health: http://localhost:{port}/api/health\n")
try:
run_app(app, host=host, port=port, handle_signals=True)
except KeyboardInterrupt:
print("\n👋 Server stopped")
# --- Cleanup ---
async def cleanup(self):
if self.agent_instance:
try:
await self.agent_instance.cleanup()
except Exception as e:
logger.error(f"Cleanup error: {e}")