SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Create Bundle and BundleConfig, each with their own state commands
carlosejimenez546b6cf62844
diff --git a/config/default.yaml b/config/default.yamlindex 02763114..f6f6dc64 100644--- a/config/default.yaml+++ b/config/default.yaml@@ -88,12 +88,10 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state- state_command: _state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitparse_function:type: thought_actionhistory_processor:diff --git a/config/default_from_url.yaml b/config/default_from_url.yamlindex e1c0bff2..e43cbeba 100644--- a/config/default_from_url.yaml+++ b/config/default_from_url.yaml@@ -90,12 +90,10 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state- state_command: _state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitparse_function:type: xml_thought_actionhistory_processor:diff --git a/config/default_xml.yaml b/config/default_xml.yamlindex 0cfb1415..1f9f8bac 100644--- a/config/default_xml.yaml+++ b/config/default_xml.yaml@@ -79,12 +79,10 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state- state_command: _state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitparse_function:type: xml_thought_actionhistory_processor:diff --git a/config/function_calling.yaml b/config/function_calling.yamlindex cd7611be..21022739 100644--- a/config/function_calling.yaml+++ b/config/function_calling.yaml@@ -81,13 +81,11 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitenable_bash_tool: true- state_command: _stateparse_function:type: function_callinghistory_processor:diff --git a/config/function_calling_replace.yaml b/config/function_calling_replace.yamlindex d06da625..256e7f85 100644--- a/config/function_calling_replace.yaml+++ b/config/function_calling_replace.yaml@@ -81,14 +81,12 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- # - tools/edit_linting- - tools/edit_replace- - tools/submit- - tools/state+ - path: tools/defaults+ - path: tools/search+ # - path: tools/edit_linting+ - path: tools/edit_replace+ - path: tools/submitenable_bash_tool: true- state_command: _stateparse_function:type: function_callinghistory_processor:diff --git a/config/human.yaml b/config/human.yamlindex 34650a22..65f52196 100644--- a/config/human.yaml+++ b/config/human.yaml@@ -7,12 +7,10 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state- state_command: _state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitparse_function:type: thought_actionhistory_processor:diff --git a/config/human_demo.yaml b/config/human_demo.yamlindex 6871cfe2..58151f7d 100644--- a/config/human_demo.yaml+++ b/config/human_demo.yaml@@ -26,12 +26,10 @@ agent:WINDOW: 100OVERLAP: 2bundles:- - tools/defaults- - tools/search- - tools/edit_linting- - tools/submit- - tools/state- state_command: _state+ - path: tools/defaults+ - path: tools/search+ - path: tools/edit_linting+ - path: tools/submitparse_function:type: thought_actionhistory_processor:diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 0b3f1bae..633984d5 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -271,7 +271,7 @@ class ReplayModel(AbstractModel):class PredeterminedTestModel(AbstractModel):- def __init__(self, outputs: list[str]):+ def __init__(self, outputs: list[dict | str]):self._outputs = outputsself._idx = -1self.stats = InstanceStats()@@ -279,13 +279,21 @@ class PredeterminedTestModel(AbstractModel):def query(self, *args, **kwargs) -> dict:self._idx += 1output = self._outputs[self._idx]- if output == "raise_runtime":- raise SweRexception()- elif output == "raise_cost":- raise CostLimitExceededError()- elif output == "raise_context":- raise ContextWindowExceededError()- return {"message": output}+ if isinstance(output, str):+ if output == "raise_runtime":+ raise SweRexception()+ elif output == "raise_cost":+ raise CostLimitExceededError()+ elif output == "raise_context":+ raise ContextWindowExceededError()+ return {"message": output}+ if not isinstance(output, dict):+ msg = f"Output must be string or dict, got {type(output)}"+ raise ValueError(msg)+ result = {"message": output["message"]}+ if "tool_calls" in output:+ result["tool_calls"] = output["tool_calls"]+ return resultclass InstantEmptySubmitTestModel(AbstractModel):diff --git a/sweagent/tools/bundle.py b/sweagent/tools/bundle.pynew file mode 100644index 00000000..d0da6a86--- /dev/null+++ b/sweagent/tools/bundle.py@@ -0,0 +1,57 @@+from __future__ import annotations++from pathlib import Path++import yaml+from pydantic import BaseModel, Field, PrivateAttr, model_validator++from sweagent.tools.commands import Command+from sweagent.utils.config import _convert_path_to_abspath+++class BundleConfig(BaseModel):+ tools: dict[str, dict]+ state_command: str | None = None+++class Bundle(BaseModel):+ path: Path+ hidden_tools: list[str] = Field(default_factory=list)+ _config: BundleConfig = PrivateAttr(default=None)++ @model_validator(mode="after")+ def validate_tools(self):+ self.path = _convert_path_to_abspath(self.path)+ if not self.path.exists():+ msg = f"Bundle path '{self.path}' does not exist."+ raise ValueError(msg)++ config_path = self.path / "config.yaml"+ if not config_path.exists():+ msg = f"Bundle config file '{config_path}' does not exist."+ raise ValueError(msg)++ config_data = yaml.safe_load(config_path.read_text())+ self._config = BundleConfig(**config_data)++ invalid_hidden_tools = set(self.hidden_tools) - set(self._config.tools.keys())+ if invalid_hidden_tools:+ msg = f"Hidden tools {invalid_hidden_tools} do not exist in available tools"+ raise ValueError(msg)+ return self++ @property+ def state_command(self) -> str | None:+ return self.config.state_command++ @property+ def config(self) -> BundleConfig:+ return self._config++ @property+ def commands(self) -> list[Command]:+ return [+ Command(name=tool, **tool_config.model_dump() if isinstance(tool_config, Command) else tool_config)+ for tool, tool_config in self.config.tools.items()+ if tool not in self.hidden_tools+ ]diff --git a/sweagent/tools/parsing.py b/sweagent/tools/parsing.pyindex 4fcdbf89..7d5dc11c 100644--- a/sweagent/tools/parsing.py+++ b/sweagent/tools/parsing.py@@ -242,11 +242,12 @@ class FunctionCallingParser(AbstractParseFunction, BaseModel):if not command:msg = f"Command '{name}' not found in list of available commands."raise FormatError(msg)- try:- values = json.loads(tool_call["function"]["arguments"])- except json.JSONDecodeError:- msg = "Tool call arguments are not valid JSON."- raise FormatError(msg)+ if not isinstance(tool_call["function"]["arguments"], dict):+ try:+ values = json.loads(tool_call["function"]["arguments"])+ except json.JSONDecodeError:+ msg = "Tool call arguments are not valid JSON."+ raise FormatError(msg)required_args = {arg.name for arg in command.arguments if arg.required}missing_args = required_args - values.keys()if missing_args:diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.pyindex cb275d14..4e66820f 100644--- a/sweagent/tools/tools.py+++ b/sweagent/tools/tools.py@@ -5,17 +5,16 @@ from functools import cached_propertyfrom pathlib import Pathfrom typing import Any-import yamlfrom pydantic import BaseModel, Fieldfrom swerex.runtime.abstract import Command as RexCommandfrom swerex.runtime.abstract import UploadRequestfrom typing_extensions import Selffrom sweagent.environment.swe_env import SWEEnv+from sweagent.tools.bundle import Bundlefrom sweagent.tools.commands import BASH_COMMAND, Commandfrom sweagent.tools.parsing import FunctionCallingParser, JsonParser, ParseFunctionfrom sweagent.tools.utils import _guard_multiline_input, generate_command_docs-from sweagent.utils.config import _convert_paths_to_abspathfrom sweagent.utils.log import get_logger@@ -55,7 +54,7 @@ class ToolFilterConfig(BaseModel):class ToolConfig(BaseModel):filter: ToolFilterConfig = ToolFilterConfig()- bundles: list[Path] = []+ bundles: list[Bundle] = Field(default_factory=list)env_variables: dict[str, Any] = {}"""Shorthand to set environment variables for the tools, effectively@@ -84,40 +83,45 @@ class ToolConfig(BaseModel):Unlike `install_commands`, these commands are part of the environment state."""- state_command: str = "_state"- """Should extract environment state in a json readable form"""-execution_timeout: int = 30"""Timeout for executing commands in the environment"""install_timeout: int = 300"""Timeout used for each of the installation commands"""- @property+ @cached_propertydef use_function_calling(self) -> bool:return isinstance(self.parse_function, FunctionCallingParser)+ @cached_property+ def state_commands(self) -> list[str]:+ return [bundle.state_command for bundle in self.bundles if bundle.state_command]+# todo: move to ToolHandler?@cached_propertydef commands(self) -> list[Command]:- """Read command files and returned parsed command objects"""+ """Read command files and return parsed command objects"""commands = []- tool_sources = {} # Track which file each tool comes from- for path in self.bundles:- config = yaml.safe_load((path / "config.yaml").read_text())- for tool, tool_config in config.get("tools", {}).items():- if tool in [x.name for x in commands]:- existing_source = tool_sources[tool]+ tool_sources: dict[str, Path] = {} # Track which file each tool comes from+ # Add bash command if enabled+ if self.enable_bash_tool:+ commands.append(BASH_COMMAND)+ tool_sources[BASH_COMMAND.name] = Path("<builtin>")++ # Collect commands from all bundles+ for bundle in self.bundles:+ for command in bundle.commands:+ if command.name in tool_sources:+ existing_source = tool_sources[command.name]msg = (- f"Tool '{tool}' is defined multiple times:\n"+ f"Tool '{command.name}' is defined multiple times:\n"f" - First definition in: {existing_source}\n"- f" - Duplicate definition in: {path}"+ f" - Duplicate definition in: {bundle.path}")raise ValueError(msg)- commands.append(Command(name=tool, **tool_config))- tool_sources[tool] = path- if self.enable_bash_tool:- commands.append(BASH_COMMAND)+ commands.append(command)+ tool_sources[command.name] = bundle.path+return commands@cached_property@@ -126,8 +130,6 @@ class ToolConfig(BaseModel):# todo: can some of these be moved to ToolHandler?def model_post_init(self, __context):- self.bundles = _convert_paths_to_abspath(self.bundles)-# for caching:commands = self.commandsmulti_line_command_endings = {@@ -194,7 +196,7 @@ class ToolHandler:await asyncio.gather(*(env.deployment.runtime.upload(- UploadRequest(source_path=bundle.as_posix(), target_path=f"/root/tools/{bundle.name}")+ UploadRequest(source_path=bundle.path.as_posix(), target_path=f"/root/tools/{bundle.path.name}"))for bundle in self.config.bundles)@@ -206,20 +208,22 @@ class ToolHandler:cwd = env.communicate("pwd", check=True).strip()asyncio.run(self._upload_bundles(env))for bundle in self.config.bundles:- env.communicate(f"export PATH=$PATH:/root/tools/{bundle.name}/bin", check=True)+ env.communicate(f"export PATH=$PATH:/root/tools/{bundle.path.name}/bin", check=True)asyncio.run(env.deployment.runtime.execute(- RexCommand(command=f"chmod +x /root/tools/{bundle.name}/bin/*", shell=True, check=False)+ RexCommand(command=f"chmod +x /root/tools/{bundle.path.name}/bin/*", shell=True, check=False))) # check false because bin might not exist- if (bundle / "install.sh").exists():+ if (bundle.path / "install.sh").exists():env.communicate(- f"cd /root/tools/{bundle.name}; source install.sh", check=True, timeout=self.config.install_timeout+ f"cd /root/tools/{bundle.path.name}; source install.sh",+ check=True,+ timeout=self.config.install_timeout,)# always make all files in bin executableasyncio.run(env.deployment.runtime.execute(- RexCommand(command=f"chmod +x /root/tools/{bundle.name}/bin/*", shell=True, check=True)+ RexCommand(command=f"chmod +x /root/tools/{bundle.path.name}/bin/*", shell=True, check=True)))env.communicate(f"cd {cwd}", check=True)@@ -245,25 +249,27 @@ class ToolHandler:# Getting state# -------------+ def _get_state(self, state_command: str, env: SWEEnv) -> dict[str, str]:+ output = env.communicate(state_command, check=True).strip()+ try:+ return json.loads(output)+ except json.JSONDecodeError as e:+ msg = f"State {output!r} is not valid json. This is an internal error, please report it."+ raise ValueError(msg) from e+def get_state(self, env: SWEEnv) -> dict[str, str]:- """If a state command is defined, execute it in the environment parse it as json and return the result.+ """Execute state commands from all bundles and combine their results.This can be used to extract environment variables etc. from the environment."""if self.mock_state is not None:return self.mock_state- if not self.config.state_command:- return {}- output = env.communicate(self.config.state_command, check=True).strip()- if not output:- self.logger.warning("State command %s returned empty output", self.config.state_command)- return {}- try:- state = json.loads(output)- except json.JSONDecodeError as e:- msg = f"State {output!r} is not valid json. This is an internal error, please report it."- raise ValueError(msg) from e- self.logger.debug(f"Retrieved state from environment: {state}")- return state++ combined_state = {}+ for state_command in self.config.state_commands:+ state = self._get_state(state_command, env)+ combined_state.update(state)+ self.logger.debug(f"Retrieved state from environment: {combined_state}")+ return combined_state# Blocking# --------diff --git a/tests/test_agent.py b/tests/test_agent.pyindex 07337f0f..93b8e431 100644--- a/tests/test_agent.py+++ b/tests/test_agent.py@@ -72,6 +72,11 @@ def thought_action_agent(thought_action_agent_config: AgentConfig) -> Agent:return Agent.from_config(thought_action_agent_config)+def function_calling_agent(function_calling_agent_config: AgentConfig) -> Agent:+ return Agent.from_config(function_calling_agent_config)++def test_exit_cost(dummy_env: SWEEnv, test_agent: Agent, tmp_path):test_agent.model = PredeterminedTestModel(["raise_cost"]) # type: ignorer = test_agent.run(@@ -226,3 +231,22 @@ def test_human_exit(dummy_env: SWEEnv, default_agent: Agent, tmp_path):assert r.doneassert r.exit_status == "exit_command"assert r.action.strip() == "exit"+++def test_function_calling(dummy_env: SWEEnv, function_calling_agent: Agent, tmp_path):+ a = function_calling_agent+ # Simulate a valid function call response from the model+ valid_response = {+ "message": "I'll list the contents of the directory",+ "tool_calls": [{"function": {"name": "bash", "arguments": '{"command": "ls"}'}, "id": "abc123"}],+ }+ a.model = PredeterminedTestModel([valid_response]) # type: ignore+ a.setup(dummy_env, EmptyProblemStatement())+ dummy_env.deployment.runtime.run_in_session_outputs = [+ BashObservation(output="file1 file2"),+ BashObservation(output="file1 file2"), # TODO, there's actually a bug in swe-rex, requiring two observations+ ] # type: ignore+ r = a.step()+ assert not r.done, "Expected not done, because we haven't submitted yet"+ assert r.action.strip() == "ls", "Expected the tool call to be executed"+ assert "file1 file2" in r.observation, "Expected the tool call to return the output of the command"diff --git a/tests/test_data/trajectories/gpt4__swe-agent__test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/args.yaml b/tests/test_data/trajectories/gpt4__swe-agent__test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/args.yamlindex 0fde8375..02dd7a0a 100644--- a/tests/test_data/trajectories/gpt4__swe-agent__test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/args.yaml+++ b/tests/test_data/trajectories/gpt4__swe-agent__test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/args.yaml@@ -444,7 +444,6 @@ agent:parse_command: {}parse_function: {}put_demos_in_history: false- state_command: _statestrategy_template: nullsubmit_command: submitsubroutine_types: []diff --git a/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/args.yaml b/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/args.yamlindex a0369b0f..50818f92 100644--- a/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/args.yaml+++ b/tests/test_data/trajectories/gpt4__swe-bench-dev-easy_first_only__default__t-0.00__p-0.95__c-3.00__install-1/args.yaml@@ -443,7 +443,6 @@ agent:parse_command: {}parse_function: {}put_demos_in_history: false- state_command: _statestrategy_template: nullsubmit_command: submitsubroutine_types: []diff --git a/tests/test_run_single.py b/tests/test_run_single.pyindex 17ba5ac7..9b8289a4 100644--- a/tests/test_run_single.py+++ b/tests/test_run_single.py@@ -11,6 +11,7 @@ from sweagent.environment.swe_env import EnvironmentConfigfrom sweagent.run.common import BasicCLIfrom sweagent.run.hooks.abstract import RunHookfrom sweagent.run.run_single import RunSingle, RunSingleConfig+from sweagent.tools.bundle import Bundleclass RaisesExceptionHook(RunHook):@@ -31,25 +32,45 @@ def test_run_single_raises_exception():@pytest.fixturedef agent_config_with_commands():ac = AgentConfig(model=InstantEmptySubmitModelConfig())- ac.tools.bundles = [TOOLS_DIR / "defaults", TOOLS_DIR / "submit"]+ ac.tools.bundles = [+ Bundle(path=TOOLS_DIR / "defaults"),+ Bundle(path=TOOLS_DIR / "submit"),+ ]assert (TOOLS_DIR / "submit").exists()# Make sure dependent properties are setac.tools.model_post_init(None)return ac+def test_hidden_tools(tmpdir):+ ac = AgentConfig(model=InstantEmptySubmitModelConfig())+ ac.tools.bundles = [+ Bundle(path=TOOLS_DIR / "defaults", hidden_tools=["scroll_up"]),+ Bundle(path=TOOLS_DIR / "submit"),+ ]+ ac.model.name = "instant_empty_submit"+ rsc = RunSingleConfig(+ env=EnvironmentConfig(),+ agent=ac,+ output_dir=Path(tmpdir),+ )+ rs = RunSingle.from_config(rsc)+ rs.run()++@pytest.mark.slowdef test_run_ies(tmpdir, agent_config_with_commands):# ies = instant empty submitac = agent_config_with_commandsac.model.name = "instant_empty_submit"- ac.tools.state_command = Nonersc = RunSingleConfig(env=EnvironmentConfig(),agent=ac,output_dir=Path(tmpdir),)rs = RunSingle.from_config(rsc)+ rs.agent.tools.mock_state = {"open_file": "asdf123", "working_dir": "/root"}rs.run()diff --git a/tools/state/bin/_state b/tools/defaults/bin/_statesimilarity index 100%rename from tools/state/bin/_staterename to tools/defaults/bin/_statediff --git a/tools/defaults/config.yaml b/tools/defaults/config.yamlindex 406d8a2c..4646ff10 100644--- a/tools/defaults/config.yaml+++ b/tools/defaults/config.yaml@@ -35,3 +35,4 @@ tools:signature: "scroll_down"docstring: "moves the window down {WINDOW} lines"arguments: []+state_command: "_state"\ No newline at end of filediff --git a/tools/state/config.yaml b/tools/state/config.yamldeleted file mode 100644index a2fa2036..00000000--- a/tools/state/config.yaml+++ /dev/null@@ -1 +0,0 @@-tools: {}\ No newline at end of file