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 ActionParser etc. via pydantic

Kilian Lieret455612915cf2
diff --git a/config/default.yaml b/config/default.yaml
index 2c2df3e1..4ddfa43d 100644
--- a/config/default.yaml
+++ b/config/default.yaml
@@ -95,7 +95,8 @@ agent:
- config/commands/edit_linting.sh
- config/commands/_split_string.py
- config/commands/submit.sh
- parse_command: ParseCommandDetailed
+ parse_command:
+ type: detailed
state_command:
name: state
code: |
@@ -107,7 +108,8 @@ agent:
echo '{"open_file": "'$(realpath "$CURRENT_FILE")'", "working_dir": "'$working_dir'"}';
fi
};
- parse_function: ThoughtActionParser
+ parse_function:
+ type: thought_action
history_processor:
type: last_n_observations
n: 5
diff --git a/config/default_from_url.yaml b/config/default_from_url.yaml
index 6ce90b3d..dbdd9dd4 100644
--- a/config/default_from_url.yaml
+++ b/config/default_from_url.yaml
@@ -97,8 +97,10 @@ agent:
- config/commands/edit_linting.sh
- config/commands/_split_string.py
- config/commands/submit.sh
- parse_function: ThoughtActionParser
- parse_command: ParseCommandDetailed
+ parse_function:
+ type: thought_action
+ parse_command:
+ type: detailed
state_command:
name: state
code: |
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 18d0af24..ab4df1d4 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -23,7 +23,7 @@ from sweagent.agent.models import (
)
from sweagent.environment.config.problem_statement import ProblemStatement, ProblemStatementConfig
from sweagent.environment.swe_env import SWEEnv
-from sweagent.tools.parsing import FormatError, ParseFunction
+from sweagent.tools.parsing import FormatError
from sweagent.tools.tools import ToolConfig, ToolHandler
from sweagent.types import AgentInfo, AgentRunResult, History, HistoryItem, Trajectory, TrajectoryStep
from sweagent.utils.config import _convert_paths_to_abspath, keys_config
@@ -120,9 +120,6 @@ class Agent:
self._history_processor = self._args.history_processor
- # todo: move to tools
- self._parse_function = ParseFunction.get(self.config.tools.parse_function)
-
self._chook = CombinedAgentHook()
def add_hook(self, hook: AbstractAgentHook) -> None:
@@ -454,15 +451,12 @@ class Agent:
action: action that the model proposes
output: raw model output
"""
+ assert self._tool_handler is not None
# Condition for handling outputs with no thought (just action)
if self.model.args.name == "human":
return "", output, output
elif self.model.args.name == "human_thought":
- thought, action = ParseFunction.get("ThoughtActionParser")(
- output,
- self.config.tools.commands,
- strict=False,
- )
+ thought, action = self._tool_handler.parse_actions(output)
return thought, action, output
format_fails = blocklist_fails = 0
@@ -470,10 +464,8 @@ class Agent:
assert self._tool_handler is not None
while format_fails + blocklist_fails <= 2:
try:
- thought, action = self._parse_function(
+ thought, action = self._tool_handler.parse_actions(
output,
- self.config.tools.commands,
- strict=False,
)
except KeyboardInterrupt:
raise
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index eef1b2ad..6821413b 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -20,7 +20,7 @@ from tenacity import (
wait_random_exponential,
)
-from sweagent.agent.commands import Command
+from sweagent.tools.commands import Command
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.py
index b686f5a8..959de445 100644
--- a/sweagent/environment/config/problem_statement.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -3,10 +3,13 @@ import uuid
from pathlib import Path
from typing import Any, Literal, Protocol
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from sweagent.utils.config import keys_config
from sweagent.utils.github import _get_problem_statement_from_github_issue, _parse_gh_issue_url
+from sweagent.utils.log import get_logger
+
+logger = get_logger("Config", emoji="⚙️")
class ProblemStatement(Protocol):
@@ -22,20 +25,25 @@ class EmptyProblemStatement(BaseModel):
type: Literal["empty"] = "empty"
"""Discriminator for (de)serialization/CLI. Do not change."""
+ model_config = ConfigDict(extra="forbid")
+
def get_problem_statement(self) -> str:
return ""
class TextProblemStatement(BaseModel):
- text: str = ""
+ text: str
type: Literal["text"] = "text"
"""Discriminator for (de)serialization/CLI. Do not change."""
id: str = None # type: ignore
+ model_config = ConfigDict(extra="forbid")
+
def model_post_init(self, __context: Any) -> None:
if self.id is None:
+ logger.info("Setting problem statement id to hash of text")
self.id = hashlib.sha256(self.text.encode()).hexdigest()[:6]
def get_problem_statement(self) -> str:
@@ -43,31 +51,39 @@ class TextProblemStatement(BaseModel):
class FileProblemStatement(BaseModel):
- path: str = ""
+ path: Path
type: Literal["text_file"] = "text_file"
"""Discriminator for (de)serialization/CLI. Do not change."""
id: str = None # type: ignore
+ model_config = ConfigDict(extra="forbid")
+
def model_post_init(self, __context: Any) -> None:
if self.id is None:
+ logger.info("Setting problem statement id to hash of file contents (path: %s)", self.path)
self.id = hashlib.sha256(self.get_problem_statement().encode()).hexdigest()[:6]
def get_problem_statement(self) -> str:
- return Path(self.path).read_text()
+ return self.path.read_text()
class GithubIssue(BaseModel):
- url: str = ""
+ url: str
type: Literal["github"] = "github"
"""Discriminator for (de)serialization/CLI. Do not change."""
- @property
- def id(self) -> str:
- owner, repo, issue_number = _parse_gh_issue_url(self.url)
- return f"{owner}__{repo}-i{issue_number}"
+ id: str = None # type: ignore
+
+ model_config = ConfigDict(extra="forbid")
+
+ def model_post_init(self, __context: Any) -> None:
+ if self.id is None:
+ logger.info("Setting problem statement based on github issue url")
+ owner, repo, issue_number = _parse_gh_issue_url(self.url)
+ self.id = f"{owner}__{repo}-i{issue_number}"
def get_problem_statement(self) -> str:
owner, repo, issue_number = _parse_gh_issue_url(self.url)
diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.py
index 3ec5051e..738771bd 100644
--- a/sweagent/run/batch_instances.py
+++ b/sweagent/run/batch_instances.py
@@ -2,7 +2,7 @@ import json
import re
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Annotated, Any, Literal
+from typing import Any, Literal
import yaml
from pydantic import BaseModel, Field, TypeAdapter
@@ -153,7 +153,4 @@ class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):
return _filter_batch_items(instances, self.filter)
-BatchInstanceSourceConfig = Annotated[
- InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances | ExpertInstancesFromFile,
- Field(union_mode="left_to_right"),
-]
+BatchInstanceSourceConfig = InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances | ExpertInstancesFromFile
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 50cc3504..60b1088b 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -21,7 +21,7 @@ from sweagent.utils.log import get_logger
class RunBatchConfig(BaseSettings, cli_implicit_flags=True):
- instances: BatchInstanceSourceConfig = Field(union_mode="left_to_right")
+ instances: BatchInstanceSourceConfig
agent: AgentConfig = Field(default_factory=AgentConfig)
traj_dir: Path = Path(".")
raise_exceptions: bool = False
diff --git a/sweagent/agent/commands.py b/sweagent/tools/commands.py
similarity index 86%
rename from sweagent/agent/commands.py
rename to sweagent/tools/commands.py
index 524b65e2..1732f7ae 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/tools/commands.py
@@ -1,30 +1,14 @@
from __future__ import annotations
import re
-from abc import abstractmethod
-from dataclasses import dataclass
+from abc import ABC, abstractmethod
from pathlib import Path
+from typing import Literal
import yaml
from pydantic import BaseModel
-class AssistantMetadata(BaseModel):
- """Pass observations to the assistant, and get back a response."""
-
- system_template: str | None = None
- instance_template: str | None = None
-
-
-# TODO: first can be used for two-stage actions
-# TODO: eventually might control high-level control flow
-class ControlMetadata(BaseModel):
- """TODO: should be able to control high-level control flow after calling this command"""
-
- next_step_template: str | None = None
- next_step_action_template: str | None = None
-
-
class Command(BaseModel):
code: str
name: str
@@ -35,26 +19,7 @@ class Command(BaseModel):
signature: str | None = None
-class ParseCommandMeta(type):
- _registry = {}
-
- def __new__(cls, name, bases, attrs):
- new_cls = super().__new__(cls, name, bases, attrs)
- if name != "ParseCommand":
- cls._registry[name] = new_cls
- return new_cls
-
-
-@dataclass
-class ParseCommand(metaclass=ParseCommandMeta):
- @classmethod
- def get(cls, name):
- try:
- return cls._registry[name]()
- except KeyError:
- msg = f"Command parser ({name}) not found."
- raise ValueError(msg)
-
+class AbstractParseCommand(ABC):
@abstractmethod
def parse_command_file(self, path: str) -> list[Command]:
"""
@@ -73,8 +38,11 @@ class ParseCommand(metaclass=ParseCommandMeta):
# DEFINE NEW COMMAND PARSER FUNCTIONS BELOW THIS LINE
-class ParseCommandBash(ParseCommand):
- def parse_command_file(self, path: str) -> list[Command]:
+class ParseCommandBash(AbstractParseCommand, BaseModel):
+ type: Literal["bash"] = "bash"
+ """Discriminator for (de)serialization/CLI. Do not change."""
+
+ def parse_command_file(self, path: Path) -> list[Command]:
with open(path) as file:
contents = file.read()
if contents.strip().startswith("#!"):
@@ -102,8 +70,7 @@ class ParseCommandBash(ParseCommand):
return commands
def parse_bash_functions(self, path, contents: str) -> list[Command]:
- """
- Simple logic for parsing a bash file and segmenting it into functions.
+ """Simple logic for parsing a bash file and segmenting it into functions.
Assumes that all functions have their name and opening curly bracket in one line,
and closing curly bracket in a line by itself.
@@ -212,6 +179,9 @@ class ParseCommandDetailed(ParseCommandBash):
# arg2 (type) [optional]: "description"
"""
+ type: Literal["detailed"] = "detailed"
+ """Discriminator for (de)serialization/CLI. Do not change."""
+
@staticmethod
def get_signature(cmd):
signature = cmd.name
@@ -253,3 +223,6 @@ class ParseCommandDetailed(ParseCommandBash):
docs += f" - {param} ({settings['type']}) [{req_string}]: {settings['description']}\n"
docs += "\n"
return docs
+
+
+ParseCommand = ParseCommandBash | ParseCommandDetailed
diff --git a/sweagent/tools/parsing.py b/sweagent/tools/parsing.py
index 8f714d7b..6fd0586b 100644
--- a/sweagent/tools/parsing.py
+++ b/sweagent/tools/parsing.py
@@ -5,78 +5,54 @@ import re
import shlex
import string
import textwrap
-from abc import abstractmethod
-from dataclasses import dataclass
+from abc import ABC, abstractmethod
+from typing import Any, Literal
-from sweagent.agent.commands import Command
+from pydantic import BaseModel
+
+from sweagent.tools.commands import Command
class FormatError(Exception):
pass
-# ABSTRACT BASE CLASSES
-
-
-class ParseFunctionMeta(type):
- """
- Registry maps all inherited classes to their names.
- """
-
- _registry = {}
-
- def __new__(cls, name, bases, attrs):
- new_cls = super().__new__(cls, name, bases, attrs)
- if name != "ParseFunction":
- cls._registry[name] = new_cls
- return new_cls
-
-
-@dataclass
-class ParseFunction(metaclass=ParseFunctionMeta):
+class AbstractParseFunction(ABC):
"""
Abstract class for parsing functions.
We use get to generate the right parser based on the name of the parser.
"""
- _error_message = None
+ error_message: str
@abstractmethod
- def __call__(self, model_response, commands: list[Command], strict=False):
+ def __call__(self, model_response, commands: list[Command], strict=False) -> tuple[str, str]:
raise NotImplementedError
@property
def format_error_template(self):
- if self._error_message is None:
- msg = "You must define an error message for your parser."
- raise NotImplementedError(msg)
- return textwrap.dedent(self._error_message)
-
- @classmethod
- def get(cls, name):
- try:
- return cls._registry[name]()
- except KeyError:
- msg = f"Model output parser ({name}) not found."
- raise ValueError(msg)
+ return textwrap.dedent(self.error_message)
# DEFINE NEW PARSING FUNCTIONS BELOW THIS LINE
-class ActionParser(ParseFunction):
+class ActionParser(AbstractParseFunction, BaseModel):
"""
Expects the model response to be a single command.
Example: "ls -l"
"""
- _error_message = """\
+ error_message: str = """\
The command you provided was not recognized. Please specify one of the commands (+ any necessary arguments) from the following list in your response. Do not include any other text.
COMMANDS:
{command_docs}
"""
+ type: Literal["action"] = "action"
+ """Type for (de)serialization. Do not change."""
+
def __call__(self, model_response, commands: list[Command], strict=False):
if model_response.split():
action = model_response.strip().split()[0]
@@ -86,7 +62,7 @@ class ActionParser(ParseFunction):
raise FormatError(msg)
-class ThoughtActionParser(ParseFunction):
+class ThoughtActionParser(AbstractParseFunction, BaseModel):
"""
Expects the model response to be a discussion followed by a command wrapped in backticks.
Example:
@@ -96,7 +72,7 @@ class ThoughtActionParser(ParseFunction):
```
"""
- _error_message = """\
+ error_message: str = """\
Your output was not formatted correctly. You must always include one discussion and one command as part of your response. Make sure you do not have multiple discussion/command tags.
Please make sure your output precisely matches the following format:
DISCUSSION
@@ -107,6 +83,9 @@ class ThoughtActionParser(ParseFunction):
```
"""
+ type: Literal["thought_action"] = "thought_action"
+ """Type for (de)serialization. Do not change."""
+
def __call__(self, model_response, commands: list[Command], strict=False):
"""
Parses the action from the output of the API call.
@@ -142,7 +121,7 @@ class ThoughtActionParser(ParseFunction):
raise FormatError(msg)
-class XMLThoughtActionParser(ParseFunction):
+class XMLThoughtActionParser(AbstractParseFunction, BaseModel):
"""
Expects the model response to be a discussion followed by a command wrapped in XML tags.
Example:
@@ -152,12 +131,15 @@ class XMLThoughtActionParser(ParseFunction):
</command>
"""
- _error_message = """\
+ error_message: str = """\
Your output was not formatted correctly. You must always include one discussion and one command as part of your response. Make sure you do not have multiple discussion/command tags.
Please make sure your output precisely matches the following format:
"""
- def __call__(self, model_response, commands: list[Command], strict=False):
+ type: Literal["xml_thought_action"] = "xml_thought_action"
+ """Type for (de)serialization. Do not change."""
+
+ def __call__(self, model_response, commands: list[Command], strict=False) -> tuple[str, str]:
"""
Parses the action from the output of the API call.
We assume that the action is the last code block in the model_response.
@@ -188,7 +170,7 @@ class XMLThoughtActionParser(ParseFunction):
return thought.strip(), action.strip()
-class EditFormat(ThoughtActionParser):
+class EditFormat(ThoughtActionParser, BaseModel):
"""
Expects the model response to be a discussion followed by a command wrapped in backticks.
Example:
@@ -199,7 +181,7 @@ class EditFormat(ThoughtActionParser):
```
"""
- _error_message = """\
+ error_message: str = """\
Your output was not formatted correctly. You must wrap the replacement text in backticks (```).
Please make sure your output precisely matches the following format:
COMMENTS
@@ -214,37 +196,41 @@ class EditFormat(ThoughtActionParser):
```
"""
+ type: Literal["edit_format"] = "edit_format"
+ """Type for (de)serialization. Do not change."""
-class Identity(ParseFunction):
- """
- This parser does not do any parsing. It just returns the model response as both the thought and action.
- """
- _error_message = """\
+class Identity(AbstractParseFunction, BaseModel):
+ """This parser does not do any parsing. It just returns the model response as both the thought and action."""
+
+ error_message: str = """\
It seems like something went wrong with your output. Please try again.
"""
- def __call__(self, model_response, commands: list[Command], strict=False):
+ type: Literal["identity"] = "identity"
+ """Type for (de)serialization. Do not change."""
+
+ def __call__(self, model_response, commands: list[Command], strict=False) -> tuple[str, str]:
"""
This doesn't do any parsing. It just returns the model response as the thought and action.
"""
return model_response, model_response
-class JsonParser(ParseFunction):
- """
- Expects the model response to be a JSON object.
- """
+class JsonParser(AbstractParseFunction, BaseModel):
+ """Expects the model response to be a JSON object."""
- _error_message = """\
+ error_message: str = """\
Your output could not be parsed as JSON. Please make sure your output 1) is valid JSON and
2) Includes the "thought" and "command" fields.
"""
+ type: Literal["json"] = "json"
+ """Type for (de)serialization. Do not change."""
+
def __call__(self, model_response, commands: list[Command], strict=False):
- """
- Parses the action from the output of the API call.
+ """Parses the action from the output of the API call.
We assume that model output is a JSON object with the following fields:
{
"thought": "discussion text here.",
@@ -295,15 +281,16 @@ class JsonParser(ParseFunction):
action += " " + " ".join(data_command["arguments"].values())
else:
signature = command.signature
+ assert signature is not None
signature = signature.replace("[", "").replace("]", "").replace("<", "{").replace(">", "}")
- signature_args = extract_keys(signature)
+ signature_args = _extract_keys(signature)
command_args = {k: "" for k in signature_args}
if "arguments" in data_command:
for arg in signature_args:
if arg in data_command["arguments"]:
value = data_command["arguments"][arg]
- if should_quote(value, command):
+ if _should_quote(value, command):
value = shlex.quote(value)
command_args[arg] = value
action = signature.format(**command_args)
@@ -314,10 +301,11 @@ class JsonParser(ParseFunction):
raise FormatError(msg)
-def extract_keys(format_string):
- """
- Given a format string, returns a set of all the keys in the format string.
- """
+ParseFunction = ActionParser | ThoughtActionParser | XMLThoughtActionParser | EditFormat | Identity | JsonParser
+
+
+def _extract_keys(format_string: str) -> set[str]:
+ """Given a format string, returns a set of all the keys in the format string."""
formatter = string.Formatter()
keys = set()
for _, field_name, _, _ in formatter.parse(format_string):
@@ -326,8 +314,6 @@ def extract_keys(format_string):
return keys
-def should_quote(value, command):
- """
- Returns True if the value should be quoted, False otherwise.
- """
+def _should_quote(value: Any, command: Command) -> bool:
+ """Returns True if the value should be quoted, False otherwise."""
return isinstance(value, str) and command.end_name is None
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index 18f869a9..97593a07 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -4,12 +4,12 @@ import re
from pathlib import Path
from typing import Any, Self
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from swerex.runtime.abstract import AbstractRuntime, BashAction, WriteFileRequest
from swerex.runtime.abstract import Command as RexCommand
-from sweagent.agent.commands import Command, ParseCommand
-from sweagent.tools.parsing import ParseFunction
+from sweagent.tools.commands import Command, ParseCommand, ParseCommandBash
+from sweagent.tools.parsing import ParseFunction, ThoughtActionParser
from sweagent.tools.utils import _guard_multiline_input
from sweagent.utils.config import _convert_paths_to_abspath
from sweagent.utils.log import get_logger
@@ -60,9 +60,8 @@ class ToolConfig(BaseModel):
submit_command: str = "submit"
- # todo: These should also simply be pydantic objects
- parse_function: Any = "ThoughtActionParser"
- parse_command: Any = "ParseCommandBash"
+ parse_function: ParseFunction = Field(default_factory=ThoughtActionParser)
+ parse_command: ParseCommand = Field(default_factory=ParseCommandBash)
format_error_template: str = None # type: ignore
"""Defaults to format_error_template in ParseFunction"""
@@ -98,9 +97,8 @@ class ToolConfig(BaseModel):
def commands(self) -> list[Command]:
"""Read command files and returned parsed command objects"""
commands = []
- parse_command = ParseCommand.get(self.parse_command)
for file in self.command_files:
- parsed_commands = parse_command.parse_command_file(file)
+ parsed_commands = self.parse_command.parse_command_file(file)
commands.extend([command for command in parsed_commands if not command.name.startswith("_")])
return commands
@@ -108,7 +106,6 @@ class ToolConfig(BaseModel):
def model_post_init(self, __context):
self.command_files = _convert_paths_to_abspath(self.command_files)
- parse_command = ParseCommand.get(self.parse_command)
# for caching:
commands = self.commands
@@ -116,14 +113,13 @@ class ToolConfig(BaseModel):
command.name: command.end_name for command in commands if command.end_name is not None
}
self.multi_line_command_endings = multi_line_command_endings
- self.command_docs = parse_command.generate_command_docs(
+ self.command_docs = self.parse_command.generate_command_docs(
self.commands,
[],
**self.env_variables,
)
- parse_function = ParseFunction.get(self.parse_function)
if self.format_error_template is None:
- self.format_error_template = parse_function.format_error_template
+ self.format_error_template = self.parse_function.format_error_template
self.format_error_template = self.format_error_template.format(**self.__dict__)
for command in commands:
if command.name == self.submit_command:
@@ -312,3 +308,7 @@ class ToolHandler:
if match is None:
return None
return match.group(1)
+
+ def parse_actions(self, output: str) -> tuple[str, str]:
+ """Parse the model output into a thought and action."""
+ return self.config.parse_function(output, self.config.commands)
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 071fea4c..4833d3ee 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -2,30 +2,18 @@ from __future__ import annotations
import pytest
-from sweagent.agent.commands import Command
+from sweagent.tools.commands import Command
from sweagent.tools.parsing import (
ActionParser,
EditFormat,
FormatError,
Identity,
JsonParser,
- ParseFunction,
ThoughtActionParser,
XMLThoughtActionParser,
)
-def test_parse_function_registry():
- assert isinstance(ParseFunction.get("ActionParser"), ActionParser)
- assert isinstance(ParseFunction.get("ThoughtActionParser"), ThoughtActionParser)
- assert isinstance(ParseFunction.get("XMLThoughtActionParser"), XMLThoughtActionParser)
- assert isinstance(ParseFunction.get("EditFormat"), EditFormat)
- assert isinstance(ParseFunction.get("Identity"), Identity)
- assert isinstance(ParseFunction.get("JsonParser"), JsonParser)
- with pytest.raises(ValueError):
- ParseFunction.get("InvalidParser")
-
-
def test_action_parser():
parser = ActionParser()
command = Command(code="ls", name="ls")