-
Notifications
You must be signed in to change notification settings - Fork 2
Reducing Code in Python AgentsFramework Sample #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
94e55e4
e23d1b6
71c9e7f
9b36858
9875336
09f19e8
004135c
8ac8c0e
6d404d5
8cec7ae
961d354
a37bf0e
85ca5f5
c3b52d0
83461f2
3fa1929
a6496fd
c8c0db0
8de72f9
e07cac0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -17,7 +17,6 @@ | |||||||||||||
| - Comprehensive error handling and cleanup | ||||||||||||||
| """ | ||||||||||||||
|
|
||||||||||||||
| import asyncio | ||||||||||||||
| import logging | ||||||||||||||
| import os | ||||||||||||||
|
|
||||||||||||||
|
|
@@ -38,14 +37,12 @@ | |||||||||||||
| # AgentFramework SDK | ||||||||||||||
| from agent_framework import ChatAgent | ||||||||||||||
| from agent_framework.azure import AzureOpenAIChatClient | ||||||||||||||
| from agent_framework.observability import setup_observability | ||||||||||||||
|
|
||||||||||||||
| # Agent Interface | ||||||||||||||
| from agent_interface import AgentInterface | ||||||||||||||
| from azure.identity import AzureCliCredential | ||||||||||||||
|
|
||||||||||||||
| # Microsoft Agents SDK | ||||||||||||||
| from local_authentication_options import LocalAuthenticationOptions | ||||||||||||||
| from microsoft_agents.hosting.core import Authorization, TurnContext | ||||||||||||||
|
|
||||||||||||||
| # Notifications | ||||||||||||||
|
|
@@ -60,10 +57,11 @@ | |||||||||||||
| from microsoft_agents_a365.tooling.extensions.agentframework.services.mcp_tool_registration_service import ( | ||||||||||||||
| McpToolRegistrationService, | ||||||||||||||
| ) | ||||||||||||||
| from token_cache import get_cached_agentic_token | ||||||||||||||
|
|
||||||||||||||
| # </DependencyImports> | ||||||||||||||
|
|
||||||||||||||
| class LocalAuthenticationOptions(): | ||||||||||||||
| bearer_token: str | ||||||||||||||
|
|
||||||||||||||
| class AgentFrameworkAgent(AgentInterface): | ||||||||||||||
| """AgentFramework Agent integrated with MCP servers and Observability""" | ||||||||||||||
|
|
@@ -79,23 +77,18 @@ def __init__(self): | |||||||||||||
| """Initialize the AgentFramework agent.""" | ||||||||||||||
| self.logger = logging.getLogger(self.__class__.__name__) | ||||||||||||||
|
|
||||||||||||||
| # Initialize auto instrumentation with Agent 365 Observability SDK | ||||||||||||||
| self._enable_agentframework_instrumentation() | ||||||||||||||
| # Initialize Agent 365 Observability Wrapper for AgentFramework SDK | ||||||||||||||
| AgentFrameworkInstrumentor().instrument() | ||||||||||||||
|
|
||||||||||||||
| # Initialize authentication options | ||||||||||||||
| self.auth_options = LocalAuthenticationOptions.from_environment() | ||||||||||||||
|
|
||||||||||||||
| # Create Azure OpenAI chat client | ||||||||||||||
| self._create_chat_client() | ||||||||||||||
|
|
||||||||||||||
| # Create the agent with initial configuration | ||||||||||||||
| self._create_agent() | ||||||||||||||
| self.auth_options = LocalAuthenticationOptions() | ||||||||||||||
| self.auth_options.bearer_token = os.getenv("BEARER_TOKEN", "") | ||||||||||||||
|
|
||||||||||||||
| # Initialize MCP services | ||||||||||||||
| self._initialize_services() | ||||||||||||||
| self.tool_service = McpToolRegistrationService() | ||||||||||||||
|
|
||||||||||||||
| # Track if MCP servers have been set up | ||||||||||||||
| self.mcp_servers_initialized = False | ||||||||||||||
| # Create Azure OpenAI chat client | ||||||||||||||
| self._create_chat_client() | ||||||||||||||
JesuTerraz marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||
|
|
||||||||||||||
| # </Initialization> | ||||||||||||||
|
|
||||||||||||||
|
|
@@ -125,7 +118,8 @@ def _create_chat_client(self): | |||||||||||||
| deployment_name=deployment, | ||||||||||||||
| api_version=api_version, | ||||||||||||||
| ) | ||||||||||||||
| logger.info("✅ AzureOpenAIChatClient created") | ||||||||||||||
|
|
||||||||||||||
| logger.info("AzureOpenAIChatClient created successfully") | ||||||||||||||
JesuTerraz marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||
|
|
||||||||||||||
| def _create_agent(self): | ||||||||||||||
| """Create the AgentFramework agent with initial configuration""" | ||||||||||||||
|
|
@@ -135,70 +129,31 @@ def _create_agent(self): | |||||||||||||
| instructions=self.AGENT_PROMPT, | ||||||||||||||
| tools=[], | ||||||||||||||
| ) | ||||||||||||||
| logger.info("✅ AgentFramework agent created") | ||||||||||||||
| except Exception as e: | ||||||||||||||
| logger.error(f"Failed to create agent: {e}") | ||||||||||||||
| raise | ||||||||||||||
|
|
||||||||||||||
| # </ClientCreation> | ||||||||||||||
|
|
||||||||||||||
| # ========================================================================= | ||||||||||||||
| # OBSERVABILITY CONFIGURATION | ||||||||||||||
| # ========================================================================= | ||||||||||||||
| # <ObservabilityConfiguration> | ||||||||||||||
|
|
||||||||||||||
| def token_resolver(self, agent_id: str, tenant_id: str) -> str | None: | ||||||||||||||
| """Token resolver for Agent 365 Observability""" | ||||||||||||||
| try: | ||||||||||||||
| cached_token = get_cached_agentic_token(tenant_id, agent_id) | ||||||||||||||
| if not cached_token: | ||||||||||||||
| logger.warning(f"No cached token for agent {agent_id}") | ||||||||||||||
| return cached_token | ||||||||||||||
| except Exception as e: | ||||||||||||||
| logger.error(f"Error resolving token: {e}") | ||||||||||||||
| return None | ||||||||||||||
|
|
||||||||||||||
| def _enable_agentframework_instrumentation(self): | ||||||||||||||
| """Enable AgentFramework instrumentation""" | ||||||||||||||
| try: | ||||||||||||||
| AgentFrameworkInstrumentor().instrument() | ||||||||||||||
| logger.info("✅ Instrumentation enabled") | ||||||||||||||
| except Exception as e: | ||||||||||||||
| logger.warning(f"⚠️ Instrumentation failed: {e}") | ||||||||||||||
|
|
||||||||||||||
| # </ObservabilityConfiguration> | ||||||||||||||
|
|
||||||||||||||
| # ========================================================================= | ||||||||||||||
| # MCP SERVER SETUP AND INITIALIZATION | ||||||||||||||
| # MCP SERVER SETUP | ||||||||||||||
| # ========================================================================= | ||||||||||||||
| # <McpServerSetup> | ||||||||||||||
|
|
||||||||||||||
| def _initialize_services(self): | ||||||||||||||
| """Initialize MCP services""" | ||||||||||||||
| try: | ||||||||||||||
| self.tool_service = McpToolRegistrationService() | ||||||||||||||
| logger.info("✅ MCP tool service initialized") | ||||||||||||||
| except Exception as e: | ||||||||||||||
| logger.warning(f"⚠️ MCP tool service failed: {e}") | ||||||||||||||
| self.tool_service = None | ||||||||||||||
|
|
||||||||||||||
| async def setup_mcp_servers(self, auth: Authorization, context: TurnContext): | ||||||||||||||
| async def _create_agent_with_mcp(self, auth: Authorization, context: TurnContext): | ||||||||||||||
| """Set up MCP server connections""" | ||||||||||||||
| if self.mcp_servers_initialized: | ||||||||||||||
| return | ||||||||||||||
|
|
||||||||||||||
| try: | ||||||||||||||
| if not self.tool_service: | ||||||||||||||
| logger.warning("⚠️ MCP tool service unavailable") | ||||||||||||||
| return | ||||||||||||||
| logger.info("Starting MCP server setup...") | ||||||||||||||
|
|
||||||||||||||
| agent_user_id = os.getenv("AGENT_ID", "user123") | ||||||||||||||
| use_agentic_auth = os.getenv("USE_AGENTIC_AUTH", "false").lower() == "true" | ||||||||||||||
|
|
||||||||||||||
| if use_agentic_auth: | ||||||||||||||
| scope = os.getenv("AGENTIC_AUTH_SCOPE") | ||||||||||||||
| if not scope: | ||||||||||||||
| logger.error("❌ AGENTIC_AUTH_SCOPE is required when USE_AGENTIC_AUTH is enabled") | ||||||||||||||
| logger.warning( | ||||||||||||||
| "AGENTIC_AUTH_SCOPE environment variable is not set when USE_AGENTIC_AUTH=true" | ||||||||||||||
JesuTerraz marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||
| ) | ||||||||||||||
| return | ||||||||||||||
| scopes = [scope] | ||||||||||||||
| authToken = await auth.exchange_token(context, scopes, "AGENTIC") | ||||||||||||||
|
|
@@ -222,33 +177,29 @@ async def setup_mcp_servers(self, auth: Authorization, context: TurnContext): | |||||||||||||
| auth_token=self.auth_options.bearer_token, | ||||||||||||||
| turn_context=context, | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| if self.agent: | ||||||||||||||
| logger.info("✅ MCP setup completed") | ||||||||||||||
| self.mcp_servers_initialized = True | ||||||||||||||
| else: | ||||||||||||||
| logger.warning("⚠️ MCP setup failed") | ||||||||||||||
|
|
||||||||||||||
| except Exception as e: | ||||||||||||||
| logger.error(f"MCP setup error: {e}") | ||||||||||||||
|
|
||||||||||||||
| if not self.agent: | ||||||||||||||
| logger.warning("Agent MCP setup returned None, returning agent without servers.") | ||||||||||||||
| self._create_agent() | ||||||||||||||
|
Comment on lines
+184
to
+185
|
||||||||||||||
| logger.warning("Agent MCP setup returned None, returning agent without servers.") | |
| self._create_agent() | |
| logger.warning("MCP setup failed to create agent. Creating basic agent without MCP servers.") | |
| self._create_agent() | |
| else: | |
| logger.info("✅ Agent with MCP servers created successfully") |
Uh oh!
There was an error while loading. Please reload this page.