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]

added LM summarizer

Talor Abramovichf1d443596b47
diff --git a/config/default_ctf.yaml b/config/default_ctf.yaml
index 2dd57fe1..5d88496f 100644
--- a/config/default_ctf.yaml
+++ b/config/default_ctf.yaml
@@ -86,8 +86,39 @@ state_command:
fi
};
parse_function: ThoughtActionParser
-summarizer_function: SimpleSummarizer
+summarizer_function: LMSummarizer
summarizer_window_length: 105
+summarizer_system_template: |-
+ SETTING: You are a skilled cybersecurity professional and top CTF player.
+ You are currently playing as part of a team in a CTF competetion.
+
+ Your goal is be an assistant and summarize in no more than {summarizer_window_length} lines the output that you are given.
+ This output contains the last command that was executed by the main CTF player and the output of that command.
+
+ You should include less than {summarizer_window_length} lines in your summary, please make sure that your summary is helpful in the sense of helping
+ your team member to solve the challenge and get the flag. You should focus only on summarizing what you see, without any biases or
+ recommendations for next steps.
+summarizer_instance_template: |-
+ We're currently solving the following CTF challenge. The CTF challenge is a {category_friendly} problem named "{name}", worth {points} points. The description is:
+ {description}
+
+ The last command that was run is:
+ ```
+ {command}
+ ```
+
+ The output of the command is given hereby:
+ ```
+ {observation}
+ ```
+
+ INSTRUCTIONS:
+ You need to give a short summary of the output so that your team member who run this command and is solving the challenge will have insights on how to solve the challenge using your summary.
+ Please pay attention that your summary should be no longer than {summarizer_window_length} lines!
+summarizer_model:
+ model_name: azure:gpt4
+ per_instance_cost_limit: 2
+ total_cost_limit: 2
env_variables:
WINDOW: 100
OVERLAP: 2
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 48a07ad0..c2d97b73 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -62,12 +62,16 @@ class AgentConfig(FrozenSerializable):
util_functions: list[str] = field(default_factory=list)
submit_command: str = "submit"
parse_function: str = "ThoughtActionParser"
- summarizer_function: str = "SimpleSummarizer"
- summarizer_window_length: int = 105
parse_command: str = "ParseCommandBash"
history_processor: str = "DefaultHistoryProcessor"
history_processor_args: dict[str, Any] = field(default_factory=dict)
command_docs: str = None # type: ignore
+ summarizer_function: str | None = "SimpleSummarizer"
+ summarizer_window_length: int | None = 105
+ summarizer_template: str | None = None
+ summarizer_model: ModelArguments | None = None
+ summarizer_system_template: str | None = None
+ summarizer_instance_template: str | None = None
blocklist_error_template: str = "Interactive operation '{name}' is not supported by this environment"
blocklist: tuple[str, ...] = (
"vim",
@@ -169,9 +173,13 @@ class AgentConfig(FrozenSerializable):
"history_processor",
HistoryProcessor.get(self.history_processor, **self.history_processor_args),
)
- if "WINDOW" in self.env_variables:
+ if self.summarizer_function is None:
+ self.summarizer_function = "Identity"
+ if "WINDOW" in self.env_variables and self.summarizer_window_length is not None:
assert self.summarizer_window_length >= int(self.env_variables["WINDOW"]), AssertionError(f"Summarizer window length is set to {self.summarizer_window_length} which is less then the defined window length {self.env_variables['WINDOW']}")
object.__setattr__(self, "summarizer_function", SummarizeFunction.get(self.summarizer_function, self.summarizer_window_length))
+ if isinstance(self.summarizer_model, dict):
+ self.summarizer_model = ModelArguments.from_dict(self.summarizer_model)
@dataclass(frozen=True)
@@ -248,6 +256,7 @@ class Agent:
def __init__(self, name: str, args: AgentArguments):
self.name = name
self.model = get_model(args.model, args.config._commands + args.config.subroutine_types)
+ self.summarizer_model = get_model(args.config.summarizer_model if args.config.summarizer_model is not None else args.model)
self.config = args.config
assert self.config is not None # mypy
self.system_args = {
@@ -802,6 +811,7 @@ class Agent:
self.last_container_id = env.container_obj.id
# Re-initialize primary
self.setup(setup_args, init_model_stats)
+ self.config.summarizer_function.setup(setup_args, self.config)
for hook in self.hooks:
hook.on_run_start()
@@ -825,7 +835,8 @@ class Agent:
for hook in self.hooks:
hook.on_sub_action_started(sub_action=sub_action)
obs, _, done, info = env.step(sub_action["action"])
- obs = self.config.summarizer_function(sub_action["action"], obs, env)
+ obs, additional_cost = self.config.summarizer_function(sub_action["action"], obs, env, self.summarizer_model)
+ self.model.stats += additional_cost
for hook in self.hooks:
hook.on_sub_action_executed(obs=obs, done=done)
observations.append(obs)
diff --git a/sweagent/agent/summarizer.py b/sweagent/agent/summarizer.py
index 4712a364..a3bfec4e 100644
--- a/sweagent/agent/summarizer.py
+++ b/sweagent/agent/summarizer.py
@@ -4,7 +4,9 @@ import shlex
import textwrap
from abc import abstractmethod
from dataclasses import dataclass
+from typing import Any
+from sweagent.agent.models import APIStats, BaseModel
from sweagent.environment.swe_env import SWEEnv
from sweagent.utils.log import get_logger
@@ -17,6 +19,8 @@ class SummarizeFunctionMeta(type):
Registry maps all inherited classes to their names.
"""
+ _warning_message = None
+
_registry = {}
def __new__(cls, name, bases, attrs):
@@ -33,12 +37,18 @@ class SummarizeFunction(metaclass=SummarizeFunctionMeta):
We use get to generate the right summarizer based on the name of the summarizer.
"""
- def __init__(self, window_length: int):
+ def __init__(self, window_length: int | None):
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
+
@abstractmethod
- def __call__(self, input: str, observation, env: SWEEnv) -> str:
+ 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.
@@ -62,6 +72,12 @@ 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",
@@ -73,19 +89,18 @@ class SimpleSummarizer(SummarizeFunction):
"search_dir",
]
- def __call__(self, input: str, observation: str, env: SWEEnv) -> str:
+ def __call__(self, input: str, observation: str, env: SWEEnv, model: type[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
+ return observation, APIStats()
self.logger.debug(f"Summarizing current observation for input {input}")
command_file_name = "/output/" + input.replace(" ", "_").replace("/", "__")
- observation = f"COMMAND OUTPUT EXCEEDED WINDOW, SAVED COMMAND TO A FILE {command_file_name} AND OPENED THE FILE AT LINE 0.\n\n\n{observation}"
env.communicate("mkdir -p /output")
env.communicate(f"printf {shlex.quote(observation)} > {command_file_name}")
- return env.communicate(f"open {command_file_name}")
+ return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + env.communicate(f"open {command_file_name}"), APIStats()
except Exception as e:
self.logger.warning(f"Unhandled exception occured when trying to summarize observation for input {input}: {e}")
- return observation
+ return observation, APIStats()
class Identity(SummarizeFunction):
@@ -93,9 +108,61 @@ 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) -> str:
+ 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
+ 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:
+ """
+
+ block_list_input = [
+ "create",
+ "open",
+ "edit",
+ "scroll_up",
+ "scroll_down",
+ "goto",
+ "search_file",
+ "search_dir",
+ ]
+
+ def __init__(self, window_length: int):
+ super().__init__(window_length)
+ self.history = []
+
+ def setup(self, instance_args: dict[str, Any], config):
+ self.name = "ctf_summarizer"
+ system_msg = config.summarizer_system_template.format(**config.__dict__)
+ 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_instance_template
+ self.instance_args = instance_args
+ self.system_args = config.__dict__
+
+ def __call__(self, input: str, observation: str, env: SWEEnv, model: type[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/" + input.replace(" ", "_").replace("/", "__")
+ env.communicate("mkdir -p /output")
+ env.communicate(f"printf {shlex.quote(observation)} > {command_file_name}")
+ 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 Exception as e:
+ self.logger.warning(f"Unhandled exception occured when trying to summarize observation for input {input}: {e}")
+ return observation, APIStats()
+