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]
Break up model config objects
Kilian Lieret9c84fdc11246
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 2e9aaa1a..1c310135 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -66,7 +66,7 @@ class AgentConfig(BaseModel):templates: TemplateConfig = Field(default_factory=TemplateConfig)tools: ToolConfig = Field(default_factory=ToolConfig)history_processor: HistoryProcessor = Field(default_factory=DefaultHistoryProcessor)- model: ModelConfig = Field(default_factory=ModelConfig)+ model: ModelConfig# pydantic configmodel_config = ConfigDict(extra="forbid")diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 1c5376b2..d70f2145 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -6,12 +6,14 @@ import loggingfrom collections import defaultdictfrom dataclasses import dataclass, fieldsfrom pathlib import Path+from typing import Annotated, Literalimport togetherfrom anthropic import AI_PROMPT, HUMAN_PROMPT, Anthropic, AnthropicBedrockfrom groq import Groqfrom openai import AzureOpenAI, BadRequestError, OpenAIfrom pydantic import BaseModel as PydanticBaseModel+from pydantic import ConfigDict, Fieldfrom simple_parsing.helpers.serialization.serializable import Serializablefrom tenacity import (retry,@@ -29,24 +31,56 @@ logger = get_logger("lm", emoji="🤖")_MAX_RETRIES = int(keys_config.get("SWE_AGENT_MODEL_MAX_RETRIES", 10))-# todo: Separate out human model and replay model?-class ModelConfig(PydanticBaseModel):+class GenericAPIModelConfig(PydanticBaseModel):+ name: str"""Arguments configuring the model and its behavior."""-- # Name of the model to use- name: str = "gpt4"- # Cost limit for every instance (task)per_instance_cost_limit: float = 0.0- # Total cost limit+ """Cost limit for every instance (task)"""total_cost_limit: float = 0.0- # Sampling temperature+ """Total cost limit"""temperature: float = 1.0- # Sampling top-p+ """Sampling temperature"""top_p: float = 1.0- # Path to replay file when using the replay model+ """Sampling top-p"""++ # pydantic+ model_config = ConfigDict(extra="forbid")+++class ReplayModelConfig(GenericAPIModelConfig):replay_path: str | None = None- # Host URL when using Ollama model- host_url: str = "localhost:11434"+ """Path to replay file when using the replay model"""++ name: Literal["replay"] = "replay"+ """Do not change. Used for (de)serialization."""++ model_config = ConfigDict(extra="forbid")+++class InstantEmptySubmitModelConfig(GenericAPIModelConfig):+ """Model that immediately submits an empty patch"""++ name: Literal["instant_empty_submit"] = "instant_empty_submit"+ """Do not change. Used for (de)serialization."""++ model_config = ConfigDict(extra="forbid")+++class GenericLocalModelConfig(GenericAPIModelConfig):+ name: str+ api_base: str+ temperature: float = 1.0+ """Sampling temperature"""+ top_p: float = 1.0+ """Sampling top-p"""++ model_config = ConfigDict(extra="forbid")+++ModelConfig = Annotated[+ GenericAPIModelConfig | GenericLocalModelConfig | ReplayModelConfig | InstantEmptySubmitModelConfig,+ Field(union_mode="left_to_right"),+] # noqa: F821@dataclass@@ -273,7 +307,7 @@ class OpenAIModel(AbstractModel):"o1-mini": "o1-mini-2024-09-12",}- def __init__(self, args: ModelConfig, commands: list[Command]):+ def __init__(self, args: GenericAPIModelConfig, commands: list[Command]):super().__init__(args, commands)logging.getLogger("openai").setLevel(logging.WARNING)diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.pyindex 012ef93b..4a548370 100644--- a/sweagent/run/run_replay.py+++ b/sweagent/run/run_replay.py@@ -13,7 +13,7 @@ from swerex.deployment.abstract import AbstractDeploymentfrom sweagent import CONFIG_DIRfrom sweagent.agent.agents import Agent, AgentConfig-from sweagent.agent.models import ModelConfig+from sweagent.agent.models import ReplayModelConfigfrom sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfigfrom sweagent.environment.config.problem_statement import EmptyProblemStatementfrom sweagent.environment.config.repo import RepoConfig@@ -82,9 +82,9 @@ class RunReplay:)def _get_agent(self) -> Agent:- _agent_config = yaml.safe_load(Path(self.config_path).read_text())- agent_config = AgentConfig(**_agent_config["agent"])- agent_config.model = ModelConfig(name="replay", replay_path=str(self._replay_action_trajs_path))+ _agent_config = yaml.safe_load(Path(self.config_path).read_text())["agent"]+ _agent_config["model"] = ReplayModelConfig(replay_path=str(self._replay_action_trajs_path)).model_dump()+ agent_config = AgentConfig(**_agent_config)agent = Agent.from_config(agent_config)agent._catch_errors = self._catch_errorsagent._always_require_zero_exit_code = self._require_zero_exit_codediff --git a/tests/test_agent.py b/tests/test_agent.pyindex b96ca9b3..ce833dbf 100644--- a/tests/test_agent.py+++ b/tests/test_agent.py@@ -3,7 +3,7 @@ from swerex.runtime.abstract import Action, Observationfrom swerex.runtime.dummy import DummyRuntimefrom sweagent.agent.agents import Agent, AgentConfig-from sweagent.agent.models import ModelConfig, PredeterminedTestModel+from sweagent.agent.models import InstantEmptySubmitModelConfig, PredeterminedTestModelfrom sweagent.environment.config.problem_statement import EmptyProblemStatementfrom sweagent.environment.swe_env import SWEEnv@@ -14,7 +14,7 @@ def test_dummy_env(dummy_env):@pytest.fixturedef agent_config():- return AgentConfig(model=ModelConfig(name="instant_empty_submit"))+ return AgentConfig(model=InstantEmptySubmitModelConfig())@pytest.fixturediff --git a/tests/test_models.py b/tests/test_models.pyindex 84f490ef..6db6b864 100644--- a/tests/test_models.py+++ b/tests/test_models.py@@ -4,7 +4,7 @@ from unittest.mock import MagicMock, Mock, patchimport pytest-from sweagent.agent.models import GroqModel, ModelConfig, OpenAIModel, TogetherModel+from sweagent.agent.models import GenericAPIModelConfig, GroqModel, OpenAIModel, TogetherModel@pytest.fixture@@ -34,7 +34,7 @@ TEST_HISTORY = [{"role": "system", "content": "Hello, how are you?"}]def test_openai_model(openai_mock_client):for model_name in list(OpenAIModel.MODELS) + list(OpenAIModel.SHORTCUTS):- model_args = ModelConfig(name=model_name)+ model_args = GenericAPIModelConfig(name=model_name)with patch("sweagent.agent.models.keys_config"), patch("sweagent.agent.models.OpenAI"):model = OpenAIModel(model_args, [])model.client = openai_mock_client@@ -44,7 +44,7 @@ def test_openai_model(openai_mock_client):# Test groq modelsdef test_groq_model(openai_mock_client):for model_name in list(GroqModel.MODELS) + list(GroqModel.SHORTCUTS):- model_args = ModelConfig(name=model_name)+ model_args = GenericAPIModelConfig(name=model_name)with patch("sweagent.agent.models.keys_config"), patch("sweagent.agent.models.Groq"):model = GroqModel(model_args, [])model.client = openai_mock_client@@ -57,6 +57,6 @@ def test_together_model(mock_together_response, model_name):mock_together.version = "1.1.0"mock_together.Complete.create.return_value = mock_together_response- model_args = ModelConfig(name=model_name)+ model_args = GenericAPIModelConfig(name=model_name)model = TogetherModel(model_args, [])model.query(TEST_HISTORY)diff --git a/tests/test_run_single.py b/tests/test_run_single.pyindex 7267edcc..6d6acf21 100644--- a/tests/test_run_single.py+++ b/tests/test_run_single.py@@ -5,6 +5,7 @@ from pathlib import Pathimport pytestfrom sweagent.agent.agents import AgentConfig+from sweagent.agent.models import InstantEmptySubmitModelConfigfrom sweagent.environment.swe_env import EnvironmentConfigfrom sweagent.run.common import BasicCLIfrom sweagent.run.hooks.abstract import RunHook@@ -19,10 +20,7 @@ class RaisesExceptionHook(RunHook):@pytest.mark.slowdef test_run_single_raises_exception():- rsc = RunSingleConfig()- rsc.agent.model.name = "instant_empty_submit"- rsc.agent.model.model_post_init(None)- rsc.agent.model_post_init(None)+ rsc = RunSingleConfig(agent=AgentConfig(model=InstantEmptySubmitModelConfig()))rs = RunSingle.from_config(rsc)rs.add_hook(RaisesExceptionHook())with pytest.raises(ValueError, match="test exception"):@@ -31,7 +29,7 @@ def test_run_single_raises_exception():@pytest.fixturedef agent_config_with_commands():- ac = AgentConfig()+ ac = AgentConfig(model=InstantEmptySubmitModelConfig())ac.tools.command_files = [Path(f"config/commands/{name}") for name in ["submit.sh"]]# Make sure dependent properties are setac.tools.model_post_init(None)