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]

Simpler setting of pydantic defaults; pydantic config

Kilian Lieret4f972256a09a
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 24d7c83d..5b1f58e0 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -36,8 +36,7 @@ from sweagent.utils.log import get_logger
class TemplateConfig(BaseModel):
system_template: str = ""
instance_template: str = ""
- next_step_template: str = None # type: ignore
- """Template for the next step. Defaults to instance_template."""
+ next_step_template: str = "Observation: {observation}"
next_step_no_output_template: str = None # type: ignore
"""Template for the next step when the last output was empty. Defaults to next_step_template."""
@@ -55,8 +54,6 @@ class TemplateConfig(BaseModel):
def model_post_init(self, __context):
self.demonstrations = _convert_paths_to_abspath(self.demonstrations)
- if self.next_step_template is None:
- self.next_step_template = self.instance_template
if self.next_step_no_output_template is None:
self.next_step_no_output_template = self.next_step_template
@@ -89,19 +86,17 @@ class ToolFilterConfig(BaseModel):
"su",
]
# todo: probably rename this
- block_unless_regex: dict[str, str] = field(
- default_factory=lambda: {
- "radare2": r"\b(?:radare2)\b.*\s+-c\s+.*",
- "r2": r"\b(?:radare2)\b.*\s+-c\s+.*",
- }
- )
+ block_unless_regex: dict[str, str] = {
+ "radare2": r"\b(?:radare2)\b.*\s+-c\s+.*",
+ "r2": r"\b(?:radare2)\b.*\s+-c\s+.*",
+ }
class ToolConfig(BaseModel):
- filter: ToolFilterConfig = field(default_factory=ToolFilterConfig)
- command_files: list[str] = field(default_factory=list)
- env_variables: dict[str, Any] = field(default_factory=dict)
- util_functions: list[str] = field(default_factory=list)
+ filter: ToolFilterConfig = ToolFilterConfig()
+ command_files: list[str] = []
+ env_variables: dict[str, Any] = {}
+ util_functions: list[str] = []
submit_command: str = "submit"
parse_function: Any = "ThoughtActionParser"
parse_command: Any = "ParseCommandBash"
@@ -110,11 +105,11 @@ class ToolConfig(BaseModel):
"""Defaults to format_error_template in ParseFunction"""
command_docs: str = None # type: ignore
- multi_line_command_endings: dict[str, str] = field(default_factory=dict)
+ multi_line_command_endings: dict[str, str] = {}
submit_command_end_name: str | None = None
- install_commands: list[str] = field(default_factory=list)
- reset_commands: list[str] = field(default_factory=list)
+ install_commands: list[str] = []
+ reset_commands: list[str] = []
@property
def commands(self) -> list[Command]:
@@ -168,24 +163,22 @@ class ToolConfig(BaseModel):
# todo: factor out tools config and potentially try to only give it to SWEEnv. Agent should only need allow-lists and the final tools documentation
class AgentConfig(BaseModel):
- templates: TemplateConfig = field(default_factory=TemplateConfig)
- tools: ToolConfig = field(default_factory=ToolConfig)
+ templates: TemplateConfig = TemplateConfig()
+ tools: ToolConfig = ToolConfig()
# todo: Why can't we just configure this in the same way as the models?
history_processor: Any = "DefaultHistoryProcessor"
- history_processor_args: dict[str, Any] = field(default_factory=dict)
+ history_processor_args: dict[str, Any] = {}
- state_command: Command = field(
- default_factory=lambda: Command(
- name="state",
- code="""state() {
+ state_command: Command = Command(
+ name="state",
+ code="""state() {
echo '{"working_dir": "'$(realpath --relative-to=$ROOT/.. $PWD)'"}';
};""",
- )
)
"""Should extract environment state in a json readable form"""
- model: ModelConfig = field(default_factory=lambda: ModelConfig(name="gpt4"))
+ model: ModelConfig = ModelConfig(name="gpt4")
# todo: separate out from_config. In particular separate out model (as a class, etc.)
@@ -798,7 +791,6 @@ class Agent:
"""
self._problem_statement = problem_statement
self._env = env
- # todo: Shouldn't this be moved to setup?
self.setup(init_model_stats)
# Save/reset some attributes
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 1f6609db..7dbb9ce2 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -7,7 +7,7 @@ import shlex
from pathlib import PurePath
from typing import Self
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from swerex.deployment.abstract import AbstractDeployment
from swerex.runtime.abstract import BashAction, CreateBashSessionRequest, WriteFileRequest
@@ -31,8 +31,8 @@ class EnvironmentConfig(BaseModel):
repo: RepoConfig | None = None
startup_commands: list[str] = []
- class Config:
- extra = "forbid"
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
class SWEEnv:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 06863192..9afd583c 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -12,7 +12,6 @@ from pydantic import Field
from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
-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,7 +22,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=ModelConfig(name="human"), next_step_template="Observation: {observation}")
+ agent: AgentConfig = AgentConfig()
traj_dir: Path = Path(".")
raise_exceptions: bool = False
redo_existing: bool = False
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index 30a4170f..2593281e 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -5,11 +5,10 @@ from pathlib import Path
from typing import Self
import yaml
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from pydantic_settings import BaseSettings
from sweagent.agent.agents import Agent, AgentConfig
-from sweagent.agent.models import ModelConfig
from sweagent.environment.config.problem_statement import (
EmptyProblemStatement,
ProblemStatement,
@@ -28,23 +27,23 @@ class RunSingleActionConfig(BaseModel, cli_implicit_flags=True):
# Open a PR with the patch if we can solve the issue
open_pr: bool = False
- pr_config: OpenPRConfig = Field(default_factory=OpenPRConfig)
+ pr_config: OpenPRConfig = OpenPRConfig()
# When working with local repository: Apply patch
apply_patch_locally: bool = False
class RunSingleConfig(BaseSettings, cli_implicit_flags=True):
- env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
- agent: AgentConfig = AgentConfig(model=ModelConfig(name="human"), next_step_template="Observation: {observation}")
+ env: EnvironmentConfig = EnvironmentConfig()
+ agent: AgentConfig = AgentConfig()
problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
traj_dir: Path = Path(".")
- actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
+ actions: RunSingleActionConfig = RunSingleActionConfig()
print_config: bool = False
"""Print config at the beginning of the run."""
- class Config:
- extra = "forbid"
+ # pydantic config
+ model_config = ConfigDict(extra="forbid") # type: ignore
class RunSingle:
diff --git a/tests/test_run.py b/tests/test_run.py
index c7a1253e..eee17d77 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -8,6 +8,8 @@ def test_run_cli_no_arg_error():
"sweagent",
]
output = subprocess.run(args, check=False, capture_output=True)
+ print(output.stdout.decode())
+ print(output.stderr.decode())
assert output.returncode == 2
assert "run-batch" in output.stdout.decode()
assert "run-replay" in output.stdout.decode()
diff --git a/tests/test_run_single.py b/tests/test_run_single.py
index ecf272b7..186f7568 100644
--- a/tests/test_run_single.py
+++ b/tests/test_run_single.py
@@ -19,7 +19,11 @@ class RaisesExceptionHook(RunHook):
@pytest.mark.slow
def test_run_single_raises_exception():
- rs = RunSingle.from_config(RunSingleConfig())
+ rsc = RunSingleConfig()
+ rsc.agent.model.name = "instant_empty_submit"
+ rsc.agent.model.model_post_init(None)
+ rsc.agent.model_post_init(None)
+ rs = RunSingle.from_config(rsc)
rs.add_hook(RaisesExceptionHook())
with pytest.raises(ValueError, match="test exception"):
rs.run()