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: add search tool to FileToolkit (#3289)

Hesam Sheikh13cd77e16c01
diff --git a/camel/toolkits/file_toolkit.py b/camel/toolkits/file_toolkit.py
index 1ac9d427b..35e1d6c11 100644
--- a/camel/toolkits/file_toolkit.py
+++ b/camel/toolkits/file_toolkit.py
@@ -1201,6 +1201,171 @@ class FileToolkit(BaseToolkit):
except Exception as e:
return f"Error editing file: {e}"
+ def search_files(
+ self,
+ pattern: str,
+ file_types: Optional[List[str]] = None,
+ file_pattern: Optional[str] = None,
+ path: Optional[str] = None,
+ ) -> str:
+ r"""Search for a text pattern in files with specified extensions or
+ file patterns.
+
+ This method searches for a text pattern (case-insensitive substring
+ match) in files matching either the specified file types or a file
+ pattern. It returns structured results showing which files contain
+ the pattern, along with line numbers and matching content.
+
+ Args:
+ pattern (str): The text pattern to search for (case-insensitive
+ string match).
+ file_types (Optional[List[str]]): List of file extensions to
+ search (e.g., ["md", "txt", "py"]). Do not include the dot.
+ If not provided and file_pattern is also not provided,
+ defaults to ["md"] (markdown files). Ignored if file_pattern
+ is provided. (default: :obj:`None`)
+ file_pattern (Optional[str]): Glob pattern for matching files
+ (e.g., "*_workflow.md", "test_*.py"). If provided, this
+ overrides file_types. (default: :obj:`None`)
+ path (Optional[str]): Directory to search in. If not provided,
+ uses the working_directory. Can be relative or absolute.
+ (default: :obj:`None`)
+
+ Returns:
+ str: JSON-formatted string containing search results with the
+ structure:
+ {
+ "pattern": "search_pattern",
+ "searched_path": "/absolute/path",
+ "file_types": ["md", "txt"],
+ "file_pattern": "*_workflow.md",
+ "matches": [
+ {
+ "file": "relative/path/to/file.md",
+ "line": 42,
+ "content": "matching line content"
+ },
+ ...
+ ],
+ "total_matches": 10,
+ "files_searched": 5
+ }
+ If an error occurs, returns a JSON string with an "error" key.
+ """
+ import json
+
+ try:
+ # resolve search path
+ if path:
+ path_obj = Path(path)
+ if not path_obj.is_absolute():
+ search_path = (self.working_directory / path_obj).resolve()
+ else:
+ search_path = path_obj.resolve()
+ else:
+ search_path = self.working_directory
+
+ # validate that search path exists
+ if not search_path.exists():
+ return json.dumps(
+ {"error": f"Search path does not exist: {search_path}"}
+ )
+
+ if not search_path.is_dir():
+ return json.dumps(
+ {"error": f"Search path is not a directory: {search_path}"}
+ )
+
+ # collect all matching files
+ matching_files: List[Path] = []
+
+ if file_pattern:
+ # use file_pattern if provided (overrides file_types)
+ pattern_glob = f"**/{file_pattern}"
+ matching_files.extend(search_path.rglob(pattern_glob))
+ else:
+ # use file_types if file_pattern not provided
+ if file_types is None:
+ file_types = ["md"]
+
+ # normalize and deduplicate file types
+ normalized_types = set()
+ for file_type in file_types:
+ file_type = file_type.lstrip('.')
+ if file_type: # skip empty strings
+ normalized_types.add(file_type)
+
+ for file_type in normalized_types:
+ # use rglob for recursive search
+ pattern_glob = f"**/*.{file_type}"
+ matching_files.extend(search_path.rglob(pattern_glob))
+
+ # search through files (case-insensitive)
+ matches = []
+ files_searched = 0
+ pattern_lower = pattern.lower()
+
+ for file_path in matching_files:
+ files_searched += 1
+ try:
+ # read file content
+ content = file_path.read_text(
+ encoding=self.default_encoding
+ )
+ lines = content.splitlines()
+
+ # search each line for pattern (case-insensitive)
+ for line_num, line in enumerate(lines, start=1):
+ if pattern_lower in line.lower():
+ # get relative path for cleaner output
+ try:
+ relative_path = file_path.relative_to(
+ search_path
+ )
+ except ValueError:
+ relative_path = file_path
+
+ matches.append(
+ {
+ "file": str(relative_path),
+ "line": line_num,
+ "content": line.strip(),
+ }
+ )
+
+ except (UnicodeDecodeError, PermissionError) as e:
+ # skip files that can't be read
+ logger.debug(f"Skipping file {file_path}: {e}")
+ continue
+
+ # build result
+ result = {
+ "pattern": pattern,
+ "searched_path": str(search_path),
+ "matches": matches,
+ "total_matches": len(matches),
+ "files_searched": files_searched,
+ }
+
+ # include file_pattern or file_types in result
+ if file_pattern:
+ result["file_pattern"] = file_pattern
+ else:
+ result["file_types"] = (
+ sorted(normalized_types) if normalized_types else ["md"]
+ )
+
+ logger.info(
+ f"Search completed: found {len(matches)} matches "
+ f"in {files_searched} files"
+ )
+ return json.dumps(result, indent=2)
+
+ except Exception as e:
+ error_msg = f"Error during file search: {e}"
+ logger.error(error_msg)
+ return json.dumps({"error": error_msg})
+
def get_tools(self) -> List[FunctionTool]:
r"""Return a list of FunctionTool objects representing the functions
in the toolkit.
@@ -1213,6 +1378,7 @@ class FileToolkit(BaseToolkit):
FunctionTool(self.write_to_file),
FunctionTool(self.read_file),
FunctionTool(self.edit_file),
+ FunctionTool(self.search_files),
]
diff --git a/test/toolkits/test_file_toolkit.py b/test/toolkits/test_file_toolkit.py
index 6d57f163e..545490763 100644
--- a/test/toolkits/test_file_toolkit.py
+++ b/test/toolkits/test_file_toolkit.py
@@ -319,14 +319,15 @@ def test_get_tools(file_write_toolkit):
tools = file_write_toolkit.get_tools()
# Check that we have the expected number of tools
- # (now 3: write_to_file, read_file, edit_file)
- assert len(tools) == 3
+ # (now 4: write_to_file, read_file, edit_file, search_files)
+ assert len(tools) == 4
# 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
+ assert "search_files" in tool_names
def test_sanitize_and_resolve_filepath(file_write_toolkit):
@@ -452,3 +453,212 @@ def test_deprecated_alias():
assert hasattr(toolkit, 'write_to_file')
assert hasattr(toolkit, 'read_file')
assert hasattr(toolkit, 'edit_file')
+
+
+def test_search_files_basic(file_write_toolkit):
+ r"""Test basic file search functionality with default markdown files."""
+ # create test files with content
+ file_write_toolkit.write_to_file("Test", "CAMEL is great", "test1.md")
+ file_write_toolkit.write_to_file("Test", "Python is awesome", "test2.md")
+ file_write_toolkit.write_to_file("Test", "CAMEL framework", "test3.md")
+
+ # search for pattern
+ result = file_write_toolkit.search_files("CAMEL")
+ result_data = json.loads(result)
+
+ # verify results
+ assert result_data["pattern"] == "CAMEL"
+ assert result_data["total_matches"] == 2
+ assert result_data["files_searched"] == 3
+ assert len(result_data["matches"]) == 2
+
+
+def test_search_files_with_file_types(file_write_toolkit):
+ r"""Test file search with specific file types."""
+ # create test files
+ file_write_toolkit.write_to_file("Test", "Python code", "test.py")
+ file_write_toolkit.write_to_file("Test", "Text file", "test.txt")
+ file_write_toolkit.write_to_file("Test", "Markdown", "test.md")
+
+ # search in python and text files only
+ result = file_write_toolkit.search_files("file", file_types=["py", "txt"])
+ result_data = json.loads(result)
+
+ # verify results
+ assert result_data["total_matches"] == 1
+ assert result_data["file_types"] == ["py", "txt"]
+ assert result_data["matches"][0]["file"] in ["test.py", "test.txt"]
+
+
+def test_search_files_with_file_pattern(file_write_toolkit):
+ r"""Test file search with glob pattern."""
+ # create test files
+ file_write_toolkit.write_to_file(
+ "Test", "workflow data", "main_workflow.md"
+ )
+ file_write_toolkit.write_to_file(
+ "Test", "workflow info", "test_workflow.md"
+ )
+ file_write_toolkit.write_to_file("Test", "other data", "readme.md")
+
+ # search with file pattern
+ result = file_write_toolkit.search_files(
+ "workflow", file_pattern="*_workflow.md"
+ )
+ result_data = json.loads(result)
+
+ # verify results
+ assert result_data["file_pattern"] == "*_workflow.md"
+ assert result_data["total_matches"] == 2
+ assert result_data["files_searched"] == 2
+
+
+def test_search_files_case_insensitive(file_write_toolkit):
+ r"""Test that search is case-insensitive."""
+ # create test file
+ file_write_toolkit.write_to_file(
+ "Test", "CAMEL is great\ncamel is small", "test.md"
+ )
+
+ # search for uppercase
+ result_upper = file_write_toolkit.search_files("CAMEL")
+ result_upper_data = json.loads(result_upper)
+
+ # search for lowercase
+ result_lower = file_write_toolkit.search_files("camel")
+ result_lower_data = json.loads(result_lower)
+
+ # verify case insensitivity - both should find 2 matches
+ assert result_upper_data["total_matches"] == 2
+ assert result_lower_data["total_matches"] == 2
+ # verify both lines are found regardless of search case
+ assert len(result_upper_data["matches"]) == 2
+ assert len(result_lower_data["matches"]) == 2
+
+
+def test_search_files_no_matches(file_write_toolkit):
+ r"""Test search when no matches are found."""
+ # create test files
+ file_write_toolkit.write_to_file("Test", "Python code", "test.md")
+
+ # search for non-existent pattern
+ result = file_write_toolkit.search_files("nonexistent")
+ result_data = json.loads(result)
+
+ # verify no matches
+ assert result_data["total_matches"] == 0
+ assert len(result_data["matches"]) == 0
+ assert result_data["files_searched"] == 1
+
+
+def test_search_files_line_numbers(file_write_toolkit):
+ r"""Test that line numbers are correct."""
+ # create test file with multiple lines
+ content = "line 1\nline 2 CAMEL\nline 3\nline 4 CAMEL\nline 5"
+ file_write_toolkit.write_to_file("Test", content, "test.md")
+
+ # search
+ result = file_write_toolkit.search_files("CAMEL")
+ result_data = json.loads(result)
+
+ # verify line numbers
+ assert result_data["total_matches"] == 2
+ assert result_data["matches"][0]["line"] == 2
+ assert result_data["matches"][1]["line"] == 4
+
+
+def test_search_files_nested_directory(file_write_toolkit):
+ r"""Test search in nested directories."""
+ # create nested files
+ file_write_toolkit.write_to_file("Test", "nested content", "dir1/file1.md")
+ file_write_toolkit.write_to_file(
+ "Test", "nested data", "dir1/dir2/file2.md"
+ )
+
+ # search recursively
+ result = file_write_toolkit.search_files("nested")
+ result_data = json.loads(result)
+
+ # verify recursive search works
+ assert result_data["total_matches"] == 2
+ assert result_data["files_searched"] == 2
+
+
+def test_search_files_duplicate_file_types(file_write_toolkit):
+ r"""Test that duplicate file types are handled correctly."""
+ # create test file
+ file_write_toolkit.write_to_file("Test", "Python code", "test.py")
+
+ # search with duplicate file types (including with dot prefix)
+ result = file_write_toolkit.search_files(
+ "Python", file_types=["py", "py", ".py"]
+ )
+ result_data = json.loads(result)
+
+ # verify no duplicates in results (file searched only once)
+ assert result_data["total_matches"] == 1
+ assert result_data["files_searched"] == 1
+ assert len(result_data["matches"]) == 1
+ # verify normalized file types in result
+ assert result_data["file_types"] == ["py"]
+
+
+def test_search_files_empty_file_types(file_write_toolkit):
+ r"""Test that empty strings in file_types are filtered out."""
+ # create test files
+ file_write_toolkit.write_to_file("Test", "Content", "test.py")
+ file_write_toolkit.write_to_file("Test", "Content", "test.txt")
+
+ # search with empty strings in file_types
+ result = file_write_toolkit.search_files(
+ "Content", file_types=["py", "", "txt"]
+ )
+ result_data = json.loads(result)
+
+ # verify empty strings are filtered out
+ assert "" not in result_data["file_types"]
+ assert set(result_data["file_types"]) == {"py", "txt"}
+ assert result_data["total_matches"] == 2
+
+
+def test_search_files_path_with_special_chars(file_write_toolkit):
+ r"""Test search in directory with special characters in name."""
+ # create directory with special characters
+ special_dir = "test-dir with spaces!"
+ file_write_toolkit.write_to_file(
+ "Test", "Content", f"{special_dir}/test.md"
+ )
+
+ # search in the directory with special characters
+ result = file_write_toolkit.search_files("Content", path=special_dir)
+ result_data = json.loads(result)
+
+ # verify search succeeded
+ assert "error" not in result_data
+ assert result_data["total_matches"] == 1
+ assert result_data["files_searched"] == 1
+
+
+def test_search_files_invalid_path(file_write_toolkit):
+ r"""Test search with non-existent directory path."""
+ # search in non-existent directory
+ result = file_write_toolkit.search_files("Content", path="nonexistent/dir")
+ result_data = json.loads(result)
+
+ # verify error is returned
+ assert "error" in result_data
+ assert "does not exist" in result_data["error"]
+
+
+def test_search_files_path_is_file(file_write_toolkit):
+ r"""Test search when path points to a file instead of directory."""
+ # create a file
+ file_write_toolkit.write_to_file("Test", "Content", "test.py")
+
+ # try to search with path pointing to the file
+ result = file_write_toolkit.search_files("Content", path="test.py")
+ result_data = json.loads(result)
+
+ # verify error is returned
+ assert "error" in result_data
+ assert "not a directory" in result_data["error"]