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]

Add patch context extender to repository

Kilian Lieret5ad794a3d3b8
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index 1109d369..028bb6e1 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -227,17 +227,13 @@ class BinaryReviewer(AbstractBinaryReviewer):
traj_item_template=config.traj_item_template,
)
- @staticmethod
- def _add_dict_suffix(d: dict[str, Any], suffix: str) -> dict[str, Any]:
- return {f"{k}{suffix}": v for k, v in d.items()}
-
def format_messages(self, instance: INSTANCE_TYPE, sub1: ReviewSubmission, sub2: ReviewSubmission):
system_message = self._config.system_template
logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (system)\n{system_message}")
user_message = self._config.instance_template.format(
**instance,
- **self._add_dict_suffix(sub1.to_format_dict(), "1"),
- **self._add_dict_suffix(sub2.to_format_dict(), "2"),
+ **sub1.to_format_dict(suffix="1"),
+ **sub2.to_format_dict(suffix="2"),
traj1=self._traj_formatter.format_trajectory(sub1.trajectory, i_traj=1),
traj2=self._traj_formatter.format_trajectory(sub2.trajectory, i_traj=2),
)
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 845297c0..9d15bafe 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -10,7 +10,7 @@ import subprocess
import time
import traceback
from dataclasses import dataclass
-from pathlib import Path
+from pathlib import Path, PurePath
from typing import Any
import gymnasium as gym
@@ -28,6 +28,7 @@ from sweagent.environment.utils import (
PROCESS_DONE_MARKER_END,
PROCESS_DONE_MARKER_START,
InvalidGithubURL,
+ PatchFormatter,
copy_anything_to_container,
copy_file_to_container,
format_trajectory_markdown,
@@ -420,6 +421,14 @@ class SWEEnv(gym.Env):
)
os.remove(path_to_patch)
+ def _get_edited_files_with_context(self, patch: str) -> dict[str, str]:
+ """Get the edited files with context from the patch"""
+ pf = PatchFormatter(patch, read_method=self.read_file)
+ out = {}
+ for context_length in [30, 50, 70]:
+ out[f"edited_files{context_length}"] = pf.get_files_str(original=False, context_length=context_length)
+ return out
+
def step(self, action: str) -> tuple[str | None, int, bool, AgentInfo]:
"""
Runs given action in environment and returns corresponding output
@@ -449,6 +458,8 @@ class SWEEnv(gym.Env):
self.logger.info(f"Found submission: {submission}")
info["exit_status"] = f"submitted ({action})"
info["submission"] = submission
+ for k, v in self._get_edited_files_with_context(patch=submission).items():
+ info[k] = v
observation = "Exited (autosubmitted)"
self.logger.info("Exiting with autosubmission")
return observation, 0, True, info
@@ -495,6 +506,8 @@ class SWEEnv(gym.Env):
self.logger.info(f"Found submission: {submission}")
info["exit_status"] = "submitted"
info["submission"] = submission if submission.strip() != "" else None
+ for k, v in self._get_edited_files_with_context(patch=submission).items():
+ info[k] = v
observation = submission if submission.strip() != "" else None
return observation, 0, True, info
return observation, 0, False, info
@@ -1156,3 +1169,15 @@ class SWEEnv(gym.Env):
"any required changes onto the branch and then click "
"'Ready for Review' to bring it to the attention of the maintainers.",
)
+
+ def read_file(self, path: str | PurePath) -> str:
+ """Read file contents from container
+
+ Args:
+ path: Path to file relative to repository root
+
+ Returns:
+ file_contents: Contents of file as string
+ """
+ path_in_container = f"/{self._repo_name}/{path}"
+ return self.communicate(f"cat {str(path_in_container)}")
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 07357f67..29a476b0 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -19,9 +19,11 @@ from typing import Any, Callable
from datasets import load_dataset, load_from_disk
from ghapi.all import GhApi
from git import InvalidGitRepositoryError, Repo
+from unidiff import PatchSet
import docker
from docker.models.containers import Container
+from sweagent.types import Trajectory
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
@@ -763,7 +765,7 @@ _MARKDOWN_TRAJECTORY_EMOJI_MAPPING = {
}
-def format_trajectory_markdown(trajectory: list[dict[str, str]]):
+def format_trajectory_markdown(trajectory: Trajectory):
"""Format a trajectory as a markdown string for use in gh PR description."""
prefix = [
"<details>",
@@ -791,3 +793,145 @@ def format_trajectory_markdown(trajectory: list[dict[str, str]]):
"</details>",
]
return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
+
+
+class PatchFormatter:
+ def __init__(
+ self,
+ patch: str,
+ read_method: Callable[[str], str],
+ ):
+ """Given the final patch and access to the container that contains the repository,
+ extract relevant lines from the modified file.
+
+ Args:
+ patch: The patch as a string.
+ read_method: Callable with path to file (relative to repository root) as argument
+ that returns the file content as a string.
+ """
+ self._patch = PatchSet(patch)
+ self._patched_files: dict[str, str] = {}
+ self._original_files: dict[str, str] = {}
+ self._patch_applied = True
+ self._read_file = read_method
+ self._read_files(original=False)
+
+ @staticmethod
+ def _merge_intervals(starts: list[int], stops: list[int]) -> tuple[list[int], list[int]]:
+ """Given two lists of integers, starts and stops, merges all overlapping intervals.
+
+ For example `starts=[1, 5, 18]`, `stops=[10, 13, 20]`
+ should return `starts=[1, 18]`, `stops=[13, 20]`
+ """
+
+ intervals = sorted(zip(starts, stops))
+ merged = []
+ for start, stop in intervals:
+ if not merged or merged[-1][1] < start:
+ # No overlap
+ merged.append([start, stop])
+ else:
+ # Overlap
+ merged[-1][1] = max(merged[-1][1], stop)
+ # Unzip again
+ merged_starts, merged_stops = zip(*merged)
+ return list(merged_starts), list(merged_stops)
+
+ def format_file(self, text: str, starts: list[int], stops: list[int], *, linenos: bool = True) -> str:
+ """Reads file and returns string representation of the relevant lines.
+
+ Args:
+ path: The path to the file within the repo location
+ starts: The starting line numbers of the relevant lines. The first line is line 1.
+ stops: The stopping line numbers of the relevant lines. The stop is not inclusive.
+ The first line is line 1.
+ linenos: Whether to include line numbers
+ """
+ assert len(starts) == len(stops)
+ assert all(start >= 1 for start in starts)
+ assert all(start < stop for start, stop in zip(starts, stops))
+ starts, stops = self._merge_intervals(starts, stops)
+ assert all(hunk1_start < hunk2_start for hunk1_start, hunk2_start in zip(starts, starts[1:]))
+ out: list[str] = []
+ if starts[0] > 1:
+ # Count from 1
+ out.append(f"[{starts[0]-1} lines above omitted]")
+ last_stop: int | None = None
+ lines = text.splitlines()
+ for start, stop in zip(starts, stops):
+ assert start >= 1
+ if last_stop is not None:
+ n_omitted = start - last_stop
+ # Check that we have non-overlapping hunks
+ assert n_omitted >= 0
+ if n_omitted:
+ out.append(f"\n[{n_omitted} lines omitted]\n")
+ # Count from 1
+ these_lines = lines[start - 1 : stop - 1]
+ if linenos:
+ out.append("\n".join([f"{i:6d}: {l}" for i, l in enumerate(these_lines, start=start)]))
+ else:
+ out.append("\n".join(these_lines))
+ last_stop = stop
+ if last_stop < len(lines):
+ # Stop is not inclusive
+ omitted = len(lines) - last_stop
+ assert omitted > 0
+ out.append(f"[{omitted} lines below omitted]")
+ return "\n".join(out)
+
+ def _get_hunk_lines(self, original: bool, *, context_length: int) -> dict[str, tuple[list[int], list[int]]]:
+ """Get the starts and stops for all files in the patch.
+
+ Args:
+ original: Whether to read the original file or the patched file
+ context_length: The number of lines to include above and below the hunk
+
+ Returns:
+ A dictionary with the file path as key and a tuple of lists of starts and stops as value.
+ """
+ out: dict[str, tuple[list[int], list[int]]] = {}
+ for patch in self._patch:
+ if not patch.is_modified_file:
+ continue
+ starts: list[int] = []
+ stops: list[int] = []
+ for hunk in patch:
+ if original:
+ # 1 is the lowest line number
+ start = max(1, hunk.source_start - context_length)
+ stop = hunk.source_start + hunk.source_length + context_length
+ else:
+ start = max(1, hunk.target_start - context_length)
+ stop = hunk.target_start + hunk.target_length + context_length
+ starts.append(start)
+ stops.append(stop)
+ out[patch.path] = (starts, stops)
+ return out
+
+ def _read_files(self, original: bool) -> None:
+ for patch in self._patch:
+ path = patch.path
+ if not patch.is_modified_file:
+ continue
+ if original:
+ msg = "Original file reading not implemented"
+ raise NotImplementedError(msg)
+ else:
+ assert self._patch_applied
+ self._patched_files[path] = self._read_file(path)
+
+ @staticmethod
+ def concat_files_strings(files: dict[str, str]) -> str:
+ """Concatenate multiple `read_files` outputs into a single string."""
+ out = []
+ for path, content in files.items():
+ out.append(f"[File: {path}]\n{content}")
+ return "\n\n".join(out)
+
+ def get_files_str(self, *, original: bool, context_length: int | None = 50, linenos: bool = True) -> str:
+ hunk_lines = self._get_hunk_lines(original=original, context_length=context_length)
+ sources = self._original_files if original else self._patched_files
+ return self.concat_files_strings(
+ {path: self.format_file(text, *hunk_lines[path], linenos=linenos) for path, text in sources.items()}
+ )
diff --git a/sweagent/types.py b/sweagent/types.py
index 61ada5e3..562bafaa 100644
--- a/sweagent/types.py
+++ b/sweagent/types.py
@@ -44,6 +44,9 @@ class AgentInfo(TypedDict, total=False):
submission: str | None
# same as `ReviewerResult`
review: dict[str, Any]
+ edited_files30: str
+ edited_files50: str
+ edited_files70: str
@dataclass
@@ -55,16 +58,15 @@ class ReviewSubmission:
#: Aggregate info dict (including several retries)
info: AgentInfo
- def to_format_dict(self) -> dict[str, Any]:
+ def to_format_dict(self, *, suffix="") -> dict[str, Any]:
"""Return all the data that is used to format the
messages. Trajectory is excluded because it needs special treatment.
"""
- assert "exit_status" in self.info # mypy
- assert "submission" in self.info
- return {
- "exit_status": self.info["exit_status"],
- "submission": self.info["submission"],
- }
+ out = {}
+ for k, v in self.info.items():
+ if isinstance(v, str):
+ out[f"{k}{suffix}"] = v
+ return out
@dataclass(frozen=True)
diff --git a/tests/test_env.py b/tests/test_env.py
index 13121424..ab2bf918 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -73,6 +73,14 @@ def test_execute_setup_script(tmp_path, test_env_args):
env.reset()
+def test_read_file(tmp_path, test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ content = env.read_file(Path("tests/filetoread.txt"))
+ assert content.splitlines()[-1].strip() == "SWEEnv.read_file"
+
+
@pytest.mark.slow()
def test_execute_environment(tmp_path, test_env_args, capsys):
test_env = {