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 trajectory to PR

Kilian Lieretd808b00fd04f
diff --git a/run.py b/run.py
index 7ddf876e..30a614ff 100644
--- a/run.py
+++ b/run.py
@@ -123,16 +123,16 @@ def main(args: ScriptArguments):
"test_files": test_files,
"tests": tests
}
- info = agent.run(
+ info, trajectory = agent.run(
setup_args=setup_args,
env=env,
observation=observation,
traj_dir=traj_dir,
- return_type="info",
+ return_type="info_trajectory",
)
save_predictions(traj_dir, instance_id, info)
if args.actions.open_pr and should_open_pr(args, info, token=env.token):
- env.open_pr(args.actions)
+ env.open_pr(args.actions, info, trajectory)
except KeyboardInterrupt:
logger.info("Exiting InterCode environment...")
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 593b6e71..de099f9e 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -675,7 +675,9 @@ class Agent:
info['model_stats'] = self.model.stats.to_dict()
if traj_dir:
self.save_trajectory(trajectory, traj_dir, env, info)
+ if return_type == "info":
+ return info
+ if return_type == "info_trajectory":
+ return info, trajectory
if return_type != "info":
return trajectory[-1][return_type]
- else:
- return info
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 47e88d17..acffde4f 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -18,6 +18,7 @@ from rich.logging import RichHandler
from simple_parsing.helpers import FrozenSerializable
from sweagent.environment.utils import (
copy_file_to_container,
+ format_trajectory_markdown,
get_container,
get_gh_issue_data,
get_instances,
@@ -674,7 +675,7 @@ class SWEEnv(gym.Env):
raise RuntimeError("Failed to interrupt container")
- def open_pr(self, action_config: "ActionsArguments"):
+ def open_pr(self, action_config: "ActionsArguments", info, trajectory):
"""Create PR to repository"""
logger.info("Opening PR")
# todo: have better way of handling this
@@ -732,6 +733,7 @@ class SWEEnv(gym.Env):
f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "
f"to close [#{issue.number}]({issue_url}) ({issue.title}).\n\nCloses #{issue.number}."
)
+ body += "\n\n" + format_trajectory_markdown(trajectory)
api = GhApi(token=self.token)
pr_info = api.pulls.create(
owner=owner,
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index ff5ad42b..9085cc41 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -1,5 +1,3 @@
-from ast import Dict, parse
-from dataclasses import dataclass
import docker
import json
import logging
@@ -18,7 +16,7 @@ from ghapi.all import GhApi
from io import BytesIO
from pathlib import Path
from subprocess import PIPE, STDOUT
-from typing import Any, Tuple
+from typing import Any, List, Tuple, Dict
LOGGER_NAME = "intercode"
START_UP_DELAY = 5
@@ -382,4 +380,46 @@ def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token:
message = commit.commit.message
if f"fixes #{issue_number}" in message.lower() or f"closes #{issue_number}" in message.lower():
commit_urls.append(commit.html_url)
- return commit_urls
\ No newline at end of file
+ return commit_urls
+
+
+def remove_triple_backticks(text: str) -> str:
+ return "\n".join(line.removeprefix("```") for line in text.splitlines())
+
+
+def format_trajectory_markdown(trajectory: List[Dict[str, str]]):
+ """Format a trajectory as a markdown string for use in gh PR description."""
+ emojis = {
+ "action": "πŸ”₯",
+ "observation": "πŸ‘€",
+ "response": "οΈπŸ§‘β€πŸš’",
+ "state": "🧠",
+ "thought": "πŸ’‘",
+
+ }
+ prefix = [
+ "<details>",
+ "<summary>Thought process ('trajectory') of SWE-agent (click to expand)</summary>",
+ "",
+ "",
+ ]
+ steps = []
+ for i, step in enumerate(trajectory):
+ step_strs = []
+ for key, value in step.items():
+ emoji = emojis.get(key, "")
+ if emoji:
+ emoji += " "
+ step_strs.append(f"**{emoji}{key.capitalize()} ({i})**:")
+ if key in ["observation", "state", "action"]:
+ step_strs.append("```")
+ step_strs.append(remove_triple_backticks(value).strip())
+ step_strs.append("```")
+ else:
+ step_strs.append(value.strip())
+ steps.append("\n".join(step_strs))
+ suffix = [
+ "",
+ "</details>",
+ ]
+ return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
\ No newline at end of file