response_parser.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from agenthub.codeact_swe_agent.action_parser import (
  2. CodeActSWEActionParserCmdRun,
  3. CodeActSWEActionParserFinish,
  4. CodeActSWEActionParserIPythonRunCell,
  5. CodeActSWEActionParserMessage,
  6. )
  7. from opendevin.controller.action_parser import ResponseParser
  8. from opendevin.events.action import Action
  9. class CodeActSWEResponseParser(ResponseParser):
  10. """
  11. Parser action:
  12. - CmdRunAction(command) - bash command to run
  13. - IPythonRunCellAction(code) - IPython code to run
  14. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  15. - AgentFinishAction() - end the interaction
  16. """
  17. def __init__(
  18. self,
  19. ):
  20. # Need pay attention to the item order in self.action_parsers
  21. self.action_parsers = [
  22. CodeActSWEActionParserFinish(),
  23. CodeActSWEActionParserCmdRun(),
  24. CodeActSWEActionParserIPythonRunCell(),
  25. ]
  26. self.default_parser = CodeActSWEActionParserMessage()
  27. def parse(self, response: str) -> Action:
  28. action_str = self.parse_response(response)
  29. return self.parse_action(action_str)
  30. def parse_response(self, response) -> str:
  31. action = response.choices[0].message.content
  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)