response_parser.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from openhands.agenthub.codeact_swe_agent.action_parser import (
  2. CodeActSWEActionParserCmdRun,
  3. CodeActSWEActionParserFinish,
  4. CodeActSWEActionParserIPythonRunCell,
  5. CodeActSWEActionParserMessage,
  6. )
  7. from openhands.controller.action_parser import ResponseParser
  8. from openhands.events.action import Action
  9. class CodeActSWEResponseParser(ResponseParser):
  10. """Parser action:
  11. - CmdRunAction(command) - bash command to run
  12. - IPythonRunCellAction(code) - IPython code to run
  13. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  14. - AgentFinishAction() - end the interaction
  15. """
  16. def __init__(self):
  17. # Need pay attention to the item order in self.action_parsers
  18. super().__init__()
  19. self.action_parsers = [
  20. CodeActSWEActionParserFinish(),
  21. CodeActSWEActionParserCmdRun(),
  22. CodeActSWEActionParserIPythonRunCell(),
  23. ]
  24. self.default_parser = CodeActSWEActionParserMessage()
  25. def parse(self, response: str) -> Action:
  26. action_str = self.parse_response(response)
  27. return self.parse_action(action_str)
  28. def parse_response(self, response) -> str:
  29. action = response.choices[0].message.content
  30. if action is None:
  31. return ''
  32. for lang in ['bash', 'ipython']:
  33. if f'<execute_{lang}>' in action and f'</execute_{lang}>' not in action:
  34. action += f'</execute_{lang}>'
  35. return action
  36. def parse_action(self, action_str: str) -> Action:
  37. for action_parser in self.action_parsers:
  38. if action_parser.check_condition(action_str):
  39. return action_parser.parse(action_str)
  40. return self.default_parser.parse(action_str)