agent.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from openhands.controller.agent import Agent
  2. from openhands.controller.state.state import State
  3. from openhands.core.config import AgentConfig
  4. from openhands.events.action import Action, AgentDelegateAction, AgentFinishAction
  5. from openhands.events.observation import AgentDelegateObservation
  6. from openhands.llm.llm import LLM
  7. class DelegatorAgent(Agent):
  8. VERSION = '1.0'
  9. """
  10. The Delegator Agent is responsible for delegating tasks to other agents based on the current task.
  11. """
  12. current_delegate: str = ''
  13. def __init__(self, llm: LLM, config: AgentConfig):
  14. """Initialize the Delegator Agent with an LLM
  15. Parameters:
  16. - llm (LLM): The llm to be used by this agent
  17. """
  18. super().__init__(llm, config)
  19. def step(self, state: State) -> Action:
  20. """Checks to see if current step is completed, returns AgentFinishAction if True.
  21. Otherwise, delegates the task to the next agent in the pipeline.
  22. Parameters:
  23. - state (State): The current state given the previous actions and observations
  24. Returns:
  25. - AgentFinishAction: If the last state was 'completed', 'verified', or 'abandoned'
  26. - AgentDelegateAction: The next agent to delegate the task to
  27. """
  28. if self.current_delegate == '':
  29. self.current_delegate = 'study'
  30. task, _ = state.get_current_user_intent()
  31. return AgentDelegateAction(
  32. agent='StudyRepoForTaskAgent', inputs={'task': task}
  33. )
  34. # last observation in history should be from the delegate
  35. last_observation = state.history.get_last_observation()
  36. if not isinstance(last_observation, AgentDelegateObservation):
  37. raise Exception('Last observation is not an AgentDelegateObservation')
  38. goal, _ = state.get_current_user_intent()
  39. if self.current_delegate == 'study':
  40. self.current_delegate = 'coder'
  41. return AgentDelegateAction(
  42. agent='CoderAgent',
  43. inputs={
  44. 'task': goal,
  45. 'summary': last_observation.outputs['summary'],
  46. },
  47. )
  48. elif self.current_delegate == 'coder':
  49. self.current_delegate = 'verifier'
  50. return AgentDelegateAction(
  51. agent='VerifierAgent',
  52. inputs={
  53. 'task': goal,
  54. },
  55. )
  56. elif self.current_delegate == 'verifier':
  57. if (
  58. 'completed' in last_observation.outputs
  59. and last_observation.outputs['completed']
  60. ):
  61. return AgentFinishAction()
  62. else:
  63. self.current_delegate = 'coder'
  64. return AgentDelegateAction(
  65. agent='CoderAgent',
  66. inputs={
  67. 'task': goal,
  68. 'summary': last_observation.outputs['summary'],
  69. },
  70. )
  71. else:
  72. raise Exception('Invalid delegate state')