observation.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from openhands.events.observation.agent import AgentStateChangedObservation
  2. from openhands.events.observation.browse import BrowserOutputObservation
  3. from openhands.events.observation.commands import (
  4. CmdOutputObservation,
  5. IPythonRunCellObservation,
  6. )
  7. from openhands.events.observation.delegate import AgentDelegateObservation
  8. from openhands.events.observation.empty import NullObservation
  9. from openhands.events.observation.error import ErrorObservation
  10. from openhands.events.observation.files import (
  11. FileEditObservation,
  12. FileReadObservation,
  13. FileWriteObservation,
  14. )
  15. from openhands.events.observation.observation import Observation
  16. from openhands.events.observation.reject import UserRejectObservation
  17. from openhands.events.observation.success import SuccessObservation
  18. observations = (
  19. NullObservation,
  20. CmdOutputObservation,
  21. IPythonRunCellObservation,
  22. BrowserOutputObservation,
  23. FileReadObservation,
  24. FileWriteObservation,
  25. FileEditObservation,
  26. AgentDelegateObservation,
  27. SuccessObservation,
  28. ErrorObservation,
  29. AgentStateChangedObservation,
  30. UserRejectObservation,
  31. )
  32. OBSERVATION_TYPE_TO_CLASS = {
  33. observation_class.observation: observation_class # type: ignore[attr-defined]
  34. for observation_class in observations
  35. }
  36. def observation_from_dict(observation: dict) -> Observation:
  37. observation = observation.copy()
  38. if 'observation' not in observation:
  39. raise KeyError(f"'observation' key is not found in {observation=}")
  40. observation_class = OBSERVATION_TYPE_TO_CLASS.get(observation['observation'])
  41. if observation_class is None:
  42. raise KeyError(
  43. f"'{observation['observation']=}' is not defined. Available observations: {OBSERVATION_TYPE_TO_CLASS.keys()}"
  44. )
  45. observation.pop('observation')
  46. observation.pop('message', None)
  47. content = observation.pop('content', '')
  48. extras = observation.pop('extras', {})
  49. return observation_class(content=content, **extras)