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]

Instantiate HistoryProcessor via pydantic; default values & pydantic-settings

Kilian Lieret7f6ffb8a684b
diff --git a/config/default.yaml b/config/default.yaml
index 58b18bc8..2c2df3e1 100644
--- a/config/default.yaml
+++ b/config/default.yaml
@@ -107,5 +107,7 @@ agent:
echo '{"open_file": "'$(realpath "$CURRENT_FILE")'", "working_dir": "'$working_dir'"}';
fi
};
- parse_function: ThoughtActionParser
- history_processor: Last5Observations
+ parse_function: ThoughtActionParser
+ history_processor:
+ type: last_n_observations
+ n: 5
diff --git a/config/default_from_url.yaml b/config/default_from_url.yaml
index 85737250..6ce90b3d 100644
--- a/config/default_from_url.yaml
+++ b/config/default_from_url.yaml
@@ -110,4 +110,6 @@ agent:
echo '{"open_file": "'$(realpath "$CURRENT_FILE")'", "working_dir": "'$working_dir'"}';
fi
};
- history_processor: Last5Observations
+ history_processor:
+ type: last_n_observations
+ n: 5
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 65feeace..18d0af24 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -7,12 +7,12 @@ from collections import defaultdict
from pathlib import Path
from typing import Any
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict, Field
from simple_parsing.helpers.fields import field
from tenacity import RetryError
from sweagent import __version__, get_agent_commit_hash
-from sweagent.agent.history_processors import HistoryProcessor
+from sweagent.agent.history_processors import DefaultHistoryProcessor, HistoryProcessor
from sweagent.agent.hooks.abstract import AbstractAgentHook, CombinedAgentHook
from sweagent.agent.models import (
APIStats,
@@ -63,14 +63,13 @@ class TemplateConfig(BaseModel):
class AgentConfig(BaseModel):
- templates: TemplateConfig = TemplateConfig()
- tools: ToolConfig = ToolConfig()
+ 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)
- # 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] = {}
-
- model: ModelConfig = ModelConfig()
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
# todo: Move parse function to tools
@@ -119,9 +118,7 @@ class Agent:
#: solution attempt to the next
self._forwarded_vars: dict[str, Any] = {}
- self._history_processor = HistoryProcessor.get(
- self.config.history_processor, **self.config.history_processor_args
- )
+ self._history_processor = self._args.history_processor
# todo: move to tools
self._parse_function = ParseFunction.get(self.config.tools.parse_function)
diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.py
index 1848b771..5a78c706 100644
--- a/sweagent/agent/history_processors.py
+++ b/sweagent/agent/history_processors.py
@@ -2,51 +2,33 @@ from __future__ import annotations
import re
from abc import abstractmethod
-from dataclasses import dataclass
+from typing import Annotated, Literal, Protocol
+
+from pydantic import BaseModel, ConfigDict, Field
class FormatError(Exception):
pass
-# ABSTRACT BASE CLASSES
-
-
-class HistoryProcessorMeta(type):
- _registry = {}
-
- def __new__(cls, name, bases, attrs):
- new_cls = super().__new__(cls, name, bases, attrs)
- if name != "HistoryProcessor":
- cls._registry[name] = new_cls
- return new_cls
-
-
-@dataclass
-class HistoryProcessor(metaclass=HistoryProcessorMeta):
- def __init__(self, *args, **kwargs):
- pass
-
+class AbstractHistoryProcessor(Protocol):
@abstractmethod
def __call__(self, history: list[str]) -> list[str]:
raise NotImplementedError
- @classmethod
- def get(cls, name, *args, **kwargs):
- try:
- return cls._registry[name](*args, **kwargs)
- except KeyError:
- msg = f"Model output parser ({name}) not found."
- raise ValueError(msg)
+class DefaultHistoryProcessor(BaseModel):
+ type: Literal["default"] = "default"
+ """Do not change. Used for (de)serialization."""
+
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
-# DEFINE NEW PARSING FUNCTIONS BELOW THIS LINE
-class DefaultHistoryProcessor(HistoryProcessor):
def __call__(self, history):
return history
-def last_n_history(history, n):
+def _last_n_history(history, n):
if n <= 0:
msg = "n must be a positive integer"
raise ValueError(msg)
@@ -71,27 +53,29 @@ def last_n_history(history, n):
return new_history
-class LastNObservations(HistoryProcessor):
- def __init__(self, n):
- self.n = n
+class LastNObservations(BaseModel):
+ """Keep the last n observations"""
- def __call__(self, history):
- return last_n_history(history, self.n)
+ n: int
+ type: Literal["last_n_observations"] = "last_n_observations"
+ """Do not change. Used for (de)serialization."""
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
-class Last2Observations(HistoryProcessor):
def __call__(self, history):
- return last_n_history(history, 2)
+ return _last_n_history(history, self.n)
-class Last5Observations(HistoryProcessor):
- def __call__(self, history):
- return last_n_history(history, 5)
+class ClosedWindowHistoryProcessor(BaseModel):
+ type: Literal["closed_window"] = "closed_window"
+ """Do not change. Used for (de)serialization."""
+ _pattern = re.compile(r"^(\d+)\:.*?(\n|$)", re.MULTILINE)
+ _file_pattern = re.compile(r"\[File:\s+(.*)\s+\(\d+\s+lines\ total\)\]")
-class ClosedWindowHistoryProcessor(HistoryProcessor):
- pattern = re.compile(r"^(\d+)\:.*?(\n|$)", re.MULTILINE)
- file_pattern = re.compile(r"\[File:\s+(.*)\s+\(\d+\s+lines\ total\)\]")
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
def __call__(self, history):
new_history = list()
@@ -107,9 +91,9 @@ class ClosedWindowHistoryProcessor(HistoryProcessor):
if data.get("is_demo", False):
new_history.append(entry)
continue
- matches = list(self.pattern.finditer(entry["content"]))
+ matches = list(self._pattern.finditer(entry["content"]))
if len(matches) >= 1:
- file_match = self.file_pattern.search(entry["content"])
+ file_match = self._file_pattern.search(entry["content"])
if file_match:
file = file_match.group(1)
else:
@@ -125,3 +109,8 @@ class ClosedWindowHistoryProcessor(HistoryProcessor):
windows.add(file)
new_history.append(data)
return list(reversed(new_history))
+
+
+HistoryProcessor = Annotated[
+ DefaultHistoryProcessor | LastNObservations | ClosedWindowHistoryProcessor, Field(discriminator="type")
+]
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.py
index 40350fe6..b686f5a8 100644
--- a/sweagent/environment/config/problem_statement.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -1,7 +1,7 @@
import hashlib
import uuid
from pathlib import Path
-from typing import Annotated, Any, Literal, Protocol
+from typing import Any, Literal, Protocol
from pydantic import BaseModel, Field
@@ -76,6 +76,4 @@ class GithubIssue(BaseModel):
)
-ProblemStatementConfig = Annotated[
- TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement, Field(union_mode="left_to_right")
-]
+ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement
diff --git a/sweagent/run/common.py b/sweagent/run/common.py
index 7108178c..edfafd4e 100644
--- a/sweagent/run/common.py
+++ b/sweagent/run/common.py
@@ -5,10 +5,12 @@ from argparse import ArgumentParser
from pathlib import Path
import yaml
+from pydantic import ValidationError
from pydantic_settings import BaseSettings, CliApp
from sweagent import CONFIG_DIR
from sweagent.types import AgentInfo, AgentRunResult
+from sweagent.utils.log import get_logger
# todo: Parameterize type hints
@@ -16,6 +18,7 @@ class BasicCLI:
def __init__(self, arg_type: type[BaseSettings], default_settings: bool = True):
self.arg_type = arg_type
self.default_settings = default_settings
+ self.logger = get_logger("CLI", emoji="⚙️")
def get_args(self, args=None) -> BaseSettings:
# The defaults if no config file is provided
@@ -49,15 +52,32 @@ class BasicCLI:
config_merged = {}
if cli_args.config:
for _f in cli_args.config:
- _loaded = yaml.safe_load(Path(_f).read_text())
+ txt = Path(_f).read_text()
+ if not txt.strip():
+ self.logger.warning(f"Config file {_f} is empty")
+ continue
+ _loaded = yaml.safe_load(txt)
config_merged.update(_loaded)
elif self.default_settings and not cli_args.no_config_file:
- config_merged = yaml.safe_load((CONFIG_DIR / "default.yaml").read_text())
+ config_file = CONFIG_DIR / "default.yaml"
+ self.logger.info(f"Loading default config from {config_file}")
+ txt = config_file.read_text()
+ if not txt.strip():
+ self.logger.warning(f"Default config file {config_file} is empty")
+ config_merged = {}
+ else:
+ config_merged = yaml.safe_load(txt)
else:
config_merged = {}
- # args = ScriptArguments.model_validate(config_merged)
- args = CliApp.run(self.arg_type, remaining_args, **config_merged) # type: ignore
+ try:
+ args = CliApp.run(self.arg_type, remaining_args, **config_merged) # type: ignore
+ except (ValidationError, AttributeError, TypeError):
+ print("Merged configuration dictionary:")
+ print("-" * 40)
+ print(yaml.dump(config_merged))
+ print("-" * 40)
+ raise
if cli_args.print_config: # type: ignore
print(yaml.dump(args.model_dump()))
exit(0)
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 9afd583c..50cc3504 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -22,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()
+ agent: AgentConfig = Field(default_factory=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 2593281e..ca105004 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -27,17 +27,17 @@ 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 = OpenPRConfig()
+ pr_config: OpenPRConfig = Field(default_factory=OpenPRConfig)
# When working with local repository: Apply patch
apply_patch_locally: bool = False
class RunSingleConfig(BaseSettings, cli_implicit_flags=True):
- env: EnvironmentConfig = EnvironmentConfig()
- agent: AgentConfig = AgentConfig()
+ env: EnvironmentConfig = Field(default_factory=EnvironmentConfig)
+ agent: AgentConfig = Field(default_factory=AgentConfig)
problem_statement: ProblemStatementConfig = Field(default_factory=EmptyProblemStatement)
traj_dir: Path = Path(".")
- actions: RunSingleActionConfig = RunSingleActionConfig()
+ actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
print_config: bool = False
"""Print config at the beginning of the run."""