Skip to content

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]

Resolve relative paths to demonstrations and commands (#444)

Kilian Lieretd56ff56ec337
diff --git a/docs/config/config.md b/docs/config/config.md
index 1a02d720..915f55d1 100644
--- a/docs/config/config.md
+++ b/docs/config/config.md
@@ -71,6 +71,10 @@ In the [`config/`](https://github.com/princeton-nlp/SWE-agent/tree/main/config)
* [`configs/`](https://github.com/princeton-nlp/SWE-agent/tree/main/config/configs) for examples of properly formatted configuration files. Each configuration differs in its set of commands, input/output format, demonstrations, etc.
* [`commands/`](https://github.com/princeton-nlp/SWE-agent/tree/main/config/commands) for the bash implementations of the custom commands that SWE-agent uses to navigate + edit the codebase. More information [here](commands.md).
+!!! hint "Relative paths"
+ Relative paths in config files are resolved to the `SWE_AGENT_CONFIG_ROOT` environment variable (if set)
+ or the SWE-agent repository root.
+
## How a Configuration File is Processed
Some notes on processing that occurs on config fields when SWE-agent is run:
diff --git a/docs/config/env.md b/docs/config/env.md
new file mode 100644
index 00000000..77f13125
--- /dev/null
+++ b/docs/config/env.md
@@ -0,0 +1,9 @@
+# Environment variables
+
+This page details all environment variables that are currently in use by SWE-agent.
+
+* All API keys (for LMs and GitHub) can be set as an environment variable. See [here](../installation/keys.md) for more information.
+* [Experimental] `SWE_AGENT_EXPERIMENTAL_COMMUNICATE` switches to a faster way of communicating with running docker
+ shell sessions. This has not been tested on SWE-bench, so it might sometimes break.
+ However, it can be very useful when running on single issues.
+* `SWE_AGENT_CONFIG_ROOT`: Used to resolve relative paths in the [config](config.md)
\ No newline at end of file
diff --git a/mkdocs.yml b/mkdocs.yml
index 0f3460ec..2d395709 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -62,6 +62,7 @@ nav:
- "Config files": "config/config.md"
- "Command definitions": "config/commands.md"
- "Demonstrations": "config/demonstrations.md"
+ - "Environment variables": "config/env.md"
- Development:
- "Contribution guide": "dev/contribute.md"
- "Code structure": "dev/code_structure.md"
diff --git a/run.py b/run.py
index 6fc1f601..9b334367 100644
--- a/run.py
+++ b/run.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from sweagent import CONFIG_DIR
+
try:
import rich
except ModuleNotFoundError as e:
@@ -480,7 +482,7 @@ def get_args(args=None) -> ScriptArguments:
temperature=0.0,
top_p=0.95,
),
- config_file=Path("config/default.yaml"),
+ config_file=CONFIG_DIR / "default.yaml",
),
actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),
)
diff --git a/sweagent/__init__.py b/sweagent/__init__.py
index b791faff..b21081c3 100644
--- a/sweagent/__init__.py
+++ b/sweagent/__init__.py
@@ -6,6 +6,8 @@ from pathlib import Path
PACKAGE_DIR = Path(__file__).resolve().parent
assert PACKAGE_DIR.is_dir()
+REPO_ROOT = PACKAGE_DIR.parent
+assert REPO_ROOT.is_dir()
CONFIG_DIR = PACKAGE_DIR.parent / "config"
assert CONFIG_DIR.is_dir()
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index dde20eeb..340fe598 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -24,6 +24,7 @@ from sweagent.agent.models import (
from sweagent.agent.parsing import FormatError, ParseFunction
from sweagent.environment.swe_env import SWEEnv
from sweagent.environment.utils import LOGGER_NAME
+from sweagent.utils.config import convert_paths_to_abspath
logger = logging.getLogger(LOGGER_NAME)
@@ -50,11 +51,15 @@ class AgentConfig(FrozenSerializable):
next_step_no_output_template: str | None = None # defaults to next_step_template
strategy_template: str | None = None
demonstration_template: str | None = None
- demonstrations: list[str] = field(default_factory=list)
+ # Paths to demonstrations. If path is not absolute, it is assumed to be
+ # relative to the SWE_AGENT_CONFIG_ROOT (if set) or the SWE-agent repository root
+ demonstrations: list[str | Path] = field(default_factory=list)
put_demos_in_history: bool = False # if True, add demonstration to history instead of as a single message
# defaults to format_error_template in ParseFunction
format_error_template: str = None # type: ignore
- command_files: list[str] = field(default_factory=list)
+ # Paths to command files. If path is not absolute, it is assumed to be
+ # relative to the SWE_AGENT_CONFIG_ROOT (if set) or the SWE-agent repository root
+ command_files: list[str | Path] = field(default_factory=list)
env_variables: dict[str, str] = field(default_factory=dict)
util_functions: list[str] = field(default_factory=list)
submit_command: str = "submit"
@@ -99,6 +104,9 @@ class AgentConfig(FrozenSerializable):
subroutine_types: list[Subroutine] = field(default_factory=list)
def __post_init__(self):
+ object.__setattr__(self, "command_files", convert_paths_to_abspath(self.command_files))
+ object.__setattr__(self, "demonstrations", convert_paths_to_abspath(self.demonstrations))
+
if self.next_step_template is None:
object.__setattr__(self, "next_step_template", self.instance_template)
if self.next_step_no_output_template is None:
@@ -270,7 +278,7 @@ class Agent:
self.history: list[dict[str, Any]] = []
self._append_history({"role": "system", "content": system_msg, "agent": self.name})
- if len(self.config.demonstrations) > 0 and "history_to_messages" in dir(self.model):
+ if "history_to_messages" in dir(self.model):
for demonstration_path in self.config.demonstrations:
if self.config.demonstration_template is None and not self.config.put_demos_in_history:
msg = "Cannot use demonstrations without a demonstration template or put_demos_in_history=True"
@@ -278,7 +286,7 @@ class Agent:
# Load history
logger.info(f"DEMONSTRATION: {demonstration_path}")
- demo_history = json.load(open(demonstration_path))["history"]
+ demo_history = json.loads(Path(demonstration_path).read_text())["history"]
demo_history = [
entry
for entry in demo_history
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index 1151e047..7446f100 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -81,7 +81,7 @@ class ParseCommandBash(ParseCommand):
if contents.strip().startswith("#!"):
commands = self.parse_script(path, contents)
else:
- if not path.endswith(".sh") and not Path(path).name.startswith("_"):
+ if Path(path).suffix != ".sh" and not Path(path).name.startswith("_"):
msg = (
f"Source file {path} does not have a .sh extension.\n"
"Only .sh files are supported for bash function parsing.\n"
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 1f72c7c1..c15e81ef 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -21,6 +21,7 @@ from simple_parsing.helpers.serialization.serializable import FrozenSerializable
from swebench import MAP_VERSION_TO_INSTALL, get_environment_yml, get_requirements
import docker
+from sweagent import REPO_ROOT
from sweagent.environment.utils import (
LOGGER_NAME,
PROCESS_DONE_MARKER_END,
@@ -126,7 +127,7 @@ class SWEEnv(gym.Env):
#: The commit hash of the swe-agent repository
self.commit_sha = None
try:
- repo = Repo(search_parent_directories=True)
+ repo = Repo(REPO_ROOT, search_parent_directories=True)
self.commit_sha = repo.head.object.hexsha
except KeyboardInterrupt:
raise
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index 0394754e..97cfb324 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -6,10 +6,29 @@ from pathlib import Path
from typing import Any
import config as config_file
+from sweagent import REPO_ROOT
logger = logging.getLogger("config")
+def convert_path_to_abspath(path: Path | str) -> Path:
+ """If path is not absolute, convert it to an absolute path
+ using the SWE_AGENT_CONFIG_ROOT environment variable (if set) or
+ REPO_ROOT as base.
+ """
+ path = Path(path)
+ root = Path(os.environ.get("SWE_AGENT_CONFIG_ROOT", REPO_ROOT))
+ assert root.is_dir()
+ if not path.is_absolute():
+ path = root / path
+ assert path.is_absolute()
+ return path.resolve()
+
+
+def convert_paths_to_abspath(paths: list[Path | str]) -> list[Path]:
+ return [convert_path_to_abspath(p) for p in paths]
+
+
class Config:
def __init__(self, *, keys_cfg_path: Path | None = None):
"""This wrapper class is used to load keys from environment variables or keys.cfg file.
diff --git a/tests/test_replay.py b/tests/test_replay.py
index 534ea2dd..d2ff7bd9 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
from run_replay import get_args, main
+from sweagent import CONFIG_DIR
@pytest.fixture()
@@ -37,6 +38,7 @@ def swe_agent_test_repo_local_problem_stmt(swe_agent_test_repo_clone) -> Path:
@pytest.mark.slow()
@pytest.mark.parametrize("problem_statement_source", ["github", "local"])
def test_model_replay_github_repo(
+ tmpdir,
swe_agent_test_repo_traj,
problem_statement_source,
swe_agent_test_repo_local_problem_stmt,
@@ -47,17 +49,19 @@ def test_model_replay_github_repo(
data_path = str(swe_agent_test_repo_local_problem_stmt)
args = [
"--traj_path",
- str(swe_agent_test_repo_traj),
+ str(swe_agent_test_repo_traj.resolve()),
"--data_path",
data_path,
"--config_file",
- "config/default_from_url.yaml",
+ str(CONFIG_DIR / "default_from_url.yaml"),
"--raise_exceptions",
]
if problem_statement_source == "local":
args.extend(["--repo_path", "https://github.com/klieret/swe-agent-test-repo/"])
args, remaining_args = get_args(args)
- main(**vars(args), forward_args=remaining_args)
+ with tmpdir.as_cwd():
+ # Test that we can run run.py also independently from repo dir
+ main(**vars(args), forward_args=remaining_args)
@pytest.mark.slow()
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 010e6890..c9a32748 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+from pathlib import Path
from unittest import mock
import pytest
-from sweagent.utils.config import Config
+from sweagent import REPO_ROOT
+from sweagent.utils.config import Config, convert_path_to_abspath, convert_paths_to_abspath
def test_config_retrieval_fails():
@@ -31,3 +33,12 @@ def test_retrieve_from_env(tmp_path):
tmp_keys_cfg.write_text("MY_KEY: 'other VALUE'\n")
config = Config(keys_cfg_path=tmp_keys_cfg)
assert config["MY_KEY"] == "VALUE"
+
+
+def test_convert_path_to_abspath():
+ assert convert_path_to_abspath("sadf") == REPO_ROOT / "sadf"
+ assert convert_path_to_abspath("/sadf") == Path("/sadf")
+
+
+def test_convert_paths_to_abspath():
+ assert convert_paths_to_abspath([Path("sadf"), "/sadf"]) == [REPO_ROOT / "sadf", Path("/sadf")]