fileop.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. from dataclasses import dataclass
  3. from opendevin.observation import FileReadObservation, FileWriteObservation
  4. from opendevin.schema import ActionType
  5. from opendevin import config
  6. from .base import ExecutableAction
  7. SANDBOX_PATH_PREFIX = '/workspace/'
  8. def resolve_path(file_path):
  9. if file_path.startswith(SANDBOX_PATH_PREFIX):
  10. # Sometimes LLMs include the absolute path of the file inside the sandbox
  11. file_path = file_path[len(SANDBOX_PATH_PREFIX):]
  12. return os.path.join(config.get('WORKSPACE_BASE'), file_path)
  13. @dataclass
  14. class FileReadAction(ExecutableAction):
  15. path: str
  16. action: str = ActionType.READ
  17. def run(self, controller) -> FileReadObservation:
  18. path = resolve_path(self.path)
  19. with open(path, 'r', encoding='utf-8') as file:
  20. return FileReadObservation(path=path, content=file.read())
  21. @property
  22. def message(self) -> str:
  23. return f'Reading file: {self.path}'
  24. @dataclass
  25. class FileWriteAction(ExecutableAction):
  26. path: str
  27. content: str
  28. action: str = ActionType.WRITE
  29. def run(self, controller) -> FileWriteObservation:
  30. whole_path = resolve_path(self.path)
  31. with open(whole_path, 'w', encoding='utf-8') as file:
  32. file.write(self.content)
  33. return FileWriteObservation(content='', path=self.path)
  34. @property
  35. def message(self) -> str:
  36. return f'Writing file: {self.path}'