Skip to content

Commit c4ff686

Browse files
vriaeyurtsev
andauthored
WriteFileTool should create not existent parent dirs in file_path (#132)
This PR updates the WriteFileTool to ensure that all missing parent directories are created when writing a file. The current tool creates only one immediate parent directory. This causes failures in my workflow because I expect my agents to create many files in many dirs. --------- Co-authored-by: Eugene Yurtsev <[email protected]>
1 parent fdd86e3 commit c4ff686

File tree

2 files changed

+9
-1
lines changed
  • libs/community

2 files changed

+9
-1
lines changed

libs/community/langchain_community/tools/file_management/write.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _run(
4040
except FileValidationError:
4141
return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path)
4242
try:
43-
write_path.parent.mkdir(exist_ok=True, parents=False)
43+
write_path.parent.mkdir(exist_ok=True, parents=True)
4444
mode = "a" if append else "w"
4545
with write_path.open(mode, encoding="utf-8") as f:
4646
f.write(text)

libs/community/tests/unit_tests/tools/file_management/test_write.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,11 @@ def test_write_file() -> None:
3636
tool.run({"file_path": file_path, "text": "Hello, world!"})
3737
assert (Path(temp_dir) / "file.txt").exists()
3838
assert (Path(temp_dir) / "file.txt").read_text() == "Hello, world!"
39+
40+
41+
def test_write_file_in_subdir_of_root_dir() -> None:
42+
"""Test the WriteFile tool when the path is a subdirectory of the root dir."""
43+
with TemporaryDirectory() as temp_dir:
44+
tool = WriteFileTool(root_dir=temp_dir)
45+
tool.run({"file_path": "a/b/file.txt", "text": "Hello, world!"})
46+
assert (Path(temp_dir) / "a/b/file.txt").exists()

0 commit comments

Comments
 (0)