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]

Separate Agent.from_config method from __init__

Kilian Lieret5c33020e7145
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index e3fbecea..0c808d88 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -5,7 +5,7 @@ import json
import time
from collections import defaultdict
from pathlib import Path
-from typing import Any
+from typing import Any, Self
from pydantic import BaseModel, ConfigDict, Field
from simple_parsing.helpers.fields import field
@@ -15,6 +15,7 @@ from sweagent import __version__, get_agent_commit_hash
from sweagent.agent.history_processors import DefaultHistoryProcessor, HistoryProcessor
from sweagent.agent.hooks.abstract import AbstractAgentHook, CombinedAgentHook
from sweagent.agent.models import (
+ AbstractModel,
APIStats,
ContextWindowExceededError,
CostLimitExceededError,
@@ -63,6 +64,7 @@ class TemplateConfig(BaseModel):
class AgentConfig(BaseModel):
+ name: str = "main"
templates: TemplateConfig = Field(default_factory=TemplateConfig)
tools: ToolConfig = Field(default_factory=ToolConfig)
history_processor: HistoryProcessor = Field(default_factory=DefaultHistoryProcessor)
@@ -79,30 +81,29 @@ class Agent:
def __init__(
self,
- name: str,
- args: AgentConfig,
- _catch_errors: bool = False,
+ *,
+ templates: TemplateConfig,
+ tools: ToolHandler,
+ history_processor: HistoryProcessor,
+ model: AbstractModel,
+ name: str = "main",
+ _catch_errors: bool = True,
_always_require_zero_exit_code: bool = False,
):
self._catch_errors = _catch_errors
self._always_require_zero_exit_code = _always_require_zero_exit_code
self.name = name
- # todo: currently only used to get the model name, so might remove this later
- self._args = args
- self.model = get_model(args.model, args.tools.commands)
- self.config = args
-
- self.system_args = {
- "command_docs": self.config.tools.command_docs,
- **self.config.tools.env_variables,
- }
+ self.model = model
+ self.templates = templates
+ self.tools = tools
+ self.history_processor = history_processor
+
self.logger = get_logger("agent", emoji="🤠")
# Set in run method
self._env: SWEEnv | None = None
self._problem_statement: ProblemStatement | ProblemStatementConfig | None = None
self.traj_path: Path | None = None
- self._tool_handler: ToolHandler | None = None
#: Number of attempts to solve the issue when using a review loop
self._i_attempt: int = 0
@@ -117,10 +118,18 @@ class Agent:
#: solution attempt to the next
self._forwarded_vars: dict[str, Any] = {}
- self._history_processor = self._args.history_processor
-
self._chook = CombinedAgentHook()
+ @classmethod
+ def from_config(cls, config: AgentConfig) -> Self:
+ model = get_model(config.model, config.tools.commands)
+ return cls(
+ templates=config.templates,
+ tools=ToolHandler.from_config(config.tools),
+ history_processor=config.history_processor,
+ model=model,
+ )
+
def add_hook(self, hook: AbstractAgentHook) -> None:
"""Add hook to agent"""
hook.on_init(agent=self)
@@ -164,7 +173,7 @@ class Agent:
@property
def local_history(self) -> list[dict[str, str]]:
"""Return the history of the agent since the last reset."""
- return self._history_processor([entry for entry in self.history if entry["agent"] == self.name])
+ return self.history_processor([entry for entry in self.history if entry["agent"] == self.name])
# Methods
# -------
@@ -190,15 +199,13 @@ class Agent:
self._forwarded_vars = {}
# if self._rloop is not None:
# self._forwarded_vars = self._rloop.get_forwarded_vars()
- assert self._tool_handler is not None
- self._tool_handler.install()
+ self.tools.install(self._env)
self.setup_attempt(init_model_stats=init_model_stats)
self._chook.on_setup_done()
def setup_attempt(self, *, init_model_stats: APIStats | None = None) -> None:
"""Setup the agent for a new attempt. This includes resetting the model stats."""
- assert self._tool_handler is not None
if self._i_attempt > 0 and init_model_stats is not None:
msg = (
"We might be dealing with nested retries, where subroutines are mixed with retries. "
@@ -215,20 +222,22 @@ class Agent:
def add_system_message_to_history(self) -> None:
"""Add system message to history"""
assert self._problem_statement is not None
- system_msg = self.config.templates.system_template.format(
- **self.system_args, problem_statement=self._problem_statement.get_problem_statement()
+ system_msg = self.templates.system_template.format(
+ command_docs=self.tools.config.command_docs,
+ **self.tools.config.env_variables,
+ problem_statement=self._problem_statement.get_problem_statement(),
)
self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
self._append_history(HistoryItem({"role": "system", "content": system_msg, "agent": self.name}))
def add_demonstrations_to_history(self) -> None:
"""Add demonstrations to history"""
- for demonstration_path in self.config.templates.demonstrations:
+ for demonstration_path in self.templates.demonstrations:
self._add_demonstration_to_history(demonstration_path)
def _add_demonstration_to_history(self, demonstration_path: Path) -> None:
"""Load demonstration from disk and add to history"""
- if self.config.templates.demonstration_template is None and not self.config.templates.put_demos_in_history:
+ if self.templates.demonstration_template is None and not self.templates.put_demos_in_history:
msg = "Cannot use demonstrations without a demonstration template or put_demos_in_history=True"
raise ValueError(msg)
@@ -241,8 +250,8 @@ class Agent:
if ("agent" not in entry) or ("agent" in entry and entry["agent"] == self.name)
]
- if self.config.templates.put_demos_in_history:
- if self.config.templates.demonstration_template is not None:
+ if self.templates.put_demos_in_history:
+ if self.templates.demonstration_template is not None:
self.logger.warning("Demonstration template is ignored for put_demos_in_history=True")
# Add demonstration to history directly as separate messages
for entry in demo_history:
@@ -255,8 +264,8 @@ class Agent:
demo_history,
is_demonstration=True,
)
- assert self.config.templates.demonstration_template is not None
- demonstration = self.config.templates.demonstration_template.format(demonstration=demo_message)
+ assert self.templates.demonstration_template is not None
+ demonstration = self.templates.demonstration_template.format(demonstration=demo_message)
self._append_history(
{
"agent": self.name,
@@ -274,15 +283,15 @@ class Agent:
# Determine observation template based on what prior observation was
if self.history[-1]["role"] == "system" or self.history[-1].get("is_demo", False):
# Show instance template if prev. obs. was initial system message
- templates = [self.config.templates.instance_template]
- if self.config.templates.strategy_template is not None:
- templates.append(self.config.templates.strategy_template)
+ templates = [self.templates.instance_template]
+ if self.templates.strategy_template is not None:
+ templates.append(self.templates.strategy_template)
elif observation is None or observation.strip() == "":
# Show no output template if observation content was empty
- templates = [self.config.templates.next_step_no_output_template]
+ templates = [self.templates.next_step_no_output_template]
else:
# Show standard output template if there is observation content
- templates = [self.config.templates.next_step_template]
+ templates = [self.templates.next_step_template]
# Populate selected template(s) with information (e.g., issue, arguments, state)
messages = []
@@ -290,7 +299,8 @@ class Agent:
for template in templates:
messages.append(
template.format(
- **self.system_args,
+ command_docs=self.tools.config.command_docs,
+ **self.tools.config.env_variables,
**state,
observation=observation or "",
**self._forwarded_vars,
@@ -394,7 +404,7 @@ class Agent:
If the model is able to correct itself, the records of the mistakes will not be part of the history
(but they are saved in the trajectory).
"""
- format_error_template = self.config.tools.format_error_template
+ format_error_template = self.tools.config.format_error_template
self.logger.warning(f"MALFORMED OUTPUT\n{output}")
self.logger.warning(f"FORMAT ERROR\n{format_error_template}")
@@ -413,7 +423,7 @@ class Agent:
(but they are saved in the trajectory).
"""
name = action.strip().split()[0]
- blocklist_error_message = self.config.tools.filter.blocklist_error_template.format(name=name)
+ blocklist_error_message = self.tools.config.filter.blocklist_error_template.format(name=name)
self.logger.warning(f"BLOCKLISTED OUTPUT\n{output}")
self.logger.warning(f"BLOCKLIST ERROR\n{blocklist_error_message}")
@@ -439,20 +449,18 @@ 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.name == "human":
return "", output, output
elif self.model.name == "human_thought":
- thought, action = self._tool_handler.parse_actions(output)
+ thought, action = self.tools.parse_actions(output)
return thought, action, output
format_fails = blocklist_fails = 0
- assert self._tool_handler is not None
while format_fails + blocklist_fails <= 2:
try:
- thought, action = self._tool_handler.parse_actions(
+ thought, action = self.tools.parse_actions(
output,
)
except KeyboardInterrupt:
@@ -461,7 +469,7 @@ class Agent:
format_fails += 1
output = self.retry_after_format_fail(output)
continue
- if self._tool_handler.should_block_action(action):
+ if self.tools.should_block_action(action):
blocklist_fails += 1
output = self.retry_after_blocklist_fail(output, action)
else:
@@ -473,7 +481,7 @@ class Agent:
def handle_special_actions(self, action: str, info: AgentInfo) -> tuple[str, bool, AgentInfo] | None:
"""Handles special actions like `skip`, `exit_cost`, etc."""
assert self._env is not None
- assert self._tool_handler is not None
+ assert self.tools is not None
if action == "skip":
observation = "Skipped"
info["exit_status"] = "skipped"
@@ -498,9 +506,9 @@ class Agent:
and submit this. This means we send the `submit` command to the runtime and parse the output.
"""
assert self._env is not None
- assert self._tool_handler is not None
+ assert self.tools is not None
observation = self._env.communicate(input="submit")
- submission = self._tool_handler.parse_submission_cmd_output(observation)
+ submission = self.tools.parse_submission_cmd_output(observation)
assert submission is not None and submission.strip() != "", AssertionError("No submission found.")
self.logger.info(f"Found submission: {submission}")
info["exit_status"] = f"submitted ({action})"
@@ -516,8 +524,8 @@ class Agent:
Returns:
None if no submission was found, else tuple of observation, done, info
"""
- assert self._tool_handler is not None
- submission = self._tool_handler.parse_submission_cmd_output(observation)
+ assert self.tools is not None
+ submission = self.tools.parse_submission_cmd_output(observation)
if submission is None:
return None
self.logger.info(f"Found submission: {submission}")
@@ -612,14 +620,13 @@ class Agent:
"""
assert self._env is not None
- assert self._tool_handler is not None
# Forward model and get actions
self._chook.on_step_start()
- state = self._tool_handler.get_state()
+ state = self.tools.get_state(env=self._env)
thought, raw_action, output = self.forward_model(observation, state)
self._chook.on_actions_generated(thought=thought, action=raw_action, output=output)
- run_action: str = self._tool_handler.guard_multiline_input(raw_action).strip()
+ run_action: str = self.tools.guard_multiline_input(raw_action).strip()
# Execute action
execution_t0 = time.perf_counter()
@@ -667,7 +674,6 @@ class Agent:
"""
self._problem_statement = problem_statement
self._env = env
- self._tool_handler = ToolHandler.from_config(self.config.tools, env.deployment.runtime)
self.setup(init_model_stats)
# Save/reset some attributes
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 42e926a7..1c5376b2 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -82,7 +82,7 @@ class CostLimitExceededError(Exception):
pass
-class BaseModel:
+class AbstractModel:
MODELS = {}
SHORTCUTS = {}
@@ -194,7 +194,7 @@ class BaseModel:
raise NotImplementedError(msg)
-class OpenAIModel(BaseModel):
+class OpenAIModel(AbstractModel):
MODELS = {
"gpt-3.5-turbo-0125": {
"max_context": 16_385,
@@ -417,7 +417,7 @@ class GroqModel(OpenAIModel):
)
-class AnthropicModel(BaseModel):
+class AnthropicModel(AbstractModel):
MODELS = {
"claude-instant": {
"max_context": 100_000,
@@ -498,7 +498,7 @@ class AnthropicModel(BaseModel):
return anthropic_query(self, history)
-class BedrockModel(BaseModel):
+class BedrockModel(AbstractModel):
MODELS = {
"anthropic.claude-instant-v1": {
"max_context": 100_000,
@@ -691,7 +691,7 @@ def anthropic_query(model: AnthropicModel | BedrockModel, history: list[dict[str
return "\n".join([x.text for x in response.content])
-class OllamaModel(BaseModel):
+class OllamaModel(AbstractModel):
MODELS = defaultdict(
lambda: {
"max_context": 128_000,
@@ -755,7 +755,7 @@ class OllamaModel(BaseModel):
return response["message"]["content"]
-class TogetherModel(BaseModel):
+class TogetherModel(AbstractModel):
# Check https://docs.together.ai/docs/inference-models for model names, context
# Check https://www.together.ai/pricing for pricing
MODELS = {
@@ -855,7 +855,7 @@ def _history_to_messages(history: list[dict[str, str]], is_demonstration: bool =
return [{k: v for k, v in entry.items() if k in ["role", "content"]} for entry in history]
-class HumanModel(BaseModel):
+class HumanModel(AbstractModel):
MODELS = {"human": {}}
def __init__(self, args: ModelConfig, commands: list[Command]):
@@ -927,7 +927,7 @@ class HumanThoughtModel(HumanModel):
return f"{thought_all}\n```\n{action}\n```"
-class ReplayModel(BaseModel):
+class ReplayModel(AbstractModel):
MODELS = {"replay": {}}
def __init__(self, args: ModelConfig, commands: list[Command]):
@@ -1004,7 +1004,7 @@ class PredeterminedTestModel:
pass
-class InstantEmptySubmitTestModel(BaseModel):
+class InstantEmptySubmitTestModel(AbstractModel):
MODELS = {
"instant_empty_submit": {
"max_context": 100_000,
@@ -1034,7 +1034,7 @@ class InstantEmptySubmitTestModel(BaseModel):
return history
-def get_model(args: ModelConfig, commands: list[Command] | None = None):
+def get_model(args: ModelConfig, commands: list[Command] | None = None) -> AbstractModel:
"""
Returns correct model object given arguments and commands
"""
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 8adb6eec..d8048456 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -190,7 +190,7 @@ class SWEEnv:
if check and r.exit_code != 0:
self.logger.error(f"{error_msg}: {output}")
self.close()
- msg = f"{error_msg} (command: {input})"
+ msg = f"Command {input!r} failed ({r.exit_code=}): {error_msg}"
raise RuntimeError(msg)
# todo: What do we do with this?
if set_last_action:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 60b1088b..b8663ce5 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -75,7 +75,7 @@ class RunBatch:
logger.debug("The first instance is %s", f"{instances[0]!r}")
return cls(
instances=instances,
- agent=Agent("main", config.agent),
+ agent=Agent.from_config(config.agent),
traj_dir=config.traj_dir,
raise_exceptions=config.raise_exceptions,
)
diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.py
index f38ee1ad..012ef93b 100644
--- a/sweagent/run/run_replay.py
+++ b/sweagent/run/run_replay.py
@@ -85,12 +85,10 @@ class RunReplay:
_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))
- return Agent(
- "replay",
- agent_config,
- _catch_errors=self._catch_errors,
- _always_require_zero_exit_code=self._require_zero_exit_code,
- )
+ agent = Agent.from_config(agent_config)
+ agent._catch_errors = self._catch_errors
+ agent._always_require_zero_exit_code = self._require_zero_exit_code
+ return agent
def _get_run_single(self) -> RunSingle:
return RunSingle(
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index ca105004..9d23ff4d 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -85,7 +85,7 @@ class RunSingle:
logger.info(f"Config:\n {config_str}")
self = cls(
env=SWEEnv.from_config(config.env),
- agent=Agent("main", config.agent),
+ agent=Agent.from_config(config.agent),
problem_statement=config.problem_statement,
traj_dir=config.traj_dir,
actions=config.actions,
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index 9941b22f..5847da77 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -5,9 +5,10 @@ from pathlib import Path
from typing import Any, Self
from pydantic import BaseModel, Field
-from swerex.runtime.abstract import AbstractRuntime, BashAction, WriteFileRequest
+from swerex.runtime.abstract import BashAction, WriteFileRequest
from swerex.runtime.abstract import Command as RexCommand
+from sweagent.environment.swe_env import SWEEnv
from sweagent.tools.commands import Command, ParseCommand, ParseCommandBash
from sweagent.tools.parsing import ParseFunction, ThoughtActionParser
from sweagent.tools.utils import _guard_multiline_input
@@ -127,9 +128,8 @@ class ToolConfig(BaseModel):
break
-# todo: Take runtime in methods, not in constructor, so I can pass it to the agent
class ToolHandler:
- def __init__(self, tools: ToolConfig, runtime: AbstractRuntime):
+ def __init__(self, tools: ToolConfig):
"""This class handles most of the tool usage. It has the following responsibilities:
- Install the tools
@@ -138,22 +138,29 @@ class ToolHandler:
- Get the current state of the environment
"""
self.config = tools
- self._runtime = runtime
# partially initialized in `install_commands`.
self._reset_commands = []
self._command_patterns = self._get_command_patterns()
self.logger = get_logger("Tools", emoji="🔧")
@classmethod
- def from_config(cls, config: ToolConfig, runtime: AbstractRuntime) -> Self:
- return cls(config, runtime)
+ def from_config(cls, config: ToolConfig) -> Self:
+ return cls(config)
- def install(self) -> None:
- self._install_commands()
- self._make_state_command_available()
- self.reset()
+ # Installation & Reset
+ # --------------------
- def _install_commands(self) -> None:
+ def install(self, env: SWEEnv) -> None:
+ self._install_commands(env)
+ self._make_state_command_available(env)
+ self.reset(env)
+
+ def reset(self, env: SWEEnv) -> None:
+ self.logger.info("Resetting tools")
+ self._set_env_variables(env)
+ env.communicate(" && ".join(self._reset_commands), check=True)
+
+ def _install_commands(self, env: SWEEnv) -> None:
"""Make sure all commands are available in the container"""
for file in self.config.command_files:
contents = file.read_text()
@@ -176,48 +183,44 @@ class ToolHandler:
name = file.name.rpartition(".")[0]
mark_executable = True
+ # todo: Do this with the environment?
self.logger.debug(f"Installing command {name} ({source=}, {mark_executable=})")
- asyncio.run(self._runtime.write_file(WriteFileRequest(content=contents, path=f"/root/commands/{name}")))
+ asyncio.run(
+ env.deployment.runtime.write_file(WriteFileRequest(content=contents, path=f"/root/commands/{name}"))
+ )
if source:
self._reset_commands.append(f"source /root/commands/{name}")
if mark_executable:
asyncio.run(
- self._runtime.execute(RexCommand(command=f"chmod +x /root/commands/{name}", shell=True, check=True))
+ env.deployment.runtime.execute(
+ RexCommand(command=f"chmod +x /root/commands/{name}", shell=True, check=True)
+ )
)
for command in self.config.install_commands:
- asyncio.run(self._runtime.run_in_session(BashAction(command=command, timeout=1, check=True)))
+ asyncio.run(env.deployment.runtime.run_in_session(BashAction(command=command, timeout=1, check=True)))
- def _make_state_command_available(self) -> None:
+ def _make_state_command_available(self, env: SWEEnv) -> None:
asyncio.run(
- self._runtime.run_in_session(BashAction(command=self.config.state_command.code, timeout=1, check=True))
+ env.deployment.runtime.run_in_session(
+ BashAction(command=self.config.state_command.code, timeout=1, check=True)
+ )
)
- def _set_env_variables(self) -> None:
+ def _set_env_variables(self, env: SWEEnv) -> None:
_env_setters = [f"export {k}={v}" for k, v in self.config.env_variables.items()]
command = " && ".join(_env_setters)
- asyncio.run(
- self._runtime.run_in_session(
- BashAction(command=command, timeout=1, check=True, error_msg="Failed to set environment variables")
- )
- )
+ env.communicate(command, check=True)
- def reset(self) -> None:
- self.logger.info("Resetting tools")
- self._set_env_variables()
- asyncio.run(
- self._runtime.run_in_session(BashAction(command=" && ".join(self._reset_commands), timeout=1, check=True))
- )
+ # Getting state
+ # -------------
- def get_state(self) -> dict[str, str]:
+ def get_state(self, env: SWEEnv) -> dict[str, str]:
"""If a state command is defined, execute it in the environment parse it as json and return the result.
This can be used to extract environment variables etc. from the environment.
"""
if not self.config.state_command:
return {}
- state = asyncio.run(
- self._runtime.run_in_session(BashAction(command=self.config.state_command.name, check=True))
- )
- output = state.output.strip()
+ output = env.communicate(self.config.state_command.name, check=True).strip()
if not output:
return {}
try:
@@ -228,6 +231,9 @@ class ToolHandler:
self.logger.debug(f"Retrieved state from environment: {state}")
return state
+ # Blocking
+ # --------
+
def should_block_action(self, action: str) -> bool:
"""Check if the command should be blocked."""
names = action.strip().split()
@@ -244,6 +250,36 @@ class ToolHandler:
return True
return False
+ # Parsing & multiline commands
+ # -----------------------------
+
+ def parse_submission_cmd_output(self, output: str) -> str | None:
+ """Function for extracting diff patch submission at the end of an episode.
+
+ Args:
+ output: `submit` observation
+
+ Returns:
+ submission: diff patch submission
+ """
+ pattern = r"\<\<SUBMISSION\|\|(.*)\|\|SUBMISSION\>\>"
+ match = re.search(pattern, output, re.DOTALL)
+ 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)
+
+ def guard_multiline_input(self, action: str) -> str:
+ """Split action by multiline commands, then append the first line in each multiline command with "<< '{end_name}'".
+ Multiline commands (which are specified by an end_name) are commands that span multiple lines and are terminated by a specific end_name.
+
+ Their multi-line argument is sent using a heredoc, which is a way to send a multi-line string to a command in bash.
+ """
+ return _guard_multiline_input(action, self._get_first_multiline_cmd)
+
def _get_first_multiline_cmd(self, action: str) -> re.Match | None:
"""Return the first match of a command pattern in the action string.
Where first match is defined by the start of the match.
@@ -265,14 +301,6 @@ class ToolHandler:
matches = sorted(matches, key=lambda x: x.start())
return matches[0]
- def guard_multiline_input(self, action: str) -> str:
- """Split action by multiline commands, then append the first line in each multiline command with "<< '{end_name}'".
- Multiline commands (which are specified by an end_name) are commands that span multiple lines and are terminated by a specific end_name.
-
- Their multi-line argument is sent using a heredoc, which is a way to send a multi-line string to a command in bash.
- """
- return _guard_multiline_input(action, self._get_first_multiline_cmd)
-
def _get_command_patterns(self) -> dict[str, re.Pattern]:
"""Creates regular expressions for the commands"""
@@ -293,22 +321,3 @@ class ToolHandler:
)
_command_patterns[self.config.submit_command] = submit_pat
return _command_patterns
-
- def parse_submission_cmd_output(self, output: str) -> str | None:
- """Function for extracting diff patch submission at the end of an episode.
-
- Args:
- output: `submit` observation
-
- Returns:
- submission: diff patch submission
- """
- pattern = r"\<\<SUBMISSION\|\|(.*)\|\|SUBMISSION\>\>"
- match = re.search(pattern, output, re.DOTALL)
- 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_agent.py b/tests/test_agent.py
index 6a9e3472..0a79dc93 100644
--- a/tests/test_agent.py
+++ b/tests/test_agent.py
@@ -19,59 +19,65 @@ def agent_config():
@pytest.fixture
def test_agent(agent_config: AgentConfig) -> Agent:
- return Agent("test", agent_config, _catch_errors=True)
+ return Agent.from_config(agent_config)
-def test_exit_cost_manually_raised(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_cost_manually_raised(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["```\nexit_cost\n```"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_cost" # type: ignore
-def test_exit_cost(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_cost(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["raise_cost"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_cost" # type: ignore
-def test_exit_context(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_context(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["raise_context"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_context" # type: ignore
-def test_exit_model_error(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_model_error(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["raise_runtime"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_error" # type: ignore
-def test_exit_format(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_format(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["a", "b", "c", "d"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_format" # type: ignore
-def test_exit_blocklist(dummy_env: SWEEnv, test_agent: Agent):
+def test_exit_blocklist(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["```\nvim\n```", "```\npython\n```", "```\nsu\n```", "```\nnano\n```"]) # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_format" # type: ignore
@@ -83,12 +89,13 @@ class RuntimeRaisesFirst(DummyRuntime):
return await super().run_in_session(action)
-def test_early_exit(dummy_env: SWEEnv, test_agent: Agent):
+def test_early_exit(dummy_env: SWEEnv, test_agent: Agent, tmp_path):
test_agent.model = PredeterminedTestModel(["```\nraise\n```"]) # type: ignore
test_agent._catch_errors = True
dummy_env.deployment.runtime = RuntimeRaisesFirst() # type: ignore
r = test_agent.run(
problem_statement=EmptyProblemStatement(),
env=dummy_env,
+ traj_dir=tmp_path,
)
assert r.info["exit_status"] == "exit_environment_error" # type: ignore