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]

Rename ModelArgs -> ModelConfig; delete summarizer

Kilian Lieret7ac029dcd3ab
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index be739de5..1ebeb14a 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -21,7 +21,7 @@ from sweagent.agent.models import (
APIStats,
ContextWindowExceededError,
CostLimitExceededError,
- ModelArguments,
+ ModelConfig,
get_model,
)
from sweagent.agent.parsing import FormatError, ParseFunction
@@ -108,7 +108,7 @@ class AgentConfig(BaseModel):
)
# _subroutines: dict[str, Subroutine] = field(default_factory=dict)
# subroutine_types: list[Subroutine] = field(default_factory=list)
- model: ModelArguments = field(default_factory=lambda: ModelArguments(name="gpt4"))
+ model: ModelConfig = field(default_factory=lambda: ModelConfig(name="gpt4"))
multi_line_command_endings: dict[str, str] = field(default_factory=dict)
submit_command_end_name: str | None = None
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index d1df620f..1c901b84 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -29,8 +29,8 @@ 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 ModelArguments(PydanticBaseModel):
+# todo: Separate out human model and replay model?
+class ModelConfig(PydanticBaseModel):
"""Arguments configuring the model and its behavior."""
# Name of the model to use
@@ -86,7 +86,7 @@ class BaseModel:
MODELS = {}
SHORTCUTS = {}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
self.args = args
self.commands = commands
self.model_metadata = {}
@@ -261,7 +261,7 @@ class OpenAIModel(BaseModel):
"o1-mini": "o1-mini-2024-09-12",
}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
logging.getLogger("openai").setLevel(logging.WARNING)
@@ -456,7 +456,7 @@ class AnthropicModel(BaseModel):
"claude-sonnet-3.5": "claude-3-5-sonnet-20240620",
}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
# Set Anthropic key
@@ -526,7 +526,7 @@ class BedrockModel(BaseModel):
},
}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
# Extract provider from model ID
@@ -688,7 +688,7 @@ class OllamaModel(BaseModel):
},
)
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
from ollama import Client
@@ -782,7 +782,7 @@ class TogetherModel(BaseModel):
"redpajama7b": "togethercomputer/RedPajama-INCITE-7B-Chat",
}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
assert together.version >= "1.1.0", "Please upgrade to Together SDK v1.1.0 or later."
@@ -835,7 +835,7 @@ class TogetherModel(BaseModel):
class HumanModel(BaseModel):
MODELS = {"human": {}}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
# Determine which commands require multi-line input
@@ -912,7 +912,7 @@ class HumanThoughtModel(HumanModel):
class ReplayModel(BaseModel):
MODELS = {"replay": {}}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
super().__init__(args, commands)
if self.args.replay_path is None or not Path(self.args.replay_path).exists():
@@ -968,7 +968,7 @@ class InstantEmptySubmitTestModel(BaseModel):
}
}
- def __init__(self, args: ModelArguments, commands: list[Command]):
+ def __init__(self, args: ModelConfig, commands: list[Command]):
"""This model immediately submits. Useful for testing purposes"""
super().__init__(args, commands)
self._action_idx = 0
@@ -988,7 +988,7 @@ class InstantEmptySubmitTestModel(BaseModel):
return history
-def get_model(args: ModelArguments, commands: list[Command] | None = None):
+def get_model(args: ModelConfig, commands: list[Command] | None = None):
"""
Returns correct model object given arguments and commands
"""
diff --git a/sweagent/agent/summarizer.py b/sweagent/agent/summarizer.py
deleted file mode 100644
index 8f8950ef..00000000
--- a/sweagent/agent/summarizer.py
+++ /dev/null
@@ -1,241 +0,0 @@
-from __future__ import annotations
-
-import tempfile
-import textwrap
-import traceback
-from abc import abstractmethod
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-from sweagent.agent.models import APIStats, BaseModel, ContextWindowExceededError, ModelArguments
-from sweagent.environment.swe_env import SWEEnv
-from sweagent.utils.log import get_logger
-
-
-@dataclass
-class SummarizerConfig:
- """The configuration for the summarizer"""
-
- function: Any = "Identity"
- window_length: int = 105
- template: str | None = None
- model: ModelArguments | None = None
- system_template: str | None = None
- instance_template: str | None = None
-
- def __post_init__(self):
- # object.__setattr__(self, "function", SummarizeFunction.get(self.function, self.window_length)) # type: ignore
- if isinstance(self.model, dict):
- object.__setattr__(self, "model", ModelArguments.from_dict(self.summarizer_model)) # type: ignore
-
-
-# ABSTRACT BASE CLASSES
-
-
-class SummarizeFunctionMeta(type):
- """
- Registry maps all inherited classes to their names.
- """
-
- _warning_message = None
-
- _registry = {}
-
- def __new__(cls, name, bases, attrs):
- new_cls = super().__new__(cls, name, bases, attrs)
- if name != "SummarizeFunction":
- cls._registry[name] = new_cls
- return new_cls
-
-
-@dataclass
-class SummarizeFunction(metaclass=SummarizeFunctionMeta):
- """
- Abstract class for summarizing functions.
- We use get to generate the right summarizer based on the name of the summarizer.
- """
-
- def __init__(self, window_length: int):
- self._window_length = window_length
- self.logger = get_logger("summarizer")
-
- def setup(self, instance_args: dict[str, Any], config):
- """
- Additional setup function for the summarizer.
- """
- pass
-
- @staticmethod
- def _slugify_action(action: str) -> str:
- return "".join(c if c.isalnum() else "_" for c in action)[:50]
-
- @staticmethod
- def _upload_file_to_container(file_content: str, file_path_on_container: str, env: SWEEnv):
- assert env.container_obj is not None
- env.communicate(f'mkdir -p "{Path(file_path_on_container).parent}"')
- with tempfile.NamedTemporaryFile() as fp:
- fp.write(file_content.encode("utf-8"))
- fp.flush()
- copy_anything_to_container(env.container_obj, fp.name, file_path_on_container)
-
- @abstractmethod
- def __call__(self, input: str, observation, env: SWEEnv, model: type[BaseModel]) -> tuple[str, APIStats]:
- """
- Abstract method for getting an observation and summarize it.
- The returned value should be a summation of the given observation.
- """
- raise NotImplementedError
-
- @classmethod
- def get(cls, name: str, window_length: int):
- try:
- return cls._registry[name](window_length)
- except KeyError:
- msg = f"Model output summarizer ({name}) not found."
- raise ValueError(msg)
-
-
-# DEFINE NEW SUMMARIZE FUNCTIONS BELOW THIS LINE
-
-
-class SimpleSummarizer(SummarizeFunction):
- """
- Saves the output of the command to a file and uses the open command to show the output.
- """
-
- _warning_message = """\
- Warning: Command output exceeded window, saved command to a file {command_file_name} and opened the file at line 1.
-
-
- """
-
- block_list_input = [
- "create",
- "open",
- "edit",
- "scroll_up",
- "scroll_down",
- "goto",
- "search_file",
- "search_dir",
- ]
-
- def __call__(self, input: str, observation: str, env: SWEEnv, model: BaseModel) -> tuple[str, APIStats]:
- try:
- if (
- any(input.startswith(s) for s in self.block_list_input)
- or len(observation.splitlines()) <= self._window_length
- ):
- return observation, APIStats()
- self.logger.debug(f"Summarizing current observation for input {input}")
- command_file_name = "/output/" + self._slugify_action(input)
- self._upload_file_to_container(observation, command_file_name, env)
- return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + env.communicate(
- f"open {command_file_name}"
- ), APIStats()
- except Exception:
- self.logger.warning(
- f"Unhandled exception occurred when trying to summarize observation for input {input}: {traceback.format_exc()}"
- )
- return observation, APIStats()
-
-
-class Identity(SummarizeFunction):
- """
- This summarizer does not do any summation. It returns the environment observation as is.
- """
-
- def __call__(self, input: str, observation: str, env: SWEEnv, model: type[BaseModel]) -> tuple[str, APIStats]:
- """
- This doesn't do any summarization. It just returns the environment observation.
- """
- return observation, APIStats()
-
-
-class LMSummarizer(SummarizeFunction):
- _warning_message = """\
- Warning: Command output exceeded window size, saved command to a file {command_file_name} and summarized the command output for you.
- If you still want to view the output of the command, use the following command `open {command_file_name}`.
-
-
- SUMMARY:
- """
-
- _warning_message_summarization_failed = """\
- Warning: Command output exceeded window size, saved command to a file {command_file_name}.
- If you still want to view the output of the command, use the following command `open {command_file_name}`.
- """
-
- block_list_input = [
- "create",
- "open",
- "edit",
- "scroll_up",
- "scroll_down",
- "goto",
- "search_file",
- "search_dir",
- ]
-
- fail_back_to_simple_summarizer_input = [
- "xxd",
- "hexdump",
- "strings",
- ]
-
- lm_summarizer_char_limit = 200000
-
- def __init__(self, window_length: int):
- super().__init__(window_length)
- self.history = []
- self._simple_summarizer = SimpleSummarizer(window_length=window_length)
-
- def setup(self, instance_args: dict[str, Any], config):
- self.name = "ctf_summarizer"
- self.system_args = config.__dict__
- self.system_args.update({f"summarizer_{k}": v for k, v in config.summarizer_config.__dict__.items()})
- system_msg = config.summarizer_config.system_template.format(**self.system_args)
- self.history.append({"role": "system", "content": system_msg, "agent": self.name})
- self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
- self.instance_template = config.summarizer_config.instance_template
- self.instance_args = instance_args
-
- def __call__(self, input: str, observation: str, env: SWEEnv, model: BaseModel) -> tuple[str, APIStats]:
- try:
- if (
- any(input.startswith(s) for s in self.block_list_input)
- or len(observation.splitlines()) <= self._window_length
- ):
- return observation, APIStats()
- if len(observation) > self.lm_summarizer_char_limit or any(
- input.startswith(s) for s in self.fail_back_to_simple_summarizer_input
- ):
- self.logger.warning("Observation is too long for LMSummarizer, using SimpleSummarizer instead")
- return self._simple_summarizer(input, observation, env, model)
- self.logger.debug(f"Summarizing current observation for input {input}")
- command_file_name = "/output/" + self._slugify_action(input)
- self._upload_file_to_container(observation, command_file_name, env)
- self.history.append(
- {
- "role": "user",
- "content": self.instance_template.format(
- **self.instance_args, **self.system_args, command=input, observation=observation
- ),
- "agent": self.name,
- }
- )
- response = model.query(history=self.history)
- stats = model.stats
- model.reset_stats(APIStats())
- self.history.pop()
- return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + response, stats
- except ContextWindowExceededError:
- return textwrap.dedent(
- self._warning_message_summarization_failed.format(command_file_name=command_file_name)
- ), APIStats()
- except Exception:
- self.logger.warning(
- f"Unhandled exception occurred when trying to summarize observation for input {input}: {traceback.format_exc()}"
- )
- return observation, APIStats()
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index 0f7ce5b0..93464617 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -32,7 +32,7 @@ from flask_socketio import SocketIO
from sweagent import CONFIG_DIR, PACKAGE_DIR
from sweagent.agent.agents import AgentConfig
-from sweagent.agent.models import ModelArguments
+from sweagent.agent.models import ModelConfig
from sweagent.api.hooks import AgentUpdateHook, EnvUpdateHook, MainUpdateHook, WebUpdate
from sweagent.api.utils import AttrDict, ThreadWithExc
from sweagent.environment.swe_env import EnvironmentConfig
@@ -172,7 +172,7 @@ def run():
actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),
raise_exceptions=True,
)
- defaults.agent.model = ModelArguments(
+ defaults.agent.model = ModelConfig(
name=model_name,
total_cost_limit=0.0,
per_instance_cost_limit=3.0,
diff --git a/sweagent/main/run_basic.py b/sweagent/main/run_basic.py
index 412d5287..0c478a2b 100644
--- a/sweagent/main/run_basic.py
+++ b/sweagent/main/run_basic.py
@@ -12,16 +12,14 @@ from pydantic_settings import BaseSettings, CliApp
from sweagent import CONFIG_DIR
from sweagent.agent.agents import Agent, AgentConfig
-from sweagent.agent.models import ModelArguments
+from sweagent.agent.models import ModelConfig
from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
from sweagent.utils.log import get_logger
class BasicRunArguments(BaseSettings):
env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
- agent: AgentConfig = AgentConfig(
- model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
- )
+ agent: AgentConfig = AgentConfig(model=ModelConfig(name="human"), next_step_template="Observation: {observation}")
traj_dir: str = "."
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index a8651bf6..06863192 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -12,7 +12,7 @@ from pydantic import Field
from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
-from sweagent.agent.models import ModelArguments
+from sweagent.agent.models import ModelConfig
from sweagent.environment.swe_env import SWEEnv
from sweagent.run.batch_instances import BatchInstance, BatchInstanceSourceConfig
from sweagent.run.common import BasicCLI, save_predictions
@@ -23,9 +23,7 @@ from sweagent.utils.log import get_logger
class RunBatchConfig(BaseSettings, cli_implicit_flags=True):
instances: BatchInstanceSourceConfig = Field(union_mode="left_to_right")
- agent: AgentConfig = AgentConfig(
- model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
- )
+ agent: AgentConfig = AgentConfig(model=ModelConfig(name="human"), next_step_template="Observation: {observation}")
traj_dir: Path = Path(".")
raise_exceptions: bool = False
redo_existing: bool = False
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index f8ce68ce..2ac2bf94 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -13,7 +13,7 @@ from swerex.deployment.abstract import AbstractDeployment
from sweagent import CONFIG_DIR
from sweagent.agent.agents import Agent, AgentConfig
-from sweagent.agent.models import ModelArguments
+from sweagent.agent.models import ModelConfig
from sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfig
from sweagent.environment.config.problem_statement import EmptyProblemStatement
from sweagent.environment.config.repo import RepoConfig
@@ -86,7 +86,7 @@ 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 = ModelArguments(name="replay", replay_path=str(self._replay_action_trajs_path))
+ agent_config.model = ModelConfig(name="replay", replay_path=str(self._replay_action_trajs_path))
return Agent("replay", agent_config)
def _get_run_single(self) -> RunSingle:
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index c8dbe069..30a4170f 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -9,7 +9,7 @@ from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
-from sweagent.agent.models import ModelArguments
+from sweagent.agent.models import ModelConfig
from sweagent.environment.config.problem_statement import (
EmptyProblemStatement,
ProblemStatement,
@@ -35,9 +35,7 @@ class RunSingleActionConfig(BaseModel, cli_implicit_flags=True):
class RunSingleConfig(BaseSettings, cli_implicit_flags=True):
env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
- agent: AgentConfig = AgentConfig(
- model=ModelArguments(name="human"), next_step_template="Observation: {observation}"
- )
+ agent: AgentConfig = AgentConfig(model=ModelConfig(name="human"), next_step_template="Observation: {observation}")
problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
traj_dir: Path = Path(".")
actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
diff --git a/tests/test_models.py b/tests/test_models.py
index 3d1ae641..84f490ef 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock, Mock, patch
import pytest
-from sweagent.agent.models import GroqModel, ModelArguments, OpenAIModel, TogetherModel
+from sweagent.agent.models import GroqModel, ModelConfig, 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 = ModelArguments(name=model_name)
+ model_args = ModelConfig(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 models
def test_groq_model(openai_mock_client):
for model_name in list(GroqModel.MODELS) + list(GroqModel.SHORTCUTS):
- model_args = ModelArguments(name=model_name)
+ model_args = ModelConfig(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 = ModelArguments(name=model_name)
+ model_args = ModelConfig(name=model_name)
model = TogetherModel(model_args, [])
model.query(TEST_HISTORY)