Skip to content

Commit cc6eeee

Browse files
resolved the pylint issues
1 parent e83adbf commit cc6eeee

File tree

5 files changed

+49
-55
lines changed

5 files changed

+49
-55
lines changed

src/backend/app_kernel.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,33 +19,30 @@
1919
# Azure monitoring
2020

2121
# Semantic Kernel imports
22-
from v3.orchestration.orchestration_manager import OrchestrationManager
2322
from v3.config.agent_registry import agent_registry
2423

24+
2525
@asynccontextmanager
2626
async def lifespan(app: FastAPI):
2727
"""Manage FastAPI application lifecycle - startup and shutdown."""
2828
logger = logging.getLogger(__name__)
29-
29+
3030
# Startup
3131
logger.info("🚀 Starting MACAE application...")
3232
yield
33-
33+
3434
# Shutdown
3535
logger.info("🛑 Shutting down MACAE application...")
3636
try:
37-
# Import here to avoid circular imports and get agent registry
38-
39-
4037
# Clean up all agents from Azure AI Foundry when container stops
4138
await agent_registry.cleanup_all_agents()
4239
logger.info("✅ Agent cleanup completed successfully")
43-
40+
4441
except ImportError as ie:
4542
logger.error(f"❌ Could not import agent_registry: {ie}")
4643
except Exception as e:
4744
logger.error(f"❌ Error during shutdown cleanup: {e}")
48-
45+
4946
logger.info("👋 MACAE application shutdown complete")
5047

5148

src/backend/common/utils/utils_kernel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ async def create_RAI_agent() -> FoundryAgentTemplate:
5151

5252
try:
5353
agent_registry.register_agent(agent)
54-
54+
5555
except Exception as registry_error:
5656
logging.warning(f"Failed to register agent '{agent.agent_name}' with registry: {registry_error}")
5757
return agent

src/backend/v3/config/agent_registry.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010

1111
class AgentRegistry:
1212
"""Global registry for tracking and managing all agent instances across the application."""
13-
13+
1414
def __init__(self):
1515
self.logger = logging.getLogger(__name__)
1616
self._lock = threading.Lock()
1717
self._all_agents: WeakSet = WeakSet()
1818
self._agent_metadata: Dict[int, Dict[str, Any]] = {}
19-
19+
2020
def register_agent(self, agent: Any, user_id: Optional[str] = None) -> None:
2121
"""Register an agent instance for tracking and lifecycle management."""
2222
with self._lock:
@@ -31,7 +31,7 @@ def register_agent(self, agent: Any, user_id: Optional[str] = None) -> None:
3131
self.logger.info(f"Registered agent: {type(agent).__name__} (ID: {agent_id}, User: {user_id})")
3232
except Exception as e:
3333
self.logger.error(f"Failed to register agent: {e}")
34-
34+
3535
def unregister_agent(self, agent: Any) -> None:
3636
"""Unregister an agent instance."""
3737
with self._lock:
@@ -43,34 +43,34 @@ def unregister_agent(self, agent: Any) -> None:
4343
self.logger.info(f"Unregistered agent: {metadata.get('type', 'Unknown')} (ID: {agent_id})")
4444
except Exception as e:
4545
self.logger.error(f"Failed to unregister agent: {e}")
46-
46+
4747
def get_all_agents(self) -> List[Any]:
4848
"""Get all currently registered agents."""
4949
with self._lock:
5050
return list(self._all_agents)
51-
51+
5252
def get_agent_count(self) -> int:
5353
"""Get the total number of registered agents."""
5454
with self._lock:
5555
return len(self._all_agents)
56-
56+
5757
async def cleanup_all_agents(self) -> None:
5858
"""Clean up all registered agents across all users."""
5959
all_agents = self.get_all_agents()
60-
60+
6161
if not all_agents:
6262
self.logger.info("No agents to clean up")
6363
return
64-
64+
6565
self.logger.info(f"🧹 Starting cleanup of {len(all_agents)} total agents")
66-
66+
6767
# Log agent details for debugging
6868
for i, agent in enumerate(all_agents):
6969
agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__))
7070
agent_type = type(agent).__name__
7171
has_close = hasattr(agent, 'close')
72-
self.logger.info(f"Agent {i+1}: {agent_name} (Type: {agent_type}, Has close(): {has_close})")
73-
72+
self.logger.info(f"Agent {i + 1}: {agent_name} (Type: {agent_type}, Has close(): {has_close})")
73+
7474
# Clean up agents concurrently
7575
cleanup_tasks = []
7676
for agent in all_agents:
@@ -80,59 +80,59 @@ async def cleanup_all_agents(self) -> None:
8080
agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__))
8181
self.logger.warning(f"⚠️ Agent {agent_name} has no close() method - just unregistering from registry")
8282
self.unregister_agent(agent)
83-
83+
8484
if cleanup_tasks:
8585
self.logger.info(f"🔄 Executing {len(cleanup_tasks)} cleanup tasks...")
8686
results = await asyncio.gather(*cleanup_tasks, return_exceptions=True)
87-
87+
8888
# Log any exceptions that occurred during cleanup
8989
success_count = 0
9090
for i, result in enumerate(results):
9191
if isinstance(result, Exception):
9292
self.logger.error(f"❌ Error cleaning up agent {i}: {result}")
9393
else:
9494
success_count += 1
95-
95+
9696
self.logger.info(f"✅ Successfully cleaned up {success_count}/{len(cleanup_tasks)} agents")
97-
97+
9898
# Clear all tracking
9999
with self._lock:
100100
self._all_agents.clear()
101101
self._agent_metadata.clear()
102-
102+
103103
self.logger.info("🎉 Completed cleanup of all agents")
104-
104+
105105
async def _safe_close_agent(self, agent: Any) -> None:
106106
"""Safely close an agent with error handling."""
107107
try:
108108
agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__))
109109
self.logger.info(f"Closing agent: {agent_name}")
110-
110+
111111
# Call the agent's close method - it should handle Azure deletion and registry cleanup
112112
if asyncio.iscoroutinefunction(agent.close):
113113
await agent.close()
114114
else:
115115
agent.close()
116-
116+
117117
self.logger.info(f"Successfully closed agent: {agent_name}")
118-
118+
119119
except Exception as e:
120120
agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__))
121121
self.logger.error(f"Failed to close agent {agent_name}: {e}")
122-
122+
123123
def get_registry_status(self) -> Dict[str, Any]:
124124
"""Get current status of the agent registry for debugging and monitoring."""
125125
with self._lock:
126126
status = {
127127
'total_agents': len(self._all_agents),
128128
'agent_types': {}
129129
}
130-
130+
131131
# Count agents by type
132132
for agent in self._all_agents:
133133
agent_type = type(agent).__name__
134134
status['agent_types'][agent_type] = status['agent_types'].get(agent_type, 0) + 1
135-
135+
136136
return status
137137

138138

src/backend/v3/magentic_agents/common/lifecycle.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -123,30 +123,28 @@ async def close(self) -> None:
123123
Close the agent and clean up Azure AI Foundry resources.
124124
This method deletes the agent from Azure AI Foundry and closes credentials.
125125
"""
126-
126+
127127
try:
128128
# Delete agent from Azure AI Foundry if we have the necessary information
129129
if hasattr(self, '_agent') and self._agent and hasattr(self._agent, 'definition'):
130130
agent_id = getattr(self._agent.definition, 'id', None)
131-
agent_name = getattr(self, 'agent_name', 'Unknown')
132-
131+
133132
if agent_id and self.client:
134133
try:
135134
await self.client.agents.delete_agent(agent_id)
136-
except Exception as delete_error:
135+
except Exception:
137136
pass
138137
# Unregister from agent registry
139138
try:
140139
agent_registry.unregister_agent(self)
141-
except Exception as registry_error:
140+
except Exception:
142141
pass
143-
except Exception as cleanup_error:
142+
except Exception:
144143
pass
145144
# Always close credentials and parent resources
146145
try:
147146
if hasattr(self, 'creds') and self.creds:
148147
await self.creds.close()
149-
except Exception as creds_error:
150-
pass
148+
except Exception:
149+
pass
151150
await super().close()
152-

src/backend/v3/magentic_agents/foundry_agent.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -145,15 +145,15 @@ async def _after_open(self) -> None:
145145

146146
# Try to get existing agent definition from Foundry
147147
definition = await self._get_azure_ai_agent_definition(self.agent_name)
148-
148+
149149
# Check if existing definition uses the same connection name
150150
if definition is not None:
151151
connection_compatible = await self._check_connection_compatibility(definition)
152152
if not connection_compatible:
153153
await self.client.agents.delete_agent(definition.id)
154154
self.logger.info(f"Existing agent '{self.agent_name}' uses different connection. Creating new agent definition.")
155155
definition = None
156-
156+
157157
# If not found in Foundry, create a new one
158158
if definition is None:
159159
# Collect all tools
@@ -223,14 +223,13 @@ async def fetch_run_details(self, thread_id: str, run_id: str):
223223
except Exception as ex:
224224
self.logger.error("Could not fetch run details: %s", ex)
225225

226-
227226
async def _check_connection_compatibility(self, existing_definition) -> bool:
228227
"""
229228
Check if the existing agent definition uses the same connection name as the current configuration.
230-
229+
231230
Args:
232231
existing_definition: The existing agent definition from Azure AI Foundry
233-
232+
234233
Returns:
235234
bool: True if connections are compatible, False otherwise
236235
"""
@@ -239,44 +238,44 @@ async def _check_connection_compatibility(self, existing_definition) -> bool:
239238
if not self.search or not self.search.connection_name:
240239
self.logger.info("No search configuration to compare")
241240
return True
242-
241+
243242
# Get tool resources from existing definition
244243
if not hasattr(existing_definition, 'tool_resources') or not existing_definition.tool_resources:
245244
self.logger.info("Existing definition has no tool resources")
246245
return not self.search.connection_name # Compatible if we also don't need search
247-
246+
248247
# Check Azure AI Search tool resources
249248
azure_ai_search_resources = existing_definition.tool_resources.get('azure_ai_search', {})
250249
if not azure_ai_search_resources:
251250
self.logger.info("Existing definition has no Azure AI Search resources")
252251
return not self.search.connection_name # Compatible if we also don't need search
253-
252+
254253
# Get connection ID from existing definition
255254
indexes = azure_ai_search_resources.get('indexes')[0]
256255
existing_connection_id = indexes.get('index_connection_id')
257256
if not existing_connection_id:
258257
self.logger.info("Existing definition has no connection ID")
259258
return False
260-
259+
261260
# Get the current connection to compare
262261
try:
263262
current_connection = await self.client.connections.get(name=self.search.connection_name)
264263
current_connection_id = current_connection.id
265-
264+
266265
# Compare connection IDs
267266
is_compatible = existing_connection_id == current_connection_id
268-
267+
269268
if is_compatible:
270269
self.logger.info(f"Connection compatible: existing connection ID {existing_connection_id} matches current connection")
271270
else:
272271
self.logger.info(f"Connection mismatch: existing connection ID {existing_connection_id} != current connection ID {current_connection_id}")
273-
272+
274273
return is_compatible
275-
274+
276275
except Exception as conn_ex:
277276
self.logger.error(f"Failed to get current connection '{self.search.connection_name}': {conn_ex}")
278277
return False
279-
278+
280279
except Exception as ex:
281280
self.logger.error(f"Error checking connection compatibility: {ex}")
282281
return False

0 commit comments

Comments
 (0)