response_parser.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from openhands.controller.action_parser import ResponseParser
  2. from openhands.core.utils import json
  3. from openhands.events.action import (
  4. Action,
  5. )
  6. from openhands.events.serialization.action import action_from_dict
  7. class PlannerResponseParser(ResponseParser):
  8. def __init__(self):
  9. super().__init__()
  10. def parse(self, response: str) -> Action:
  11. action_str = self.parse_response(response)
  12. return self.parse_action(action_str)
  13. def parse_response(self, response) -> str:
  14. # get the next action from the response
  15. return response['choices'][0]['message']['content']
  16. def parse_action(self, action_str: str) -> Action:
  17. """Parses a string to find an action within it
  18. Parameters:
  19. - response (str): The string to be parsed
  20. Returns:
  21. - Action: The action that was found in the response string
  22. """
  23. # attempt to load the JSON dict from the response
  24. action_dict = json.loads(action_str)
  25. if 'content' in action_dict:
  26. # The LLM gets confused here. Might as well be robust
  27. action_dict['contents'] = action_dict.pop('content')
  28. return action_from_dict(action_dict)