diff --git a/.openhands/microagents/repo.md b/.openhands/microagents/repo.md index 36938260114..ac492c420ef 100644 --- a/.openhands/microagents/repo.md +++ b/.openhands/microagents/repo.md @@ -139,8 +139,10 @@ This repo has two python packages, with unit tests specifically written for each │ └── tools │ ├── __init__.py │ ├── execute_bash +│ │ ├── tool.py # <- BashTool subclass │ ├── pyproject.toml │ ├── str_replace_editor +│ │ ├── tool.py # <- FileEditorTool subclass │ └── utils ├── pyproject.toml ├── tests @@ -150,6 +152,32 @@ This repo has two python packages, with unit tests specifically written for each └── uv.lock ``` +## Tool Architecture + +The tools package now provides two patterns for tool usage: + +### Simplified Pattern (Recommended) +```python +from openhands.tools import BashTool, FileEditorTool + +# Direct instantiation with simplified API +tools = [ + BashTool(working_dir=os.getcwd()), + FileEditorTool(), +] +``` + +### Advanced Pattern (For Custom Tools) +```python +from openhands.tools import BashExecutor, execute_bash_tool + +# Explicit executor creation for reuse or customization +bash_executor = BashExecutor(working_dir=os.getcwd()) +bash_tool = execute_bash_tool.set_executor(executor=bash_executor) +``` + +The simplified pattern eliminates the need for manual executor instantiation and `set_executor()` calls, making tool usage more intuitive and reducing boilerplate code. + - Make sure you `make build` to configure the dependency first diff --git a/examples/advanced_tools_with_grep.py b/examples/advanced_tools_with_grep.py new file mode 100644 index 00000000000..1ec842b63b5 --- /dev/null +++ b/examples/advanced_tools_with_grep.py @@ -0,0 +1,203 @@ +"""Advanced example showing explicit executor usage and custom grep tool.""" + +import os + +from pydantic import Field, SecretStr + +from openhands.sdk import ( + LLM, + Agent, + Conversation, + EventType, + LLMConfig, + LLMConvertibleEvent, + Message, + TextContent, + Tool, + get_logger, +) +from openhands.sdk.tool import ActionBase, ObservationBase, ToolExecutor +from openhands.tools import ( + BashExecutor, + ExecuteBashAction, + FileEditorTool, + execute_bash_tool, +) + + +logger = get_logger(__name__) + + +# Define the Grep tool action and observation schemas +class GrepAction(ActionBase): + """Schema for content search using grep.""" + + pattern: str = Field(description="The regex pattern to search for in file contents") + path: str = Field( + default=".", + description=( + "The directory (absolute path) to search in. " + "Defaults to the current working directory." + ), + ) + include: str | None = Field( + default=None, + description=( + "Optional file pattern to filter which files to search " + "(e.g., '*.js', '*.{ts,tsx}')" + ), + ) + + +class GrepObservation(ObservationBase): + """Schema for grep search results.""" + + matches: list[str] = Field(description="List of matching lines with file paths") + files: list[str] = Field(description="List of files that had matches") + count: int = Field(description="Number of matching lines found") + pattern: str = Field(description="The pattern that was searched") + search_path: str = Field(description="The path that was searched") + + +# Define the Grep tool executor +class GrepExecutor(ToolExecutor[GrepAction, GrepObservation]): + """Executor for content search using bash grep commands.""" + + def __init__(self, bash_executor: BashExecutor): + """Initialize with a bash executor.""" + self.bash_executor = bash_executor + + def __call__(self, action: GrepAction) -> GrepObservation: + """Execute content search using bash grep commands.""" + search_path = os.path.abspath(action.path) + + # Build the grep command + grep_cmd = f"cd '{search_path}' && " + + if action.include: + # Use find with file pattern and pipe to grep + grep_cmd += ( + f"find . -name '{action.include}' -type f 2>/dev/null | " + f"head -1000 | " + f"xargs grep -H -n -E '{action.pattern}' 2>/dev/null | " + f"head -100" + ) + else: + # Search all files recursively + grep_cmd += f"grep -r -H -n -E '{action.pattern}' . 2>/dev/null | head -100" + + bash_action = ExecuteBashAction(command=grep_cmd, security_risk="LOW") + + result = self.bash_executor(bash_action) + + # Parse the output + matches = [] + files = set() + + if result.exit_code == 0 and result.output.strip(): + for line in result.output.strip().split("\n"): + if line.strip(): + matches.append(line) + # Extract filename from grep output (format: ./path/file:line:content) # noqa: E501 + if ":" in line: + file_path = line.split(":", 1)[0].lstrip("./") + if file_path: + files.add(os.path.join(search_path, file_path)) + + return GrepObservation( + matches=matches, + files=list(files), + count=len(matches), + pattern=action.pattern, + search_path=search_path, + ) + + +# Tool description +_GREP_DESCRIPTION = """Fast content search tool. +* Searches file contents using regular expressions +* Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.) +* Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}") +* Returns matching file paths sorted by modification time. +* Only the first 100 results are returned. Consider narrowing your search with stricter regex patterns or provide path parameter if you need more results. +* Use this tool when you need to find files containing specific patterns +* When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead +""" # noqa: E501 + +# Configure LLM +api_key = os.getenv("LITELLM_API_KEY") +assert api_key is not None, "LITELLM_API_KEY environment variable is not set." +llm = LLM( + config=LLMConfig( + model="litellm_proxy/anthropic/claude-sonnet-4-20250514", + base_url="https://llm-proxy.eval.all-hands.dev", + api_key=SecretStr(api_key), + ) +) + +# Tools - demonstrating both simplified and advanced patterns +cwd = os.getcwd() + +# Advanced pattern: explicit executor creation and reuse +bash_executor = BashExecutor(working_dir=cwd) +bash_tool_advanced = execute_bash_tool.set_executor(executor=bash_executor) + +# Create the grep tool using explicit executor that reuses the bash executor +grep_executor = GrepExecutor(bash_executor) +grep_tool = Tool( + name="grep", + description=_GREP_DESCRIPTION, + input_schema=GrepAction, + output_schema=GrepObservation, + executor=grep_executor, +) + +tools: list[Tool] = [ + # Simplified pattern + FileEditorTool(), + # Advanced pattern with explicit executor + bash_tool_advanced, + # Custom tool with explicit executor + grep_tool, +] + +# Agent +agent = Agent(llm=llm, tools=tools) + +llm_messages = [] # collect raw LLM messages + + +def conversation_callback(event: EventType): + logger.info(f"Found a conversation message: {str(event)[:200]}...") + if isinstance(event, LLMConvertibleEvent): + llm_messages.append(event.to_llm_message()) + + +conversation = Conversation(agent=agent, callbacks=[conversation_callback]) + +conversation.send_message( + message=Message( + role="user", + content=[ + TextContent( + text=( + "Hello! Can you use the grep tool to find all files " + "containing the word 'class' in this project, then create a summary file listing them? " # noqa: E501 + "Use the pattern 'class' to search and include only Python files with '*.py'." # noqa: E501 + ) + ) + ], + ) +) +conversation.run() + +print("=" * 100) +print("Conversation finished. Got the following LLM messages:") +for i, message in enumerate(llm_messages): + print(f"Message {i}: {str(message)[:200]}") + +print("=" * 100) +print("This example demonstrates:") +print("1. Simplified pattern: FileEditorTool() - direct instantiation") +print("2. Advanced pattern: explicit BashExecutor creation and reuse") +print("3. Custom tool: GlobTool with explicit executor definition") diff --git a/examples/hello_world.py b/examples/hello_world.py index ec93dbc4d13..53a6330d192 100644 --- a/examples/hello_world.py +++ b/examples/hello_world.py @@ -15,10 +15,8 @@ get_logger, ) from openhands.tools import ( - BashExecutor, - FileEditorExecutor, - execute_bash_tool, - str_replace_editor_tool, + BashTool, + FileEditorTool, ) @@ -37,11 +35,9 @@ # Tools cwd = os.getcwd() -bash = BashExecutor(working_dir=cwd) -file_editor = FileEditorExecutor() tools: list[Tool] = [ - execute_bash_tool.set_executor(executor=bash), - str_replace_editor_tool.set_executor(executor=file_editor), + BashTool(working_dir=cwd), + FileEditorTool(), ] # Agent diff --git a/examples/hello_world_with_registry.py b/examples/hello_world_with_registry.py index 66ec23b272c..189d64525e8 100644 --- a/examples/hello_world_with_registry.py +++ b/examples/hello_world_with_registry.py @@ -15,10 +15,8 @@ get_logger, ) from openhands.tools import ( - BashExecutor, - FileEditorExecutor, - execute_bash_tool, - str_replace_editor_tool, + BashTool, + FileEditorTool, ) @@ -41,11 +39,9 @@ # Tools cwd = os.getcwd() -bash = BashExecutor(working_dir=cwd) -file_editor = FileEditorExecutor() tools: list[Tool] = [ - execute_bash_tool.set_executor(executor=bash), - str_replace_editor_tool.set_executor(executor=file_editor), + BashTool(working_dir=cwd), + FileEditorTool(), ] # Agent diff --git a/openhands/tools/__init__.py b/openhands/tools/__init__.py index a8295a0f888..8e284e34752 100644 --- a/openhands/tools/__init__.py +++ b/openhands/tools/__init__.py @@ -2,12 +2,14 @@ from openhands.tools.execute_bash import ( BashExecutor, + BashTool, ExecuteBashAction, ExecuteBashObservation, execute_bash_tool, ) from openhands.tools.str_replace_editor import ( FileEditorExecutor, + FileEditorTool, StrReplaceEditorAction, StrReplaceEditorObservation, str_replace_editor_tool, @@ -19,10 +21,12 @@ "ExecuteBashAction", "ExecuteBashObservation", "BashExecutor", + "BashTool", "str_replace_editor_tool", "StrReplaceEditorAction", "StrReplaceEditorObservation", "FileEditorExecutor", + "FileEditorTool", ] from importlib.metadata import PackageNotFoundError, version diff --git a/openhands/tools/execute_bash/__init__.py b/openhands/tools/execute_bash/__init__.py index d04a6a5166c..5fbb75f7890 100644 --- a/openhands/tools/execute_bash/__init__.py +++ b/openhands/tools/execute_bash/__init__.py @@ -1,4 +1,5 @@ from openhands.tools.execute_bash.definition import ( + BashTool, ExecuteBashAction, ExecuteBashObservation, execute_bash_tool, @@ -11,4 +12,5 @@ "ExecuteBashAction", "ExecuteBashObservation", "BashExecutor", + "BashTool", ] diff --git a/openhands/tools/execute_bash/definition.py b/openhands/tools/execute_bash/definition.py index 38d29db04d1..f56929fd0c4 100644 --- a/openhands/tools/execute_bash/definition.py +++ b/openhands/tools/execute_bash/definition.py @@ -111,3 +111,34 @@ def agent_observation(self) -> str: openWorldHint=True, ), ) + + +class BashTool(Tool[ExecuteBashAction, ExecuteBashObservation]): + """A Tool subclass that automatically initializes a BashExecutor.""" + + def __init__( + self, + working_dir: str, + username: str | None = None, + ): + """Initialize BashTool with executor parameters. + + Args: + working_dir: The working directory for bash commands + username: Optional username for the bash session + """ + # Import here to avoid circular imports + from openhands.tools.execute_bash.impl import BashExecutor + + # Initialize the executor + executor = BashExecutor(working_dir=working_dir, username=username) + + # Initialize the parent Tool with the executor + super().__init__( + name=execute_bash_tool.name, + description=TOOL_DESCRIPTION, + input_schema=ExecuteBashAction, + output_schema=ExecuteBashObservation, + annotations=execute_bash_tool.annotations, + executor=executor, + ) diff --git a/openhands/tools/str_replace_editor/__init__.py b/openhands/tools/str_replace_editor/__init__.py index 415daf9bb64..0f117877a9f 100644 --- a/openhands/tools/str_replace_editor/__init__.py +++ b/openhands/tools/str_replace_editor/__init__.py @@ -1,4 +1,5 @@ from openhands.tools.str_replace_editor.definition import ( + FileEditorTool, StrReplaceEditorAction, StrReplaceEditorObservation, str_replace_editor_tool, @@ -12,4 +13,5 @@ "StrReplaceEditorObservation", "file_editor", "FileEditorExecutor", + "FileEditorTool", ] diff --git a/openhands/tools/str_replace_editor/definition.py b/openhands/tools/str_replace_editor/definition.py index dd4b21d3df1..0586e9aa766 100644 --- a/openhands/tools/str_replace_editor/definition.py +++ b/openhands/tools/str_replace_editor/definition.py @@ -138,3 +138,25 @@ def agent_observation(self) -> str: openWorldHint=False, ), ) + + +class FileEditorTool(Tool[StrReplaceEditorAction, StrReplaceEditorObservation]): + """A Tool subclass that automatically initializes a FileEditorExecutor.""" + + def __init__(self): + """Initialize FileEditorTool with a FileEditorExecutor.""" + # Import here to avoid circular imports + from openhands.tools.str_replace_editor.impl import FileEditorExecutor + + # Initialize the executor + executor = FileEditorExecutor() + + # Initialize the parent Tool with the executor + super().__init__( + name=str_replace_editor_tool.name, + description=TOOL_DESCRIPTION, + input_schema=StrReplaceEditorAction, + output_schema=StrReplaceEditorObservation, + annotations=str_replace_editor_tool.annotations, + executor=executor, + ) diff --git a/tests/tools/execute_bash/test_bash_tool.py b/tests/tools/execute_bash/test_bash_tool.py new file mode 100644 index 00000000000..b8985db22c1 --- /dev/null +++ b/tests/tools/execute_bash/test_bash_tool.py @@ -0,0 +1,76 @@ +"""Tests for BashTool subclass.""" + +import tempfile + +from openhands.tools import BashTool +from openhands.tools.execute_bash import ExecuteBashAction, ExecuteBashObservation + + +def test_bash_tool_initialization(): + """Test that BashTool initializes correctly.""" + with tempfile.TemporaryDirectory() as temp_dir: + tool = BashTool(working_dir=temp_dir) + + # Check that the tool has the correct name and properties + assert tool.name == "execute_bash" + assert tool.executor is not None + assert tool.action_type == ExecuteBashAction + + +def test_bash_tool_with_username(): + """Test that BashTool initializes correctly with username.""" + with tempfile.TemporaryDirectory() as temp_dir: + tool = BashTool(working_dir=temp_dir, username="testuser") + + # Check that the tool has the correct name and properties + assert tool.name == "execute_bash" + assert tool.executor is not None + assert tool.action_type == ExecuteBashAction + + +def test_bash_tool_execution(): + """Test that BashTool can execute commands.""" + with tempfile.TemporaryDirectory() as temp_dir: + tool = BashTool(working_dir=temp_dir) + + # Create an action + action = ExecuteBashAction(command="echo 'Hello, World!'", security_risk="LOW") + + # Execute the action + result = tool.call(action) + + # Check the result + assert result is not None + assert isinstance(result, ExecuteBashObservation) + assert "Hello, World!" in result.output + + +def test_bash_tool_working_directory(): + """Test that BashTool respects the working directory.""" + with tempfile.TemporaryDirectory() as temp_dir: + tool = BashTool(working_dir=temp_dir) + + # Create an action to check current directory + action = ExecuteBashAction(command="pwd", security_risk="LOW") + + # Execute the action + result = tool.call(action) + + # Check that the working directory is correct + assert isinstance(result, ExecuteBashObservation) + assert temp_dir in result.output + + +def test_bash_tool_to_openai_tool(): + """Test that BashTool can be converted to OpenAI tool format.""" + with tempfile.TemporaryDirectory() as temp_dir: + tool = BashTool(working_dir=temp_dir) + + # Convert to OpenAI tool format + openai_tool = tool.to_openai_tool() + + # Check the format + assert openai_tool["type"] == "function" + assert openai_tool["function"]["name"] == "execute_bash" + assert "description" in openai_tool["function"] + assert "parameters" in openai_tool["function"] diff --git a/tests/tools/str_replace_editor/test_file_editor_tool.py b/tests/tools/str_replace_editor/test_file_editor_tool.py new file mode 100644 index 00000000000..58b5ff0edd1 --- /dev/null +++ b/tests/tools/str_replace_editor/test_file_editor_tool.py @@ -0,0 +1,156 @@ +"""Tests for FileEditorTool subclass.""" + +import os +import tempfile + +from openhands.tools import FileEditorTool +from openhands.tools.str_replace_editor import ( + StrReplaceEditorAction, + StrReplaceEditorObservation, +) + + +def test_file_editor_tool_initialization(): + """Test that FileEditorTool initializes correctly.""" + tool = FileEditorTool() + + # Check that the tool has the correct name and properties + assert tool.name == "str_replace_editor" + assert tool.executor is not None + assert tool.action_type == StrReplaceEditorAction + + +def test_file_editor_tool_create_file(): + """Test that FileEditorTool can create files.""" + tool = FileEditorTool() + + with tempfile.TemporaryDirectory() as temp_dir: + test_file = os.path.join(temp_dir, "test.txt") + + # Create an action to create a file + action = StrReplaceEditorAction( + command="create", + path=test_file, + file_text="Hello, World!", + security_risk="LOW", + ) + + # Execute the action + result = tool.call(action) + + # Check the result + assert result is not None + assert isinstance(result, StrReplaceEditorObservation) + assert not result.error + assert os.path.exists(test_file) + + # Check file contents + with open(test_file, "r") as f: + content = f.read() + assert content == "Hello, World!" + + +def test_file_editor_tool_view_file(): + """Test that FileEditorTool can view files.""" + tool = FileEditorTool() + + with tempfile.TemporaryDirectory() as temp_dir: + test_file = os.path.join(temp_dir, "test.txt") + + # Create a test file + with open(test_file, "w") as f: + f.write("Line 1\nLine 2\nLine 3") + + # Create an action to view the file + action = StrReplaceEditorAction( + command="view", path=test_file, security_risk="LOW" + ) + + # Execute the action + result = tool.call(action) + + # Check the result + assert result is not None + assert isinstance(result, StrReplaceEditorObservation) + assert not result.error + assert "Line 1" in result.output + assert "Line 2" in result.output + assert "Line 3" in result.output + + +def test_file_editor_tool_str_replace(): + """Test that FileEditorTool can perform string replacement.""" + tool = FileEditorTool() + + with tempfile.TemporaryDirectory() as temp_dir: + test_file = os.path.join(temp_dir, "test.txt") + + # Create a test file + with open(test_file, "w") as f: + f.write("Hello, World!\nThis is a test.") + + # Create an action to replace text + action = StrReplaceEditorAction( + command="str_replace", + path=test_file, + old_str="World", + new_str="Universe", + security_risk="LOW", + ) + + # Execute the action + result = tool.call(action) + + # Check the result + assert result is not None + assert isinstance(result, StrReplaceEditorObservation) + assert not result.error + + # Check file contents + with open(test_file, "r") as f: + content = f.read() + assert "Hello, Universe!" in content + + +def test_file_editor_tool_to_openai_tool(): + """Test that FileEditorTool can be converted to OpenAI tool format.""" + tool = FileEditorTool() + + # Convert to OpenAI tool format + openai_tool = tool.to_openai_tool() + + # Check the format + assert openai_tool["type"] == "function" + assert openai_tool["function"]["name"] == "str_replace_editor" + assert "description" in openai_tool["function"] + assert "parameters" in openai_tool["function"] + + +def test_file_editor_tool_view_directory(): + """Test that FileEditorTool can view directories.""" + tool = FileEditorTool() + + with tempfile.TemporaryDirectory() as temp_dir: + # Create some test files + test_file1 = os.path.join(temp_dir, "file1.txt") + test_file2 = os.path.join(temp_dir, "file2.txt") + + with open(test_file1, "w") as f: + f.write("File 1 content") + with open(test_file2, "w") as f: + f.write("File 2 content") + + # Create an action to view the directory + action = StrReplaceEditorAction( + command="view", path=temp_dir, security_risk="LOW" + ) + + # Execute the action + result = tool.call(action) + + # Check the result + assert result is not None + assert isinstance(result, StrReplaceEditorObservation) + assert not result.error + assert "file1.txt" in result.output + assert "file2.txt" in result.output