fileop.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. from dataclasses import dataclass
  3. from opendevin.observation import Observation
  4. from .base import ExecutableAction
  5. # This is the path where the workspace is mounted in the container
  6. # The LLM sometimes returns paths with this prefix, so we need to remove it
  7. PATH_PREFIX = "/workspace/"
  8. def resolve_path(base_path, file_path):
  9. if file_path.startswith(PATH_PREFIX):
  10. file_path = file_path[len(PATH_PREFIX):]
  11. return os.path.join(base_path, file_path)
  12. @dataclass
  13. class FileReadAction(ExecutableAction):
  14. path: str
  15. base_path: str = ""
  16. def run(self, *args, **kwargs) -> Observation:
  17. path = resolve_path(self.base_path, self.path)
  18. with open(path, 'r') as file:
  19. return Observation(file.read())
  20. @property
  21. def message(self) -> str:
  22. return f"Reading file: {self.path}"
  23. @dataclass
  24. class FileWriteAction(ExecutableAction):
  25. path: str
  26. contents: str
  27. base_path: str = ""
  28. def run(self, *args, **kwargs) -> Observation:
  29. path = resolve_path(self.base_path, self.path)
  30. with open(path, 'w') as file:
  31. file.write(self.contents)
  32. return Observation(f"File written to {path}")
  33. @property
  34. def message(self) -> str:
  35. return f"Writing file: {self.path}"