-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Implement base AIOrchestrator for agent coordination #10
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,56 +1,39 @@ | ||
| import asyncio | ||
| import logging | ||
| from typing import Dict, Callable, Awaitable | ||
| from backend.app.services.report_service import save_report_data | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| class AIOrchestrator: | ||
| """ | ||
| Base class for coordinating multiple AI agents. | ||
| Designed to handle parallel asynchronous agent calls. | ||
| """ | ||
|
|
||
| class Orchestrator: | ||
| def __init__(self): | ||
| self.registered_agents: Dict[str, Callable[[str, str], Awaitable[Dict]]] = {} | ||
|
|
||
| def register_agent(self, name: str, agent_func: Callable[[str, str], Awaitable[Dict]]): | ||
| self.registered_agents[name] = agent_func | ||
|
|
||
| async def execute_agents_concurrently(self, report_id: str, token_id: str): | ||
| agent_tasks = [] | ||
| agent_names = [] | ||
|
|
||
| for name, agent_func in self.registered_agents.items(): | ||
| agent_names.append(name) | ||
| agent_tasks.append(self._run_agent_safely(name, agent_func, report_id, token_id)) | ||
|
|
||
| results = await asyncio.gather(*agent_tasks, return_exceptions=True) | ||
|
|
||
| aggregated_results = {} | ||
| for i, result in enumerate(results): | ||
| agent_name = agent_names[i] | ||
| if isinstance(result, Exception): | ||
| logger.error("Agent '%s' failed with error: %s", agent_name, result, exc_info=isinstance(result, BaseException)) | ||
| aggregated_results[agent_name] = {'status': 'failed', 'error': str(result)} | ||
| else: | ||
| aggregated_results[agent_name] = {'status': 'completed', 'data': result} | ||
|
|
||
| failed_count = sum(1 for r in aggregated_results.values() if r['status'] == 'failed') | ||
| total = len(aggregated_results) | ||
| if failed_count == total: | ||
| overall_status = 'failed' | ||
| elif failed_count > 0: | ||
| overall_status = 'partial_success' | ||
| else: | ||
| overall_status = 'completed' | ||
|
|
||
| await save_report_data(report_id, { | ||
| 'agent_results': aggregated_results, | ||
| 'status': overall_status, | ||
| 'summary': {'total': total, 'success': total - failed_count, 'failed': failed_count} | ||
| }) | ||
|
|
||
| async def _run_agent_safely(self, name: str, agent_func: Callable[[str, str], Awaitable[Dict]], report_id: str, token_id: str) -> Dict: | ||
| try: | ||
| return await agent_func(report_id, token_id) | ||
| except Exception as e: | ||
| logger.error("Error running agent '%s': %s", name, e, exc_info=True) | ||
| raise # Re-raise to be caught by asyncio.gather | ||
|
|
||
| orchestrator = Orchestrator() | ||
| self.agents = [] | ||
|
|
||
| def register_agent(self, agent): | ||
| """ | ||
| Registers an AI agent with the orchestrator. | ||
| Args: | ||
| agent: An instance of an AI agent. | ||
| """ | ||
| raise NotImplementedError | ||
|
|
||
| async def execute_agents(self, *args, **kwargs): | ||
| """ | ||
| Executes all registered AI agents in parallel asynchronously. | ||
| Args: | ||
| *args: Variable length argument list for agent execution. | ||
| **kwargs: Arbitrary keyword arguments for agent execution. | ||
| Returns: | ||
| A list of results from each agent. | ||
| """ | ||
| raise NotImplementedError | ||
|
|
||
| def aggregate_results(self, results): | ||
| """ | ||
| Aggregates the results from the executed AI agents. | ||
| Args: | ||
| results (list): A list of results from the executed agents. | ||
| Returns: | ||
| The aggregated result. | ||
| """ | ||
| raise NotImplementedError | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Abstract method + suggested default concurrent pattern.
Make the API abstract; if you prefer a default, use gather with a snapshot.
Optional default implementation:
Verify call-site breakages from prior API:
🏁 Script executed:
Length of output: 2500
🏁 Script executed:
Length of output: 1123
🏁 Script executed:
Length of output: 442
🏁 Script executed:
Length of output: 0
🏁 Script executed:
Length of output: 647
🏁 Script executed:
Length of output: 0
🏁 Script executed:
Length of output: 23
🏁 Script executed:
Length of output: 60
🏁 Script executed:
Length of output: 2876
Critical API inconsistencies prevent code execution; incomplete refactoring.
The review suggestion to add
@abstractmethodis valid but incomplete. Multiple breaking issues exist:Import failure: Tests import
Orchestratorbut orchestrator.py definesAIOrchestrator—class name mismatch.Missing method: All call sites invoke
execute_agents_concurrently()(test lines 27, 52; routes line 36), but onlyexecute_agents()exists in the base class. The called method doesn't exist in the codebase.Signature mismatch: Base class defines
register_agent(self, agent)with one parameter, but tests callorchestrator.register_agent("AgentOne", mock_agent_one)with two parameters (name, agent).Missing concrete implementation: No
Orchestratorclass or implementation ofexecute_agents_concurrently()found anywhere.Tests will fail immediately on import.