controller.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from opendevin.lib.command_manager import CommandManager
  2. from opendevin.lib.event import Event
  3. def print_callback(event):
  4. print(event, flush=True)
  5. class AgentController:
  6. def __init__(self, agent, max_iterations=100, callbacks=[]):
  7. self.agent = agent
  8. self.max_iterations = max_iterations
  9. self.background_commands = []
  10. self.command_manager = CommandManager()
  11. self.callbacks = callbacks
  12. self.callbacks.append(self.agent.add_event)
  13. self.callbacks.append(print_callback)
  14. def maybe_perform_action(self, event):
  15. if not (event and event.is_runnable()):
  16. return
  17. action = 'output'
  18. try:
  19. output = event.run(self)
  20. except Exception as e:
  21. output = 'Error: ' + str(e)
  22. action = 'error'
  23. out_event = Event(action, {'output': output})
  24. return out_event
  25. def start_loop(self):
  26. output = None
  27. for i in range(self.max_iterations):
  28. print("STEP", i, flush=True)
  29. log_events = self.command_manager.get_background_events()
  30. for event in log_events:
  31. for callback in self.callbacks:
  32. callback(event)
  33. action_event = self.agent.step(self.command_manager)
  34. for callback in self.callbacks:
  35. callback(action_event)
  36. if action_event.action == 'finish':
  37. break
  38. print("---", flush=True)
  39. output_event = self.maybe_perform_action(action_event)
  40. if output_event is not None:
  41. for callback in self.callbacks:
  42. callback(output_event)
  43. print("==============", flush=True)