action_parser.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from abc import ABC, abstractmethod
  2. from openhands.events.action import Action
  3. class ActionParseError(Exception):
  4. """Exception raised when the response from the LLM cannot be parsed into an action."""
  5. def __init__(self, error: str):
  6. self.error = error
  7. def __str__(self):
  8. return self.error
  9. class ResponseParser(ABC):
  10. """This abstract base class is a general interface for an response parser dedicated to
  11. parsing the action from the response from the LLM.
  12. """
  13. def __init__(
  14. self,
  15. ):
  16. # Need pay attention to the item order in self.action_parsers
  17. self.action_parsers = []
  18. @abstractmethod
  19. def parse(self, response: str) -> Action:
  20. """Parses the action from the response from the LLM.
  21. Parameters:
  22. - response (str): The response from the LLM.
  23. Returns:
  24. - action (Action): The action parsed from the response.
  25. """
  26. pass
  27. @abstractmethod
  28. def parse_response(self, response) -> str:
  29. """Parses the action from the response from the LLM.
  30. Parameters:
  31. - response (str): The response from the LLM.
  32. Returns:
  33. - action_str (str): The action str parsed from the response.
  34. """
  35. pass
  36. @abstractmethod
  37. def parse_action(self, action_str: str) -> Action:
  38. """Parses the action from the response from the LLM.
  39. Parameters:
  40. - action_str (str): The response from the LLM.
  41. Returns:
  42. - action (Action): The action parsed from the response.
  43. """
  44. pass
  45. class ActionParser(ABC):
  46. """This abstract base class is a general interface for an action parser dedicated to
  47. parsing the action from the action str from the LLM.
  48. """
  49. @abstractmethod
  50. def check_condition(self, action_str: str) -> bool:
  51. """Check if the action string can be parsed by this parser."""
  52. pass
  53. @abstractmethod
  54. def parse(self, action_str: str) -> Action:
  55. """Parses the action from the action string from the LLM response."""
  56. pass