Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Dynamic File Editing (#3063)

Saed Bhatia4acd7cfecdf
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 4bbe2b387..214188ee0 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -62,7 +62,7 @@ from .image_analysis_toolkit import ImageAnalysisToolkit
from .mcp_toolkit import MCPToolkit
from .browser_toolkit import BrowserToolkit
from .async_browser_toolkit import AsyncBrowserToolkit
-from .file_write_toolkit import FileWriteToolkit
+from .file_toolkit import FileToolkit, FileWriteToolkit
from .pptx_toolkit import PPTXToolkit
from .terminal_toolkit import TerminalToolkit
from .pubmed_toolkit import PubMedToolkit
@@ -140,7 +140,8 @@ __all__ = [
'ImageAnalysisToolkit',
'BrowserToolkit',
'AsyncBrowserToolkit',
- 'FileWriteToolkit',
+ 'FileToolkit',
+ 'FileWriteToolkit', # Deprecated, use FileToolkit instead
'PPTXToolkit',
'TerminalToolkit',
'PubMedToolkit',
diff --git a/camel/toolkits/context_summarizer_toolkit.py b/camel/toolkits/context_summarizer_toolkit.py
index 299550093..e02de0bcb 100644
--- a/camel/toolkits/context_summarizer_toolkit.py
+++ b/camel/toolkits/context_summarizer_toolkit.py
@@ -80,6 +80,8 @@ class ContextSummarizerToolkit(BaseToolkit):
# Create a separate agent for summarization without tools to avoid
# circular calls
+ from camel.agents import ChatAgent
+
self.summary_agent = ChatAgent(
system_message="You are a helpful assistant that creates concise "
"summaries of conversations.",
diff --git a/camel/toolkits/file_write_toolkit.py b/camel/toolkits/file_toolkit.py
similarity index 83%
rename from camel/toolkits/file_write_toolkit.py
rename to camel/toolkits/file_toolkit.py
index 27adea0c9..f7637e719 100644
--- a/camel/toolkits/file_write_toolkit.py
+++ b/camel/toolkits/file_toolkit.py
@@ -15,7 +15,7 @@ import os
import re
from datetime import datetime
from pathlib import Path
-from typing import List, Optional, Tuple, Union
+from typing import Dict, List, Optional, Tuple, Union
from camel.logger import get_logger
from camel.toolkits.base import BaseToolkit
@@ -26,14 +26,17 @@ logger = get_logger(__name__)
@MCPServer()
-class FileWriteToolkit(BaseToolkit):
- r"""A toolkit for creating, writing, and modifying text in files.
-
- This class provides cross-platform (macOS, Linux, Windows) support for
- writing to various file formats (Markdown, DOCX, PDF, and plaintext),
- replacing text in existing files, automatic filename uniquification to
- prevent overwrites, custom encoding and enhanced formatting options for
- specialized formats.
+class FileToolkit(BaseToolkit):
+ r"""A comprehensive toolkit for file operations including reading,
+ writing, and editing files.
+
+ This class provides cross-platform (macOS, Linux, Windows) support for:
+ - Reading various file formats (text, JSON, YAML, PDF, DOCX)
+ - Writing to multiple formats (Markdown, DOCX, PDF, plaintext, JSON,
+ YAML, CSV, HTML)
+ - Editing and modifying existing files with content replacement
+ - Automatic backup creation before modifications
+ - Custom encoding and enhanced formatting options
"""
def __init__(
@@ -126,36 +129,32 @@ class FileWriteToolkit(BaseToolkit):
with file_path.open("w", encoding=encoding) as f:
f.write(content)
- def _generate_unique_filename(self, file_path: Path) -> Path:
- r"""Generate a unique filename if the target file already exists.
+ def _create_backup(self, file_path: Path) -> Optional[Path]:
+ r"""Create a backup of the file if it exists and backup is enabled.
Args:
- file_path (Path): The original file path.
+ file_path (Path): The file path to backup.
Returns:
- Path: A unique file path that doesn't exist yet.
+ Optional[Path]: Path to the backup file if created, None otherwise.
"""
- if not file_path.exists():
- return file_path
+ if not self.backup_enabled or not file_path.exists():
+ return None
- # Generate unique filename with timestamp and counter
+ # Generate backup filename with .bak extension and timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- stem = file_path.stem
- suffix = file_path.suffix
- parent = file_path.parent
-
- # First try with timestamp
- new_path = parent / f"{stem}_{timestamp}{suffix}"
- if not new_path.exists():
- return new_path
-
- # If timestamp version exists, add counter
- counter = 1
- while True:
- new_path = parent / f"{stem}_{timestamp}_{counter}{suffix}"
- if not new_path.exists():
- return new_path
- counter += 1
+ backup_path = file_path.parent / f"{file_path.name}.{timestamp}.bak"
+
+ # Copy the file to backup location
+ import shutil
+
+ try:
+ shutil.copy2(file_path, backup_path)
+ logger.info(f"Created backup: {backup_path}")
+ return backup_path
+ except Exception as e:
+ logger.warning(f"Failed to create backup: {e}")
+ return None
def _write_docx_file(self, file_path: Path, content: str) -> None:
r"""Write text content to a DOCX file with default formatting.
@@ -1006,8 +1005,9 @@ class FileWriteToolkit(BaseToolkit):
file_path = self._resolve_filepath(filename)
file_path.parent.mkdir(parents=True, exist_ok=True)
- # Generate unique filename if file exists
- file_path = self._generate_unique_filename(file_path)
+ # Create backup of existing file if backup is enabled
+ if file_path.exists() and self.backup_enabled:
+ self._create_backup(file_path)
extension = file_path.suffix.lower()
@@ -1062,6 +1062,144 @@ class FileWriteToolkit(BaseToolkit):
logger.error(error_msg)
return error_msg
+ # ----------------------------------------------
+ # Read File Functions
+ # ----------------------------------------------
+ def read_file(
+ self, file_paths: Union[str, List[str]]
+ ) -> Union[str, Dict[str, str]]:
+ r"""Read and return content of one or more files using MarkItDown
+ for better format support.
+
+ This method uses MarkItDownLoader to convert various file formats
+ to Markdown. It supports a wide range of formats including:
+ - PDF (.pdf)
+ - Microsoft Office: Word (.doc, .docx), Excel (.xls, .xlsx),
+ PowerPoint (.ppt, .pptx)
+ - EPUB (.epub)
+ - HTML (.html, .htm)
+ - Images (.jpg, .jpeg, .png) for OCR
+ - Audio (.mp3, .wav) for transcription
+ - Text-based formats (.csv, .json, .xml, .txt, .md)
+ - ZIP archives (.zip)
+
+ Args:
+ file_paths (Union[str, List[str]]): A single file path or a list
+ of file paths to read. Paths can be relative or absolute.
+ If relative, they will be resolved relative to the working
+ directory.
+
+ Returns:
+ Union[str, Dict[str, str]]:
+ - If a single file path is provided: Returns the content as
+ a string.
+ - If multiple file paths are provided: Returns a dictionary
+ where keys are file paths and values are the corresponding
+ content in Markdown format.
+ If conversion fails, returns an error message.
+ """
+ from camel.loaders.markitdown import MarkItDownLoader
+
+ try:
+ # Handle single file path for backward compatibility
+ if isinstance(file_paths, str):
+ resolved_path = self._resolve_filepath(file_paths)
+
+ # Use MarkItDownLoader to convert the file
+ result = MarkItDownLoader().convert_files(
+ file_paths=[str(resolved_path)], parallel=False
+ )
+
+ # Return the converted content or error message
+ return result.get(
+ str(resolved_path), f"Failed to read file: {resolved_path}"
+ )
+
+ # Handle multiple file paths
+ else:
+ resolved_paths = [
+ str(self._resolve_filepath(fp)) for fp in file_paths
+ ]
+
+ # Use MarkItDownLoader to convert files in parallel
+ result = MarkItDownLoader().convert_files(
+ file_paths=resolved_paths, parallel=True
+ )
+
+ # Map back to original paths if needed
+ return_dict = {}
+ for original, resolved in zip(file_paths, resolved_paths):
+ return_dict[original] = result.get(
+ resolved, f"Failed to read file: {resolved}"
+ )
+
+ return return_dict
+
+ except Exception as e:
+ return f"Error reading file(s): {e}"
+
+ # ----------------------------------------------
+ # Edit File Functions
+ # ----------------------------------------------
+ def edit_file(
+ self, file_path: str, old_content: str, new_content: str
+ ) -> str:
+ r"""Edit a file by replacing specified content.
+
+ This method performs simple text replacement in files. It reads
+ the file, replaces all occurrences of old_content with new_content,
+ and writes the result back.
+
+ Args:
+ file_path (str): The path to the file to edit. Can be
+ relative or absolute. If relative, it will be resolved
+ relative to the working directory.
+ old_content (str): The exact text to find and replace.
+ new_content (str): The text to replace old_content with.
+
+ Returns:
+ str: A success message if the edit was successful, or an
+ error message if the content wasn't found or an error occurred.
+ """
+ try:
+ working_path = self._resolve_filepath(file_path)
+
+ if not working_path.exists():
+ return f"Error: File {working_path} does not exist"
+
+ # Create backup before editing if enabled
+ self._create_backup(working_path)
+
+ # Read the file content
+ try:
+ file_text = working_path.read_text(
+ encoding=self.default_encoding
+ )
+ except Exception as e:
+ return f"Error reading file: {e}"
+
+ # Check if the old_content exists in the file
+ if old_content not in file_text:
+ return (
+ f"No replacement performed: '{old_content}' not found in "
+ f"{working_path}."
+ )
+
+ # Replace the content
+ new_file_text = file_text.replace(old_content, new_content)
+
+ # Write back to file
+ try:
+ working_path.write_text(
+ new_file_text, encoding=self.default_encoding
+ )
+ return f"Successfully edited {working_path}"
+ except Exception as e:
+ return f"Error writing file: {e}"
+
+ except Exception as e:
+ return f"Error editing file: {e}"
+
def get_tools(self) -> List[FunctionTool]:
r"""Return a list of FunctionTool objects representing the functions
in the toolkit.
@@ -1072,4 +1210,26 @@ class FileWriteToolkit(BaseToolkit):
"""
return [
FunctionTool(self.write_to_file),
+ FunctionTool(self.read_file),
+ FunctionTool(self.edit_file),
]
+
+
+# Backward compatibility: FileWriteToolkit as deprecated alias
+class FileWriteToolkit(FileToolkit):
+ r"""Deprecated: Use FileToolkit instead.
+
+ This class is maintained for backward compatibility only.
+ Please use FileToolkit for new code.
+ """
+
+ def __init__(self, *args, **kwargs):
+ import warnings
+
+ warnings.warn(
+ "FileWriteToolkit is deprecated and will be removed in a "
+ "future version. Please use FileToolkit instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ super().__init__(*args, **kwargs)
diff --git a/camel/toolkits/markitdown_toolkit.py b/camel/toolkits/markitdown_toolkit.py
index d841c821b..1ba733437 100644
--- a/camel/toolkits/markitdown_toolkit.py
+++ b/camel/toolkits/markitdown_toolkit.py
@@ -25,12 +25,38 @@ logger = get_logger(__name__)
@MCPServer()
class MarkItDownToolkit(BaseToolkit):
- r"""A class representing a toolkit for MarkItDown."""
+ r"""A class representing a toolkit for MarkItDown.
+
+ .. deprecated::
+ MarkItDownToolkit is deprecated. Use FileToolkit instead, which now
+ includes the same functionality through its read_file method that
+ supports both single files and multiple files.
+
+ Example migration:
+ # Old way
+ from camel.toolkits import MarkItDownToolkit
+ toolkit = MarkItDownToolkit()
+ content = toolkit.read_files(['file1.pdf', 'file2.docx'])
+
+ # New way
+ from camel.toolkits import FileToolkit
+ toolkit = FileToolkit()
+ content = toolkit.read_file(['file1.pdf', 'file2.docx'])
+ """
def __init__(
self,
timeout: Optional[float] = None,
):
+ import warnings
+
+ warnings.warn(
+ "MarkItDownToolkit is deprecated and will be removed in a future "
+ "version. Please use FileToolkit instead, which now includes "
+ "read_file method that supports both single and multiple files.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
super().__init__(timeout=timeout)
def read_files(self, file_paths: List[str]) -> Dict[str, str]:
diff --git a/examples/toolkits/file_write_toolkit.py b/examples/toolkits/file_toolkit.py
similarity index 73%
rename from examples/toolkits/file_write_toolkit.py
rename to examples/toolkits/file_toolkit.py
index 5c7c40733..a7c565bad 100644
--- a/examples/toolkits/file_write_toolkit.py
+++ b/examples/toolkits/file_toolkit.py
@@ -16,7 +16,7 @@ import os
from camel.agents import ChatAgent
from camel.models import ModelFactory
-from camel.toolkits import FileWriteToolkit
+from camel.toolkits import FileToolkit
from camel.types import ModelPlatformType
from camel.types.enums import ModelType
@@ -24,7 +24,6 @@ from camel.types.enums import ModelType
model = ModelFactory.create(
model_platform=ModelPlatformType.DEFAULT,
model_type=ModelType.DEFAULT,
- model_config_dict={"temperature": 0},
)
# Define system message for the agent
@@ -35,7 +34,7 @@ working_directory = "./file_write_outputs"
os.makedirs(working_directory, exist_ok=True)
# Initialize the FileWriteToolkit with the output directory
-file_toolkit = FileWriteToolkit(working_directory=working_directory)
+file_toolkit = FileToolkit(working_directory=working_directory)
# Get the tools from the toolkit
tools_list = file_toolkit.get_tools()
@@ -311,3 +310,153 @@ These agents can be software programs, robots, or any entities that can perceive
# 'filename': 'multiagent_overview.pdf', 'encoding': None, 'use_latex': False}, result='Content successfully written to file: /Users/yifengwang/project/camel/file_write_outputs/multiagent_overview.pdf', tool_call_id='call_btYqjycX4aUfBNJUy8bpnHSV')]
===============================================================================
'''
+
+# Example 9: Read file content
+read_query = """Please read the content of the web server python file that was created earlier."""
+
+camel_agent.reset()
+response = camel_agent.step(read_query)
+print("Example 9: Reading file content")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 9: Reading file content
+Here is the content of the `simple_flask_server.py` file:
+
+```python
+from flask import Flask
+
+app = Flask(__name__)
+
+def home():
+ return "Hello, Flask!"
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
+This is a simple Flask web server that returns "Hello, Flask!" when accessed at the root URL.
+Tool calls: [ToolCallingRecord(tool_name='read_file', args={'file_path': 'simple_flask_server.py'}, result='from flask import Flask\n\napp = Flask(__name__)\n\[email protected](\'/\')\ndef home():\n return "Hello, Flask!"\n\nif __name__ == \'__main__\':\n app.run(debug=True)', tool_call_id='call_abc123def456')]
+===============================================================================
+'''
+
+# Example 10: Edit file content
+edit_query = """Please edit the simple_flask_server.py file to add a new route '/about' that returns 'About Flask Server'."""
+
+camel_agent.reset()
+response = camel_agent.step(edit_query)
+print("Example 10: Editing file content")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 10: Editing file content
+I have successfully edited the `simple_flask_server.py` file to add a new route '/about' that returns 'About Flask Server'. The file now includes both the original home route and the new about route.
+Tool calls: [ToolCallingRecord(tool_name='edit_file', args={'file_path': 'simple_flask_server.py', 'old_content': '@app.route(\'/\')\ndef home():\n return "Hello, Flask!"\n\nif __name__ == \'__main__\':', 'new_content': '@app.route(\'/\')\ndef home():\n return "Hello, Flask!"\n\[email protected](\'/about\')\ndef about():\n return "About Flask Server"\n\nif __name__ == \'__main__\':'}, result='Successfully edited file: /Users/enrei/Desktop/camel0209/camel/file_write_outputs/simple_flask_server.py', tool_call_id='call_def789ghi012')]
+===============================================================================
+'''
+
+# Example 11: Insert content at specific line
+insert_query = """Please insert a comment '# This is a simple Flask application' at the beginning of the simple_flask_server.py file."""
+
+camel_agent.reset()
+response = camel_agent.step(insert_query)
+print("Example 11: Inserting content at specific line")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 11: Inserting content at specific line
+I have successfully inserted the comment '# This is a simple Flask application' at the beginning of the `simple_flask_server.py` file. The comment has been added as the first line of the file.
+Tool calls: [ToolCallingRecord(tool_name='insert_at_line', args={'file_path': 'simple_flask_server.py', 'content': '# This is a simple Flask application', 'line_number': 0}, result='Successfully inserted content at line 0 in /Users/enrei/Desktop/camel0209/camel/file_write_outputs/simple_flask_server.py', tool_call_id='call_jkl345mno678')]
+===============================================================================
+'''
+
+# Example 12: Read and edit JSON file
+json_edit_query = """Please read the books.json file, then edit it to add a new book with title 'The Future of AI', author 'Dr. Smith', publication year 2023, and genre 'Science Fiction'."""
+
+camel_agent.reset()
+response = camel_agent.step(json_edit_query)
+print("Example 12: Reading and editing JSON file")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 12: Reading and editing JSON file
+I have successfully read the books.json file and added a new book entry. The file now contains 4 books including the newly added "The Future of AI" by Dr. Smith.
+Tool calls: [ToolCallingRecord(tool_name='read_file', args={'file_path': 'books.json'}, result='[\n {\n "title": "The Whispering Shadows",\n "author": "Ava Sinclair",\n "publication_year": 2021,\n "genre": "Fantasy"\n },\n {\n "title": "Echoes of the Past",\n "author": "Liam Carter",\n "publication_year": 2019,\n "genre": "Historical Fiction"\n },\n {\n "title": "The Last Star",\n "author": "Maya Thompson",\n "publication_year": 2022,\n "genre": "Science Fiction"\n }\n]', tool_call_id='call_pqr901stu234'), ToolCallingRecord(tool_name='edit_file', args={'file_path': 'books.json', 'old_content': ' }\n]', 'new_content': ' },\n {\n "title": "The Future of AI",\n "author": "Dr. Smith",\n "publication_year": 2023,\n "genre": "Science Fiction"\n }\n]'}, result='Successfully edited file: /Users/enrei/Desktop/camel0209/camel/file_write_outputs/books.json', tool_call_id='call_vwx567yza890')]
+===============================================================================
+'''
+
+# Example 13: Insert at end of file
+insert_end_query = """Please insert a new route '/contact' that returns 'Contact us at [email protected]' at the end of the simple_flask_server.py file, just before the 'if __name__ == \'__main__\':' line."""
+
+camel_agent.reset()
+response = camel_agent.step(insert_end_query)
+print("Example 13: Inserting at end of file")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 13: Inserting at end of file
+I have successfully inserted the new '/contact' route in the `simple_flask_server.py` file. The route has been added just before the main execution block, so the file now has three routes: '/', '/about', and '/contact'.
+Tool calls: [ToolCallingRecord(tool_name='insert_at_line', args={'file_path': 'simple_flask_server.py', 'content': '@app.route(\'/contact\')\ndef contact():\n return "Contact us at [email protected]"', 'line_number': -2}, result='Successfully inserted content at line -2 in /Users/enrei/Desktop/camel0209/camel/file_write_outputs/simple_flask_server.py', tool_call_id='call_bcd123efg456')]
+===============================================================================
+'''
+
+# Example 14: Read the final modified file
+final_read_query = """Please read the final content of the simple_flask_server.py file to see all the modifications we made."""
+
+camel_agent.reset()
+response = camel_agent.step(final_read_query)
+print("Example 14: Reading final modified file")
+print(response.msgs[0].content)
+print("Tool calls:", response.info['tool_calls'])
+print("\n")
+
+'''
+===============================================================================
+Example 14: Reading final modified file
+Here is the final content of the `simple_flask_server.py` file after all our modifications:
+
+```python
+# This is a simple Flask application
+from flask import Flask
+
+app = Flask(__name__)
+
+def home():
+ return "Hello, Flask!"
+
+def about():
+ return "About Flask Server"
+
[email protected]('/contact')
+def contact():
+ return "Contact us at [email protected]"
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
+The file now includes:
+1. A comment at the top
+2. Three routes: '/', '/about', and '/contact'
+3. All the original functionality plus the new features we added
+Tool calls: [ToolCallingRecord(tool_name='read_file', args={'file_path': 'simple_flask_server.py'}, result='# This is a simple Flask application\nfrom flask import Flask\n\napp = Flask(__name__)\n\[email protected](\'/\')\ndef home():\n return "Hello, Flask!"\n\[email protected](\'/about\')\ndef about():\n return "About Flask Server"\n\[email protected](\'/contact\')\ndef contact():\n return "Contact us at [email protected]"\n\nif __name__ == \'__main__\':\n app.run(debug=True)', tool_call_id='call_hij789klm012')]
+===============================================================================
+'''
diff --git a/test/toolkits/test_file_write_toolkit.py b/test/toolkits/test_file_toolkit.py
similarity index 70%
rename from test/toolkits/test_file_write_toolkit.py
rename to test/toolkits/test_file_toolkit.py
index 96a7f079d..6d57f163e 100644
--- a/test/toolkits/test_file_write_toolkit.py
+++ b/test/toolkits/test_file_toolkit.py
@@ -20,14 +20,15 @@ from pathlib import Path
import pytest
import yaml
-from camel.toolkits import FileWriteToolkit
+from camel.toolkits import FileToolkit, FileWriteToolkit
@pytest.fixture
def file_write_toolkit():
- r"""Create a FileWriteToolkit instance for testing."""
+ r"""Create a FileToolkit instance for testing."""
with tempfile.TemporaryDirectory() as temp_dir:
- toolkit = FileWriteToolkit(working_directory=temp_dir)
+ # Use FileToolkit (new name) for testing
+ toolkit = FileToolkit(working_directory=temp_dir)
yield toolkit
@@ -39,8 +40,8 @@ def temp_dir():
def test_initialization():
- r"""Test the initialization of FileWriteToolkit with default parameters."""
- toolkit = FileWriteToolkit()
+ r"""Test the initialization of FileToolkit with default parameters."""
+ toolkit = FileToolkit()
assert toolkit.working_directory == Path("./camel_working_dir").resolve()
assert toolkit.default_encoding == "utf-8"
@@ -48,12 +49,12 @@ def test_initialization():
def test_initialization_with_custom_parameters():
- r"""Test the initialization of FileWriteToolkit with custom parameters."""
+ r"""Test the initialization of FileToolkit with custom parameters."""
working_directory = "./custom_dir"
default_encoding = "latin-1"
backup_enabled = False
- toolkit = FileWriteToolkit(
+ toolkit = FileToolkit(
working_directory=working_directory,
default_encoding=default_encoding,
backup_enabled=backup_enabled,
@@ -295,7 +296,7 @@ def test_write_to_file_nested_directory(file_write_toolkit):
def test_write_to_file_absolute_path(temp_dir):
r"""Test writing to a file using an absolute path."""
- toolkit = FileWriteToolkit(working_directory="./default")
+ toolkit = FileToolkit(working_directory="./default")
content = "Content with absolute path"
filename = os.path.join(temp_dir, "absolute_path.txt")
@@ -318,10 +319,14 @@ def test_get_tools(file_write_toolkit):
tools = file_write_toolkit.get_tools()
# Check that we have the expected number of tools
- assert len(tools) == 1
+ # (now 3: write_to_file, read_file, edit_file)
+ assert len(tools) == 3
- # Check that the tool has the correct function name
- assert tools[0].get_function_name() == "write_to_file"
+ # Check that the tools have the correct function names
+ tool_names = [tool.get_function_name() for tool in tools]
+ assert "write_to_file" in tool_names
+ assert "read_file" in tool_names
+ assert "edit_file" in tool_names
def test_sanitize_and_resolve_filepath(file_write_toolkit):
@@ -344,3 +349,106 @@ def test_sanitize_and_resolve_filepath(file_write_toolkit):
assert (
resolved_path == expected_path.resolve()
), "The resolved file path does not match the expected sanitized path."
+
+
+def test_backup_functionality(file_write_toolkit):
+ r"""Test that backup files are created when backup_enabled is True."""
+ # Write initial file
+ content = "Initial content"
+ filename = "test_backup.txt"
+ result = file_write_toolkit.write_to_file(
+ title="Test", content=content, filename=filename
+ )
+ assert "successfully" in result.lower()
+
+ # Write again with backup enabled (default)
+ new_content = "Updated content"
+ result = file_write_toolkit.write_to_file(
+ title="Test", content=new_content, filename=filename
+ )
+ assert "successfully" in result.lower()
+
+ # Check that backup file exists
+ import glob
+
+ backup_files = glob.glob(
+ str(file_write_toolkit.working_directory / f"{filename}.*.bak")
+ )
+ assert len(backup_files) == 1, "Backup file should have been created"
+
+ # Read backup file and verify it contains original content
+ with open(backup_files[0], 'r') as f:
+ backup_content = f.read()
+ assert "Initial content" in backup_content
+
+
+def test_no_backup_when_disabled(tmp_path):
+ r"""Test that no backup is created when backup_enabled is False."""
+ # Use a temporary directory for this test
+ toolkit = FileToolkit(
+ working_directory=str(tmp_path), backup_enabled=False
+ )
+
+ # Write initial file
+ content = "Initial content"
+ filename = "test_no_backup.txt"
+ result = toolkit.write_to_file(
+ title="Test", content=content, filename=filename
+ )
+ assert "successfully" in result.lower()
+
+ # Read the file to verify content
+ file_path = toolkit.working_directory / filename
+ assert file_path.exists()
+ with open(file_path, 'r') as f:
+ file_content = f.read()
+ assert "Initial content" in file_content
+
+ # Write again with backup disabled - should overwrite
+ new_content = "Updated content"
+ result = toolkit.write_to_file(
+ title="Test", content=new_content, filename=filename
+ )
+ assert "successfully" in result.lower()
+
+ # Check that no backup file exists
+ import glob
+
+ backup_files = glob.glob(
+ str(toolkit.working_directory / f"{filename}.*.bak")
+ )
+ assert len(backup_files) == 0, "No backup file should have been created"
+
+ # Check that the original file was overwritten (only 1 file exists)
+ all_files = glob.glob(
+ str(toolkit.working_directory / "test_no_backup*.txt")
+ )
+ assert len(all_files) == 1, "Should have only 1 file (overwritten)"
+
+ # Verify the file contains the updated content
+ with open(file_path, 'r') as f:
+ file_content = f.read()
+ assert "Updated content" in file_content
+ assert "Initial content" not in file_content
+
+
+def test_deprecated_alias():
+ r"""Test that FileWriteToolkit still works with deprecation warning."""
+ import warnings
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+
+ # This should trigger a deprecation warning
+ toolkit = FileWriteToolkit()
+
+ # Check that a deprecation warning was issued
+ assert len(w) == 1
+ assert issubclass(w[0].category, DeprecationWarning)
+ assert "FileWriteToolkit is deprecated" in str(w[0].message)
+
+ # Verify the toolkit still works
+ assert toolkit is not None
+ assert hasattr(toolkit, 'write_to_file')
+ assert hasattr(toolkit, 'read_file')
+ assert hasattr(toolkit, 'edit_file')