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]

Use custom Config class to support env and keys.cfg (#430)

Kilian Lieretbd43aaac0792
diff --git a/docs/installation/docker.md b/docs/installation/docker.md
index 9bd1ce25..725217a5 100644
--- a/docs/installation/docker.md
+++ b/docs/installation/docker.md
@@ -7,14 +7,12 @@ Instead of installing SWE-agent from source, you can also run the software direc
1. [Install Docker](https://docs.docker.com/engine/install/), then start Docker locally.
2. Run `docker pull sweagent/swe-agent:latest`
-3. Add your API tokens to a file `keys.cfg` as explained [here](keys.md)
+3. Add your API tokens to a file `keys.cfg` as explained [here](keys.md) or pass them as
+ environment variables.
-Then run
+Assuming that you create `keys.cfg` in the current directory, run
```bash
-# NOTE:
-# This assumes that keys.cfg is in your current directory (else fix the path below)
-# This command is equivalent to the script shown in the quickstart
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock \
-v $(pwd)/keys.cfg:/app/keys.cfg \
sweagent/swe-agent-run:latest \
@@ -24,11 +22,22 @@ docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock \
--config_file config/default_from_url.yaml --skip_existing=False
```
-!!! tip "Tips"
- * For more information on the different API keys/tokens, see [below](keys.md).
- * If you're using docker on Windows, use `-v //var/run/docker.sock:/var/run/docker.sock`
+!!! note "Windows"
+ If you're using docker on Windows, use `-v //var/run/docker.sock:/var/run/docker.sock`
(double slash) to escape it ([more information](https://stackoverflow.com/a/47229180/)).
- * See the [installation issues section](tips.md) for more help if you run into
+
+If you instead want to pass the keys as environment variables, use
+
+```bash
+docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock \
+ -e GITHUB_TOKEN="yourgithubtoken" \
+ -e OPENAI_API_KEY="youropenaikey" \
+ sweagent/swe-agent-run:latest \
+ # rest of the command above
+```
+
+!!! tip "More tips"
+ See the [installation issues section](tips.md) for more help if you run into
trouble.
{% include-markdown "../_footer.md" %}
\ No newline at end of file
diff --git a/docs/installation/keys.md b/docs/installation/keys.md
index c9884d9d..1d793628 100644
--- a/docs/installation/keys.md
+++ b/docs/installation/keys.md
@@ -1,17 +1,25 @@
# Adding your API keys
-Create a `keys.cfg` file at the root of this repository and populate it with your API keys.
+In order to access the LM of your choice (and to access private GitHub repositories), you need to supply the corresponding keys.
+There are two options to do this:
+
+1. Set the corresponding [environment variables](https://www.cherryservers.com/blog/how-to-set-list-and-manage-linux-environment-variables).
+2. Create a `keys.cfg` file at the root of this repository.
+
+The following `keys.cfg` example shows you how the keys are named:
+
+```
+# Remove the comment '#' in front of the line for all keys that you have set
+# GITHUB_TOKEN: 'GitHub Token for access to private repos'
+# OPENAI_API_KEY: 'OpenAI API Key Here if using OpenAI Model'
+# ANTHROPIC_API_KEY: 'Anthropic API Key Here if using Anthropic Model'
+# TOGETHER_API_KEY: 'Together API Key Here if using Together Model'
+# AZURE_OPENAI_API_KEY: 'Azure OpenAI API Key Here if using Azure OpenAI Model'
+# AZURE_OPENAI_ENDPOINT: 'Azure OpenAI Endpoint Here if using Azure OpenAI Model'
+# AZURE_OPENAI_DEPLOYMENT: 'Azure OpenAI Deployment Here if using Azure OpenAI Model'
+# AZURE_OPENAI_API_VERSION: 'Azure OpenAI API Version Here if using Azure OpenAI Model'
+# OPENAI_API_BASE_URL: 'LM base URL here if using Local or alternative api Endpoint'
```
-GITHUB_TOKEN: 'GitHub Token for access to private repos' # <-- delete line if not used
-OPENAI_API_KEY: 'OpenAI API Key Here if using OpenAI Model'
-ANTHROPIC_API_KEY: 'Anthropic API Key Here if using Anthropic Model'
-TOGETHER_API_KEY: 'Together API Key Here if using Together Model'
-AZURE_OPENAI_API_KEY: 'Azure OpenAI API Key Here if using Azure OpenAI Model'
-AZURE_OPENAI_ENDPOINT: 'Azure OpenAI Endpoint Here if using Azure OpenAI Model'
-AZURE_OPENAI_DEPLOYMENT: 'Azure OpenAI Deployment Here if using Azure OpenAI Model'
-AZURE_OPENAI_API_VERSION: 'Azure OpenAI API Version Here if using Azure OpenAI Model'
-OPENAI_API_BASE_URL: 'LM base URL here if using Local or alternative api Endpoint'
-```
See the following links for tutorials on obtaining [Anthropic](https://docs.anthropic.com/claude/reference/getting-started-with-the-api), [OpenAI](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key), and [Github](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) tokens.
\ No newline at end of file
diff --git a/sweagent/__init__.py b/sweagent/__init__.py
index 34ae313d..388dace2 100644
--- a/sweagent/__init__.py
+++ b/sweagent/__init__.py
@@ -33,4 +33,5 @@ __all__ = [
"SWEEnv",
"get_data_path_name",
"PACKAGE_DIR",
+ "CONFIG_DIR",
]
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index dd3486b2..add98336 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -1,4 +1,3 @@
-import config
import json
import logging
import os
@@ -9,6 +8,7 @@ from anthropic import Anthropic, AnthropicBedrock, HUMAN_PROMPT, AI_PROMPT
from dataclasses import dataclass, fields
from openai import BadRequestError, OpenAI, AzureOpenAI
from simple_parsing.helpers.serialization.serializable import FrozenSerializable, Serializable
+from sweagent.utils.config import Config
from sweagent.agent.commands import Command
from tenacity import (
retry,
@@ -239,7 +239,7 @@ class OpenAIModel(BaseModel):
logging.getLogger("httpx").setLevel(logging.WARNING)
# Set OpenAI key
- cfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))
+ cfg = Config()
if self.args.model_name.startswith("azure"):
self.api_model = cfg["AZURE_OPENAI_DEPLOYMENT"]
self.client = AzureOpenAI(api_key=cfg["AZURE_OPENAI_API_KEY"], azure_endpoint=cfg["AZURE_OPENAI_ENDPOINT"], api_version=cfg.get("AZURE_OPENAI_API_VERSION", "2024-02-01"))
@@ -338,7 +338,7 @@ class AnthropicModel(BaseModel):
super().__init__(args, commands)
# Set Anthropic key
- cfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))
+ cfg = Config()
self.api = Anthropic(api_key=cfg["ANTHROPIC_API_KEY"])
def history_to_messages(
@@ -660,7 +660,7 @@ class TogetherModel(BaseModel):
assert together.version >= '1.1.0', "Please upgrade to Together SDK v1.1.0 or later."
# Set Together key
- cfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))
+ cfg = Config()
together.api_key = cfg.TOGETHER_API_KEY
def history_to_messages(
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 7ba9e56d..140dd28a 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -1,6 +1,5 @@
from pathlib import Path
import random
-import config
import datetime
import docker
import gymnasium as gym
@@ -41,6 +40,8 @@ from swebench import (
)
from typing import List, Optional, Tuple
+from sweagent.utils.config import Config
+
LONG_TIMEOUT = 500
PATH_TO_REQS = "/root/requirements.txt"
PATH_TO_ENV_YML = "/root/environment.yml"
@@ -125,12 +126,7 @@ class SWEEnv(gym.Env):
except:
logger.warning("Failed to get commit hash for this repo")
- self._github_token: str = os.environ.get("GITHUB_TOKEN", "")
- if not self._github_token and os.path.isfile(
- os.path.join(os.getcwd(), "keys.cfg")
- ):
- cfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))
- self._github_token: str = cfg.get("GITHUB_TOKEN", "") # type: ignore
+ self._github_token: str = Config().get("GITHUB_TOKEN", "") # type: ignore
# Load Task Instances
self.data_path = self.args.data_path
@@ -556,7 +552,7 @@ class SWEEnv(gym.Env):
input: str,
timeout_duration=25,
) -> str:
- if "SWE_AGENT_EXPERIMENTAL_COMMUNICATE" in os.environ:
+ if "SWE_AGENT_EXPERIMENTAL_COMMUNICATE" in Config():
return self._communicate_experimental(input, timeout_duration)
try:
self.returncode = None
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
new file mode 100644
index 00000000..095bca1a
--- /dev/null
+++ b/sweagent/utils/config.py
@@ -0,0 +1,42 @@
+import logging
+from typing import Any
+import config as config_file
+import os
+
+
+logger = logging.getLogger("config")
+
+
+class Config:
+ def __init__(self, ):
+ """This wrapper class is used to load keys from environment variables or keys.cfg file.
+ Whenever both are presents, the environment variable is used.
+ """
+ # Defer import to avoid circular import
+ from sweagent import PACKAGE_DIR
+ self._keys_cfg = None
+ keys_cfg_path = PACKAGE_DIR / "keys.cfg"
+ if keys_cfg_path.exists():
+ try:
+ self._keys_cfg = config_file.Config(PACKAGE_DIR / "keys.cfg")
+ except Exception as e:
+ raise RuntimeError(f"Error loading keys.cfg. Please check the file.") from e
+ else:
+ logger.error(f"keys.cfg not found in {PACKAGE_DIR}")
+
+ def get(self, key: str, default=None) -> Any:
+ if key in os.environ:
+ return os.environ[key]
+ if self._keys_cfg is not None and key in self._keys_cfg:
+ return self._keys_cfg[key]
+ return default
+
+ def __getitem__(self, key: str) -> Any:
+ if key in os.environ:
+ return os.environ[key]
+ if self._keys_cfg is not None and key in self._keys_cfg:
+ return self._keys_cfg[key]
+ raise KeyError(f"Key {key} not found in environment or keys.cfg")
+
+ def __contains__(self, key: str) -> bool:
+ return key in os.environ or (self._keys_cfg is not None and key in self._keys_cfg)
\ No newline at end of file
diff --git a/tests/test_models.py b/tests/test_models.py
index 887da3cf..4c78b061 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -35,15 +35,15 @@ TEST_HISTORY = [
def test_openai_model(openai_mock_client):
for model_name in list(OpenAIModel.MODELS) + list(OpenAIModel.SHORTCUTS):
TEST_MODEL_ARGUMENTS = ModelArguments(model_name)
- with patch("sweagent.agent.models.config.Config"), patch("sweagent.agent.models.OpenAI"):
- model = OpenAIModel(TEST_MODEL_ARGUMENTS, [])
+ with patch("sweagent.agent.models.Config"), patch("sweagent.agent.models.OpenAI"):
+ model = OpenAIModel(TEST_MODEL_ARGUMENTS, [])
model.client = openai_mock_client
model.query(TEST_HISTORY)
@pytest.mark.parametrize("model_name", list(TogetherModel.MODELS) + list(TogetherModel.SHORTCUTS))
def test_together_model(mock_together_response, model_name):
- with patch("sweagent.agent.models.config.Config"), \
+ with patch("sweagent.agent.models.Config"), \
patch("sweagent.agent.models.together") as mock_together:
mock_together.version = '1.1.0'
mock_together.Complete.create.return_value = mock_together_response