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]

Feat: TagToolCallObservations HistoryProcessor

Kilian Lieret3e4dc26a1dad
diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.py
index 57f60008..7f4eff99 100644
--- a/sweagent/agent/history_processors.py
+++ b/sweagent/agent/history_processors.py
@@ -34,13 +34,13 @@ class LastNObservations(BaseModel):
n: int
"""Number of observations to keep."""
- always_remove_output_for_tags: list[str] = []
- """Any observation with a `tag` field containing one of these strings will be elided,
+ always_remove_output_for_tags: set[str] = {"remove_output"}
+ """Any observation with a `tags` field containing one of these strings will be elided,
even if it is one of the last n observations.
"""
- always_keep_output_for_tags: list[str] = []
- """Any observation with a `tag` field containing one of these strings will be kept,
+ always_keep_output_for_tags: set[str] = {"keep_output"}
+ """Any observation with a `tags` field containing one of these strings will be kept,
even if it is not one of the last n observations.
"""
@@ -62,8 +62,9 @@ class LastNObservations(BaseModel):
]
omit_content_idxs = [idx for idx in observation_idxs[1 : -self.n]]
for idx, entry in enumerate(history):
- if ((idx not in omit_content_idxs) or (entry.get("tag") in self.always_keep_output_for_tags)) and (
- entry.get("tag") not in self.always_remove_output_for_tags
+ tags = set(entry.get("tags", []))
+ if ((idx not in omit_content_idxs) or (tags & self.always_keep_output_for_tags)) and not (
+ tags & self.always_remove_output_for_tags
):
new_history.append(entry)
else:
@@ -76,7 +77,48 @@ class LastNObservations(BaseModel):
return new_history
+class TagToolCallObservations(BaseModel):
+ """Adds tags to history items for specific tool calls."""
+
+ type: Literal["tag_tool_call_observations"] = "tag_tool_call_observations"
+ """Do not change. Used for (de)serialization."""
+
+ tags: set[str] = {"keep_output"}
+ """Add the following tag to all observations matching the search criteria."""
+
+ function_names: set[str] = set()
+ """Only consider observations made by tools with these names."""
+
+ # pydantic config
+ model_config = ConfigDict(extra="forbid")
+
+ def _add_tags(self, entry: dict) -> None:
+ tags = set(entry.get("tags", []))
+ tags.add(self.tags)
+ entry["tags"] = list(tags)
+
+ def _should_add_tags(self, entry: dict) -> bool:
+ if entry["message_type"] != "action":
+ return False
+ function_calls = entry.get("function_calls", [])
+ if not function_calls:
+ return False
+ function_names = {call["function"]["name"] for call in function_calls}
+ return bool(self.function_names & function_names)
+
+ def __call__(self, history) -> None:
+ for entry in history:
+ if self._should_add_tags(entry):
+ self._add_tags(entry)
+ return history
+
+
class ClosedWindowHistoryProcessor(BaseModel):
+ """For each value in history, keep track of which windows have been shown.
+ We want to mark windows that should stay open (they're the last window for a particular file)
+ Then we'll replace all other windows with a simple summary of the window (i.e. number of lines)
+ """
+
type: Literal["closed_window"] = "closed_window"
"""Do not change. Used for (de)serialization."""
@@ -88,9 +130,6 @@ class ClosedWindowHistoryProcessor(BaseModel):
def __call__(self, history):
new_history = list()
- # For each value in history, keep track of which windows have been shown.
- # We want to mark windows that should stay open (they're the last window for a particular file)
- # Then we'll replace all other windows with a simple summary of the window (i.e. number of lines)
windows = set()
for entry in reversed(history):
data = entry.copy()
@@ -121,5 +160,6 @@ class ClosedWindowHistoryProcessor(BaseModel):
HistoryProcessor = Annotated[
- DefaultHistoryProcessor | LastNObservations | ClosedWindowHistoryProcessor, Field(discriminator="type")
+ DefaultHistoryProcessor | LastNObservations | ClosedWindowHistoryProcessor | TagToolCallObservations,
+ Field(discriminator="type"),
]
diff --git a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj
index f004f650..70990c20 100644
--- a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj
+++ b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj
@@ -61,12 +61,14 @@
{
"role": "system",
"content": "SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.\n\nThe special interface consists of a file editor that shows you 100 lines of a file at a time.\nIn addition to typical bash commands, you can also use the following commands to help you navigate and edit files.\n\nPlease note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.\nIf you'd like to add the line ' print(x)' you must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run.\n\nRESPONSE FORMAT:\nYour shell prompt is formatted as follows:\n(Open file: <path>) <cwd> $\n\nFirst, you should _always_ include a general thought about what you're going to do next.\nThen, for every response, you must include exactly _ONE_ command to execute.\nAll of the tools you need to use are listed for your reference.\n\nRemember, you should only include a _SINGLE_ command in the command section and then wait for a response from the shell before continuing with more discussion and commands. Everything you include in the DISCUSSION section will be saved for future reference.\nIf you'd like to issue two commands at once, PLEASE DO NOT DO THAT! Please instead first submit just the first command, and then after receiving a response you'll be able to issue the second command.\nYou're free to use any other bash commands you want (e.g. find, grep, cat, ls, cd) in addition to the special commands listed above.\nHowever, the environment does NOT support interactive session commands (e.g. python, vim), so please do not invoke them.",
- "agent": "main"
+ "agent": "main",
+ "message_type": "system_prompt"
},
{
"role": "user",
"content": "We're currently solving the following issue within our repository. Here's the issue text:\nISSUE:\nSyntaxError: invalid syntax\nI'm running `missing_colon.py` as follows:\r\n\r\n```python\r\ndivision(23, 0)\r\n```\r\n\r\nbut I get the following error:\r\n\r\n```\r\n File \"/Users/fuchur/Documents/24/git_sync/swe-agent-test-repo/tests/./missing_colon.py\", line 4\r\n def division(a: float, b: float) -> float\r\n ^\r\nSyntaxError: invalid syntax\r\n```\n\n\nINSTRUCTIONS:\nNow, you're going to solve this issue on your own. Your terminal session has started and you're in the repository's root directory. You can use any bash commands or the special interface to help you. Edit all the files you need to and run any checks or tests that you want.\nRemember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.\nWhen you're satisfied with all of the changes you've made, you can submit your changes to the code base by simply running the submit command.\nNote however that you cannot use any interactive session commands (e.g. python, vim) in this environment, but you can write scripts and run them. E.g. you can write a python script and then run it with `python <script_name>.py`.\n\nNOTE ABOUT THE EDIT COMMAND: Indentation really matters! When editing a file, make sure to insert appropriate indentation before each line!\n\nIMPORTANT TIPS:\n1. Always start by trying to replicate the bug that the issues discusses.\n If the issue includes code for reproducing the bug, we recommend that you re-implement that in your environment, and run it to make sure you can reproduce the bug.\n Then start trying to fix it.\n When you think you've fixed the bug, re-run the bug reproduction script to make sure that the bug has indeed been fixed.\n\n If the bug reproduction script does not print anything when it successfully runs, we recommend adding a print(\"Script completed successfully, no errors.\") command at the end of the file,\n so that you can be sure that the script indeed ran fine all the way through.\n\n2. If you run a command and it doesn't work, try running a different command. A command that did not work once will not work the second time unless you modify it!\n\n3. If you open a file and need to get to an area around a specific line that is not in the first 100 lines, say line 583, don't just use the scroll_down command multiple times. Instead, use the goto 583 command. It's much quicker.\n\n4. If the bug reproduction script requires inputting/reading a specific file, such as buggy-input.png, and you'd like to understand how to input that file, conduct a search in the existing repo code, to see whether someone else has already done that. Do this by running the command: find_file \"buggy-input.png\" If that doesn't work, use the linux 'find' command.\n\n5. Always make sure to look at the currently open file and the current working directory (which appears right after the currently open file). The currently open file might be in a different directory than the working directory! Note that some commands, such as 'create', open files, so they might change the current open file.\n\n6. When editing files, it is easy to accidentally specify a wrong line number or to write code with incorrect indentation. Always check the code after you issue an edit to make sure that it reflects what you wanted to accomplish. If it didn't, issue another command to fix it.\n\n\n(Open file: n/a)\n(Current directory: /SWE-agent__test-repo)\nbash-$",
- "agent": "main"
+ "agent": "main",
+ "message_type": "observation"
},
{
"role": "assistant",
@@ -83,7 +85,8 @@
"id": "call_fJuazlMUN5fQDQ73G6XSpYpx",
"type": "function"
}
- ]
+ ],
+ "message_type": "action"
},
{
"role": "tool",
@@ -91,7 +94,8 @@
"agent": "main",
"tool_call_ids": [
"call_fJuazlMUN5fQDQ73G6XSpYpx"
- ]
+ ],
+ "message_type": "observation"
},
{
"role": "assistant",
@@ -108,7 +112,8 @@
"id": "call_OhmPHGZp0XJ6JRnNkQaYcBMs",
"type": "function"
}
- ]
+ ],
+ "message_type": "action"
},
{
"role": "tool",
@@ -116,7 +121,8 @@
"agent": "main",
"tool_call_ids": [
"call_OhmPHGZp0XJ6JRnNkQaYcBMs"
- ]
+ ],
+ "message_type": "observation"
},
{
"role": "assistant",
@@ -133,7 +139,8 @@
"id": "call_DVnbJcFrvwPsrPt3KfIMf7OH",
"type": "function"
}
- ]
+ ],
+ "message_type": "action"
},
{
"role": "tool",
@@ -141,7 +148,8 @@
"agent": "main",
"tool_call_ids": [
"call_DVnbJcFrvwPsrPt3KfIMf7OH"
- ]
+ ],
+ "message_type": "observation"
},
{
"role": "assistant",
@@ -158,7 +166,8 @@
"id": "call_dcF76aXH6e1pzqRwGxOwpuxb",
"type": "function"
}
- ]
+ ],
+ "message_type": "action"
},
{
"role": "tool",
@@ -166,7 +175,8 @@
"agent": "main",
"tool_call_ids": [
"call_dcF76aXH6e1pzqRwGxOwpuxb"
- ]
+ ],
+ "message_type": "observation"
}
],
"info": {
diff --git a/tests/test_history_processors.py b/tests/test_history_processors.py
new file mode 100644
index 00000000..d81c7d52
--- /dev/null
+++ b/tests/test_history_processors.py
@@ -0,0 +1,21 @@
+import json
+from pathlib import Path
+
+from sweagent.agent.history_processors import LastNObservations
+
+
+def test_last_n_observations(test_trajectories_path: Path):
+ history = json.loads(
+ (
+ test_trajectories_path
+ / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj"
+ ).read_text()
+ )["history"]
+ processor = LastNObservations(n=3)
+ new_history = processor(history)
+ total_observations = len([entry for entry in history if entry["message_type"] == "observation"])
+ # extra -1 because instance template is kept
+ assert (
+ len([entry for entry in new_history if "Old environment output" in entry["content"]])
+ == total_observations - 3 - 1
+ )