nananie143 commited on
Commit
4128a97
·
1 Parent(s): a74a84f

Fixed missing _execute_agent_task and _execute_paths methods in EnhancedAIFlow

Browse files
Files changed (1) hide show
  1. app.py +167 -81
app.py CHANGED
@@ -366,94 +366,124 @@ class AIFlow:
366
  except Exception as e:
367
  logger.error(f"Flow execution failed: {str(e)}")
368
  raise
369
-
370
  async def _execute_paths(self, paths: List[List[AgentRole]]):
371
- """Execute multiple paths through the flow in parallel."""
372
- path_tasks = [self._execute_path(path) for path in paths]
373
- await asyncio.gather(*path_tasks)
374
-
375
- async def _execute_path(self, path: List[AgentRole]):
376
- """Execute a single path through the flow."""
377
- for role in path:
378
- context = self.contexts[role]
379
- if context.state != FlowState.COMPLETED:
380
- await self._execute_agent(role)
381
-
382
- async def _execute_agent(self, role: AgentRole):
383
- """Execute a single agent's tasks."""
384
- context = self.contexts[role]
385
- context.state = FlowState.RUNNING
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
 
 
 
 
387
  try:
388
- # Get agent-specific prompt
389
- prompt = self._get_agent_prompt(role)
390
 
391
- # Execute agent's task
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  if role == AgentRole.ARCHITECT:
393
- result = await self._execute_architect(prompt)
394
  elif role == AgentRole.UI_DESIGNER:
395
- result = await self._execute_ui_designer(prompt)
396
  elif role == AgentRole.BACKEND_DEVELOPER:
397
- result = await self._execute_backend_developer(prompt)
398
- # ... (similar for other roles)
 
 
 
 
 
 
 
 
 
 
 
399
 
400
- # Store results in context
401
- context.artifacts["output"] = result
402
- context.state = FlowState.COMPLETED
 
 
403
 
 
404
  except Exception as e:
405
- context.state = FlowState.FAILED
406
- context.feedback.append(str(e))
407
  raise
408
 
409
- def _get_agent_prompt(self, role: AgentRole) -> str:
410
- """Get the appropriate prompt template for each agent role."""
411
- prompts = {
412
- AgentRole.ARCHITECT: """You are a Software Architect designing a scalable application.
413
- Requirements: {requirements}
414
-
415
- Focus on:
416
- 1. System architecture
417
- 2. Component interactions
418
- 3. Technology stack selection
419
- 4. Scalability considerations
420
- 5. Integration patterns
421
-
422
- Provide:
423
- - High-level architecture diagram
424
- - Component breakdown
425
- - Technology recommendations
426
- - Integration patterns
427
- - Performance considerations""",
428
- # ... (other role-specific prompts)
429
- }
430
-
431
- base_prompt = prompts.get(role, "")
432
- return base_prompt.format(**self.global_context)
433
-
434
- async def _execute_architect(self, prompt: str) -> str:
435
- """Execute the Architect agent's tasks."""
436
- agent = get_agent("architect")
437
- return agent.run(prompt)
438
-
439
- async def _execute_ui_designer(self, prompt: str) -> str:
440
- """Execute the UI Designer agent's tasks."""
441
- agent = get_agent("ui_designer")
442
- return agent.run(prompt)
443
-
444
- # ... (similar methods for other roles)
445
-
446
- def _compile_results(self) -> str:
447
- """Compile the results from all agents into a final output."""
448
- results = []
449
- for role, context in self.contexts.items():
450
- if context.state == FlowState.COMPLETED:
451
- results.append(f"## {role.value.replace('_', ' ').title()} Output")
452
- results.append(context.artifacts.get("output", "No output available"))
453
- results.append("")
454
-
455
- return "\n".join(results)
456
-
457
  @dataclass
458
  class FileContext:
459
  """Context for file operations and tracking."""
@@ -727,14 +757,66 @@ class EnhancedAIFlow(AIFlow):
727
  self.file_manager = FileOperationManager(self.context_manager)
728
  self.command_manager = CommandManager(self.context_manager)
729
  self.rule_system = RuleSystem()
730
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731
  async def execute_flow(self, requirements: str):
732
  """Execute the AI Flow and build the project."""
733
  try:
734
- # Execute normal flow
735
- results = await super().execute_flow(requirements)
 
 
736
 
737
- # Extract app name and generate documentation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
738
  app_name = requirements.split()[0].lower().replace(" ", "_")
739
 
740
  # Create basic project structure
@@ -766,6 +848,9 @@ class EnhancedAIFlow(AIFlow):
766
  # Create download
767
  download_path = self.output_manager.create_download(app_name)
768
 
 
 
 
769
  # Add download information to results
770
  results += f"""
771
  ## Download
@@ -784,6 +869,7 @@ The following files have been created:
784
  results += f"- {rel_path}\n"
785
 
786
  return results
 
787
  except Exception as e:
788
  logger.error(f"Enhanced flow execution failed: {str(e)}")
789
  raise
@@ -833,7 +919,7 @@ async def multi_agent_workflow(requirements: str) -> str:
833
  flow = EnhancedAIFlow()
834
  results = await flow.execute_flow(requirements)
835
 
836
- # Extract app name and generate documentation
837
  app_name = requirements.split()[0].lower().replace(" ", "_")
838
 
839
  # Generate project structure and documentation
 
366
  except Exception as e:
367
  logger.error(f"Flow execution failed: {str(e)}")
368
  raise
369
+
370
  async def _execute_paths(self, paths: List[List[AgentRole]]):
371
+ """Execute all paths in the flow graph."""
372
+ try:
373
+ results = []
374
+ for path in paths:
375
+ path_results = []
376
+ for role in path:
377
+ # Get the agent's prompt based on previous results
378
+ prompt = self._generate_prompt(role, path_results)
379
+
380
+ # Execute the agent's task
381
+ result = await self._execute_agent_task(role, prompt)
382
+ path_results.append(result)
383
+
384
+ # Store result in context
385
+ self.context_manager.add_memory(
386
+ f"{role.value}_result",
387
+ result,
388
+ {"timestamp": datetime.now()}
389
+ )
390
+
391
+ results.extend(path_results)
392
+
393
+ # Store all results in context
394
+ self.context_manager.add_memory(
395
+ "path_results",
396
+ results,
397
+ {"timestamp": datetime.now()}
398
+ )
399
+
400
+ return results
401
+ except Exception as e:
402
+ logger.error(f"Failed to execute paths: {str(e)}")
403
+ raise
404
+
405
+ def _generate_prompt(self, role: AgentRole, previous_results: List[str]) -> str:
406
+ """Generate a prompt for an agent based on previous results."""
407
+ requirements = self.context_manager.global_context.get("requirements", "")
408
+
409
+ # Base prompt with requirements
410
+ prompt = f"Requirements: {requirements}\n\n"
411
+
412
+ # Add context from previous results
413
+ if previous_results:
414
+ prompt += "Previous work:\n"
415
+ for i, result in enumerate(previous_results):
416
+ prompt += f"{i+1}. {result}\n"
417
+
418
+ # Add role-specific instructions
419
+ if role == AgentRole.ARCHITECT:
420
+ prompt += "\nAs the Architect, design the high-level system architecture."
421
+ elif role == AgentRole.UI_DESIGNER:
422
+ prompt += "\nAs the UI Designer, create the user interface design."
423
+ elif role == AgentRole.BACKEND_DEVELOPER:
424
+ prompt += "\nAs the Backend Developer, implement the server-side logic."
425
+ elif role == AgentRole.DATABASE_ENGINEER:
426
+ prompt += "\nAs the Database Engineer, design the data model and storage."
427
+ elif role == AgentRole.SECURITY_EXPERT:
428
+ prompt += "\nAs the Security Expert, ensure security best practices."
429
+ elif role == AgentRole.QA_ENGINEER:
430
+ prompt += "\nAs the QA Engineer, create test cases and validation."
431
+ elif role == AgentRole.DEVOPS_ENGINEER:
432
+ prompt += "\nAs the DevOps Engineer, set up deployment and CI/CD."
433
+ elif role == AgentRole.DOCUMENTATION_WRITER:
434
+ prompt += "\nAs the Documentation Writer, create comprehensive documentation."
435
 
436
+ return prompt
437
+
438
+ def _compile_results(self) -> str:
439
+ """Compile all results into a final output."""
440
  try:
441
+ results = []
 
442
 
443
+ # Get all results from memory
444
+ for role in AgentRole:
445
+ result = self.context_manager.get_memory(f"{role.value}_result")
446
+ if result:
447
+ results.append(f"## {role.value}\n{result['value']}\n")
448
+
449
+ return "\n".join(results)
450
+ except Exception as e:
451
+ logger.error(f"Failed to compile results: {str(e)}")
452
+ raise
453
+
454
+ async def _execute_agent_task(self, role: AgentRole, prompt: str) -> str:
455
+ """Execute a specific agent's task with the given prompt."""
456
+ try:
457
  if role == AgentRole.ARCHITECT:
458
+ agent = get_agent("architect")
459
  elif role == AgentRole.UI_DESIGNER:
460
+ agent = get_agent("ui_designer")
461
  elif role == AgentRole.BACKEND_DEVELOPER:
462
+ agent = get_agent("backend_developer")
463
+ elif role == AgentRole.DATABASE_ENGINEER:
464
+ agent = get_agent("database_engineer")
465
+ elif role == AgentRole.SECURITY_EXPERT:
466
+ agent = get_agent("security_expert")
467
+ elif role == AgentRole.QA_ENGINEER:
468
+ agent = get_agent("qa_engineer")
469
+ elif role == AgentRole.DEVOPS_ENGINEER:
470
+ agent = get_agent("devops_engineer")
471
+ elif role == AgentRole.DOCUMENTATION_WRITER:
472
+ agent = get_agent("documentation_writer")
473
+ else:
474
+ raise ValueError(f"Unknown agent role: {role}")
475
 
476
+ # Execute the agent's task
477
+ result = agent.run(prompt)
478
+
479
+ # Log the execution
480
+ logger.info(f"Agent {role.value} completed task")
481
 
482
+ return result
483
  except Exception as e:
484
+ logger.error(f"Agent {role.value} failed: {str(e)}")
 
485
  raise
486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  @dataclass
488
  class FileContext:
489
  """Context for file operations and tracking."""
 
757
  self.file_manager = FileOperationManager(self.context_manager)
758
  self.command_manager = CommandManager(self.context_manager)
759
  self.rule_system = RuleSystem()
760
+
761
+ async def _execute_agent_task(self, role: AgentRole, prompt: str) -> str:
762
+ """Execute a specific agent's task with the given prompt."""
763
+ try:
764
+ if role == AgentRole.ARCHITECT:
765
+ agent = get_agent("architect")
766
+ elif role == AgentRole.UI_DESIGNER:
767
+ agent = get_agent("ui_designer")
768
+ elif role == AgentRole.BACKEND_DEVELOPER:
769
+ agent = get_agent("backend_developer")
770
+ elif role == AgentRole.DATABASE_ENGINEER:
771
+ agent = get_agent("database_engineer")
772
+ elif role == AgentRole.SECURITY_EXPERT:
773
+ agent = get_agent("security_expert")
774
+ elif role == AgentRole.QA_ENGINEER:
775
+ agent = get_agent("qa_engineer")
776
+ elif role == AgentRole.DEVOPS_ENGINEER:
777
+ agent = get_agent("devops_engineer")
778
+ elif role == AgentRole.DOCUMENTATION_WRITER:
779
+ agent = get_agent("documentation_writer")
780
+ else:
781
+ raise ValueError(f"Unknown agent role: {role}")
782
+
783
+ # Execute the agent's task
784
+ result = agent.run(prompt)
785
+
786
+ # Log the execution
787
+ logger.info(f"Agent {role.value} completed task")
788
+
789
+ return result
790
+ except Exception as e:
791
+ logger.error(f"Agent {role.value} failed: {str(e)}")
792
+ raise
793
+
794
  async def execute_flow(self, requirements: str):
795
  """Execute the AI Flow and build the project."""
796
  try:
797
+ # Initialize flow with context
798
+ self.initialize_flow()
799
+ self.global_context["requirements"] = requirements
800
+ self.context_manager.global_context.update(self.global_context)
801
 
802
+ # Add memory of requirements
803
+ self.context_manager.add_memory(
804
+ "requirements",
805
+ requirements,
806
+ {"timestamp": datetime.now()}
807
+ )
808
+
809
+ # Get all paths through the flow graph
810
+ paths = list(nx.all_simple_paths(
811
+ self.flow_graph,
812
+ AgentRole.ARCHITECT,
813
+ AgentRole.DOCUMENTATION_WRITER
814
+ ))
815
+
816
+ # Execute paths with enhanced context
817
+ await self._execute_paths(paths)
818
+
819
+ # Extract app name
820
  app_name = requirements.split()[0].lower().replace(" ", "_")
821
 
822
  # Create basic project structure
 
848
  # Create download
849
  download_path = self.output_manager.create_download(app_name)
850
 
851
+ # Compile results
852
+ results = self._compile_results()
853
+
854
  # Add download information to results
855
  results += f"""
856
  ## Download
 
869
  results += f"- {rel_path}\n"
870
 
871
  return results
872
+
873
  except Exception as e:
874
  logger.error(f"Enhanced flow execution failed: {str(e)}")
875
  raise
 
919
  flow = EnhancedAIFlow()
920
  results = await flow.execute_flow(requirements)
921
 
922
+ # Extract app name
923
  app_name = requirements.split()[0].lower().replace(" ", "_")
924
 
925
  # Generate project structure and documentation