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]
Lots of tests; some fixes
Kilian Lieretc605ee158cf0
diff --git a/.gitignore b/.gitignoreindex 2a834fcb..0b663c83 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,4 @@+cov.xml# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex ccda75a6..fd71cd8e 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -1,7 +1,8 @@{"python.testing.pytestArgs": [+ "sweagent","--cov=sweagent/",- // "--cov-report=xml",+ "--cov-report=xml:cov.xml","tests"],"python.testing.unittestEnabled": false,diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 51b7ba26..e3fbecea 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -303,17 +303,6 @@ class Agent:self.logger.info(f"🤖 MODEL INPUT\n{message}")self._append_history({"role": "user", "content": message, "agent": self.name})- def _get_total_stats(self) -> APIStats:- """Combine model stats of different attempts"""- total_stats = APIStats()- for stats in self._info_by_attempt.values():- assert "model_stats" in stats # mypy- attempt_stats = APIStats(**stats["model_stats"]) # type: ignore- total_stats += attempt_stats- # if self._rloop is not None:- # total_stats += self._rloop.model_stats- return total_stats-def save_trajectory(self,) -> None:@@ -452,9 +441,9 @@ class Agent:"""assert self._tool_handler is not None# Condition for handling outputs with no thought (just action)- if self.model.args.name == "human":+ if self.model.name == "human":return "", output, output- elif self.model.args.name == "human_thought":+ elif self.model.name == "human_thought":thought, action = self._tool_handler.parse_actions(output)return thought, action, output@@ -565,7 +554,7 @@ class Agent:raiseobservation = e.args[1] if len(e.args) > 1 else ""observation += "COMMAND FAILED TO EXECUTE. RESTARTING PROCESS."- info["exit_status"] = "early_exit"+ info["exit_status"] = "exit_environment_error"self.logger.warning(f"Failed to execute command: {e}\nRESTARTING PROCESS.")# todo: Are we doing this here or somewhere else?self._env.reset_container()@@ -576,6 +565,7 @@ class Agent:raiseobservation = "Unknown exception"self.logger.exception("Unknown exception")+ return observation, True, info# Check if there was a submissionsubmission_result = self.handle_submission(observation, info)diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 6821413b..42e926a7 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -121,6 +121,10 @@ class BaseModel:msg = f"Unregistered model ({args.name}). Add model name to MODELS metadata to {self.__class__}"raise ValueError(msg)+ @property+ def name(self) -> str:+ return self.args.name+def reset_stats(self, other: APIStats | None = None):if other is None:self.stats = APIStats(total_cost=self.stats.total_cost)@@ -972,6 +976,34 @@ class ReplayModel(BaseModel):return _history_to_messages(history, is_demonstration=True)+class PredeterminedTestModel:+ def __init__(self, outputs: list[str]):+ self._outputs = outputs+ self._idx = -1+ self.name = "predetermined_test"+ self.stats = APIStats()++ def query(self, *args, **kwargs) -> str:+ self._idx += 1+ output = self._outputs[self._idx]+ if output == "raise_runtime":+ raise RuntimeError()+ elif output == "raise_cost":+ raise CostLimitExceededError()+ elif output == "raise_context":+ raise ContextWindowExceededError()+ return output++ def history_to_messages(self, *args, **kwargs) -> list[dict[str, str]]:+ return []++ def reset_stats(self, *args, **kwargs) -> None:+ pass++ def update_stats(self, *args, **kwargs) -> None:+ pass++class InstantEmptySubmitTestModel(BaseModel):MODELS = {"instant_empty_submit": {diff --git a/sweagent/environment/config/deployment.py b/sweagent/environment/config/deployment.pyindex d7615d11..01fdff02 100644--- a/sweagent/environment/config/deployment.py+++ b/sweagent/environment/config/deployment.py@@ -12,6 +12,16 @@ def _get_deployment(config) -> AbstractDeployment:return get_deployment(dtype, **config_dict)+class DummyDeploymentConfig(BaseModel):+ """This deployment does nothing. Used for testing purposes."""++ type: Literal["dummy"] = "dummy"+ """Discriminator for (de)serialization/CLI. Do not change."""++ def get_deployment(self) -> AbstractDeployment:+ return _get_deployment(self)++class LocalDeploymentConfig(BaseModel):type: Literal["local"] = "local""""Discriminator for (de)serialization/CLI. Do not change."""@@ -42,4 +52,4 @@ class ModalDeploymentConfig(BaseModel):return _get_deployment(self)-DeploymentConfig = DockerDeploymentConfig | ModalDeploymentConfig | LocalDeploymentConfig+DeploymentConfig = DockerDeploymentConfig | ModalDeploymentConfig | LocalDeploymentConfig | DummyDeploymentConfigdiff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.pyindex 2a408c64..9bda9c74 100644--- a/sweagent/environment/config/repo.py+++ b/sweagent/environment/config/repo.py@@ -11,6 +11,9 @@ from swerex.deployment.abstract import AbstractDeploymentfrom swerex.runtime.abstract import Command, UploadRequestfrom sweagent.utils.config import keys_config+from sweagent.utils.log import get_logger++logger = get_logger("Config", emoji="⚙️")class Repo(Protocol):@@ -69,7 +72,10 @@ class GithubRepoConfig(BaseModel):def _get_url_with_token(self, token: str) -> str:"""Prepend github token to URL"""+ if not token:+ return self.urlif "@" in self.url:+ logger.warning("Cannot prepend token to URL. '@' found in URL")return self.url_, _, url_no_protocol = self.url.partition("://")return f"https://{token}@{url_no_protocol}"@@ -78,7 +84,7 @@ class GithubRepoConfig(BaseModel):base_commit = self.base_commitgithub_token = keys_config.get("GITHUB_TOKEN", "")url = self._get_url_with_token(github_token)- r = asyncio.run(+ asyncio.run(deployment.runtime.execute(Command(command=" && ".join(@@ -94,12 +100,10 @@ class GithubRepoConfig(BaseModel):),timeout=float(keys_config.get("SWE_AGENT_ENV_LONG_TIMEOUT", 500)),shell=True,+ check=True,)),)- if r.exit_code != 0:- msg = f"Failed to clone repository (exit code: {r.exit_code}, stdout: {r.stdout}, stderr: {r.stderr})"- raise RuntimeError(msg)RepoConfig = LocalRepoConfig | GithubRepoConfigdiff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.pyindex 97593a07..9941b22f 100644--- a/sweagent/tools/tools.py+++ b/sweagent/tools/tools.py@@ -127,10 +127,7 @@ class ToolConfig(BaseModel):break-# todo: move everything about parsing the commands in here-# todo: Support different shell sessions?# todo: Take runtime in methods, not in constructor, so I can pass it to the agent-# todo: factor out tools config and potentially try to only give it to SWEEnv. Agent should only need allow-lists and the final tools documentationclass ToolHandler:def __init__(self, tools: ToolConfig, runtime: AbstractRuntime):"""This class handles most of the tool usage. It has the following responsibilities:@@ -220,10 +217,13 @@ class ToolHandler:state = asyncio.run(self._runtime.run_in_session(BashAction(command=self.config.state_command.name, check=True)))+ output = state.output.strip()+ if not output:+ return {}try:- state = json.loads(state.output)+ state = json.loads(output)except json.JSONDecodeError as e:- msg = f"State {state.output!r} is not valid json. This is an internal error, please report it."+ msg = f"State {output!r} is not valid json. This is an internal error, please report it."raise ValueError(msg) from eself.logger.debug(f"Retrieved state from environment: {state}")return statediff --git a/tests/conftest.py b/tests/conftest.pyindex 04758198..7e0789ad 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -10,7 +10,7 @@ from pathlib import Pathimport pytest-from sweagent.environment.config.deployment import DockerDeploymentConfig+from sweagent.environment.config.deployment import DockerDeploymentConfig, DummyDeploymentConfigfrom sweagent.environment.config.repo import LocalRepoConfigfrom sweagent.environment.swe_env import EnvironmentConfig, SWEEnv@@ -89,6 +89,19 @@ def test_env_args(shutil.rmtree(local_repo_path)+def dummy_env_args() -> EnvironmentConfig:+ return EnvironmentConfig(+ deployment=DummyDeploymentConfig(),+ repo=None,+ )+++def dummy_env(dummy_env_args) -> SWEEnv:+ return SWEEnv.from_config(dummy_env_args)++@contextmanagerdef swe_env_context(env_args):"""Context manager to make sure we close the shell on the containerdiff --git a/tests/test_agent.py b/tests/test_agent.pynew file mode 100644index 00000000..6a9e3472--- /dev/null+++ b/tests/test_agent.py@@ -0,0 +1,94 @@+import pytest+from swerex.runtime.abstract import Action, Observation+from swerex.runtime.dummy import DummyRuntime++from sweagent.agent.agents import Agent, AgentConfig+from sweagent.agent.models import ModelConfig, PredeterminedTestModel+from sweagent.environment.config.problem_statement import EmptyProblemStatement+from sweagent.environment.swe_env import SWEEnv+++def test_dummy_env(dummy_env):+ pass+++def agent_config():+ return AgentConfig(model=ModelConfig(name="instant_empty_submit"))+++def test_agent(agent_config: AgentConfig) -> Agent:+ return Agent("test", agent_config, _catch_errors=True)+++def test_exit_cost_manually_raised(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["```\nexit_cost\n```"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_cost" # type: ignore+++def test_exit_cost(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["raise_cost"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_cost" # type: ignore+++def test_exit_context(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["raise_context"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_context" # type: ignore+++def test_exit_model_error(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["raise_runtime"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_error" # type: ignore+++def test_exit_format(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["a", "b", "c", "d"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_format" # type: ignore+++def test_exit_blocklist(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["```\nvim\n```", "```\npython\n```", "```\nsu\n```", "```\nnano\n```"]) # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_format" # type: ignore+++class RuntimeRaisesFirst(DummyRuntime):+ async def run_in_session(self, action: Action) -> Observation:+ if action.session_type == "bash" and action.command == "raise":+ raise RuntimeError()+ return await super().run_in_session(action)+++def test_early_exit(dummy_env: SWEEnv, test_agent: Agent):+ test_agent.model = PredeterminedTestModel(["```\nraise\n```"]) # type: ignore+ test_agent._catch_errors = True+ dummy_env.deployment.runtime = RuntimeRaisesFirst() # type: ignore+ r = test_agent.run(+ problem_statement=EmptyProblemStatement(),+ env=dummy_env,+ )+ assert r.info["exit_status"] == "exit_environment_error" # type: ignore