action.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from openhands.core.exceptions import LLMMalformedActionError
  2. from openhands.events.action.action import Action
  3. from openhands.events.action.agent import (
  4. AgentDelegateAction,
  5. AgentFinishAction,
  6. AgentRejectAction,
  7. ChangeAgentStateAction,
  8. )
  9. from openhands.events.action.browse import BrowseInteractiveAction, BrowseURLAction
  10. from openhands.events.action.commands import (
  11. CmdRunAction,
  12. IPythonRunCellAction,
  13. )
  14. from openhands.events.action.empty import NullAction
  15. from openhands.events.action.files import FileReadAction, FileWriteAction
  16. from openhands.events.action.message import MessageAction
  17. from openhands.events.action.tasks import AddTaskAction, ModifyTaskAction
  18. actions = (
  19. NullAction,
  20. CmdRunAction,
  21. IPythonRunCellAction,
  22. BrowseURLAction,
  23. BrowseInteractiveAction,
  24. FileReadAction,
  25. FileWriteAction,
  26. AgentFinishAction,
  27. AgentRejectAction,
  28. AgentDelegateAction,
  29. AddTaskAction,
  30. ModifyTaskAction,
  31. ChangeAgentStateAction,
  32. MessageAction,
  33. )
  34. ACTION_TYPE_TO_CLASS = {action_class.action: action_class for action_class in actions} # type: ignore[attr-defined]
  35. def action_from_dict(action: dict) -> Action:
  36. if not isinstance(action, dict):
  37. raise LLMMalformedActionError('action must be a dictionary')
  38. action = action.copy()
  39. if 'action' not in action:
  40. raise LLMMalformedActionError(f"'action' key is not found in {action=}")
  41. if not isinstance(action['action'], str):
  42. raise LLMMalformedActionError(
  43. f"'{action['action']=}' is not defined. Available actions: {ACTION_TYPE_TO_CLASS.keys()}"
  44. )
  45. action_class = ACTION_TYPE_TO_CLASS.get(action['action'])
  46. if action_class is None:
  47. raise LLMMalformedActionError(
  48. f"'{action['action']=}' is not defined. Available actions: {ACTION_TYPE_TO_CLASS.keys()}"
  49. )
  50. args = action.get('args', {})
  51. try:
  52. decoded_action = action_class(**args)
  53. if 'timeout' in action:
  54. decoded_action.timeout = action['timeout']
  55. except TypeError:
  56. raise LLMMalformedActionError(f'action={action} has the wrong arguments')
  57. return decoded_action