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]
Style: Black format api code
Kilian Liereta00facf14857
diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.pyindex 87c7b951..8e331c61 100644--- a/sweagent/api/hooks.py+++ b/sweagent/api/hooks.py@@ -15,7 +15,10 @@ from run import MainHookclass StreamToSocketIO(io.StringIO):- def __init__(self, wu: "WebUpdate", ):+ def __init__(+ self,+ wu: "WebUpdate",+ ):super().__init__()self._wu = wu@@ -28,8 +31,8 @@ class StreamToSocketIO(io.StringIO):class WebUpdate:- """This class talks to socketio. It's pretty much a wrapper around socketio.emit.- """+ """This class talks to socketio. It's pretty much a wrapper around socketio.emit."""+def __init__(self, socketio: SocketIO):self._socketio = socketioself.log_stream = StreamToSocketIO(self)@@ -40,34 +43,51 @@ class WebUpdate:def up_log(self, message: str, level="info"):"""Update the log"""- self._emit('log_message', {'message': message, 'level': level})+ self._emit("log_message", {"message": message, "level": level})def up_agent(- self,- message: str,- *,- format: str = "markdown",- thought_idx: Optional[int] =None,- type_: str = "info",+ self,+ message: str,+ *,+ format: str = "markdown",+ thought_idx: Optional[int] = None,+ type_: str = "info",):"""Update the agent feed"""- self._emit('update', {'feed': 'agent', 'message': message, 'format': format, 'thought_idx': thought_idx, 'type': type_})-+ self._emit(+ "update",+ {+ "feed": "agent",+ "message": message,+ "format": format,+ "thought_idx": thought_idx,+ "type": type_,+ },+ )+def up_env(- self,- message: str,- *,- type_: str,- format: str = "markdown",- thought_idx: Optional[int] =None,+ self,+ message: str,+ *,+ type_: str,+ format: str = "markdown",+ thought_idx: Optional[int] = None,):"""Update the environment feed"""- self._emit('update', {'feed': 'env', 'message': message, 'format': format, 'thought_idx': thought_idx, 'type': type_})-+ self._emit(+ "update",+ {+ "feed": "env",+ "message": message,+ "format": format,+ "thought_idx": thought_idx,+ "type": type_,+ },+ )+def finish_run(self):"""Finish the run. We use that to control which buttons are active."""- self._emit('finish_run', {})-+ self._emit("finish_run", {})class MainUpdateHook(MainHook):@@ -76,8 +96,10 @@ class MainUpdateHook(MainHook):self._wu = wudef on_start(self):- self._wu.up_env(message="Environment container initialized", format="text", type_="info")-+ self._wu.up_env(+ message="Environment container initialized", format="text", type_="info"+ )+def on_end(self):self._wu.up_agent(message="The run has ended", format="text")self._wu.finish_run()@@ -91,6 +113,7 @@ class MainUpdateHook(MainHook):)self._wu.up_agent(msg, type_="success")+class AgentUpdateHook(AgentHook):def __init__(self, wu: WebUpdate):"""This hooks into the Agent class to update the web interface"""@@ -102,14 +125,19 @@ class AgentUpdateHook(AgentHook):self._thought_idx += 1for prefix in ["DISCUSSION\n", "THOUGHT\n", "DISCUSSION", "THOUGHT"]:thought = thought.replace(prefix, "")- self._wu.up_agent(message=thought, format="markdown", thought_idx=self._thought_idx, type_="thought")-+ self._wu.up_agent(+ message=thought,+ format="markdown",+ thought_idx=self._thought_idx,+ type_="thought",+ )+def on_sub_action_started(self, *, sub_action: dict):# msg = f"```bash\n{sub_action['action']}\n```"msg = "$ " + sub_action["action"].strip()self._sub_action = sub_action["action"].strip()self._wu.up_env(message=msg, thought_idx=self._thought_idx, type_="command")-+def on_sub_action_executed(self, *, obs: str, done: bool):type_ = "output"if self._sub_action == "submit":@@ -129,16 +157,14 @@ class EnvUpdateHook(EnvHook):def on_close(self):self._wu.up_env(message="Environment closed", format="text", type_="info")--# def on_query_message_added(- # self,- # *,- # role: str,- # content: str,- # agent: str,- # is_demo: bool = False,- # thought: str = "",+ # self,+ # *,+ # role: str,+ # content: str,+ # agent: str,+ # is_demo: bool = False,+ # thought: str = "",# action: str = ""# ):# if role == "assistant":diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex 9b2e0c73..3e572fca 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -38,12 +38,12 @@ from run import ActionsArguments, ScriptArguments, Mainapp = Flask(__name__)CORS(app)-socketio = SocketIO(app, cors_allowed_origins='*')+socketio = SocketIO(app, cors_allowed_origins="*")# Setting these variables outside of `if __name__ == "__main__"` because when run Flask server with# `flask run` it will skip the if block. Therefore, the app will return an error for missing `secret_key`# Setting it here will allow both `flask run` and `python server.py` to work-app.secret_key = 'super secret key'-app.config['SESSION_TYPE'] = 'memcache'+app.secret_key = "super secret key"+app.config["SESSION_TYPE"] = "memcache"THREADS: Dict[str, "MainThread"] = {}@@ -53,10 +53,10 @@ env_utils.START_UP_DELAY = 1def ensure_session_id_set():"""Ensures a session ID is set for this user"""- session_id = session.get('session_id', None)+ session_id = session.get("session_id", None)if not session_id:session_id = uuid4().hex- session['session_id'] = session_id+ session["session_id"] = session_idreturn session_id@@ -65,7 +65,7 @@ class MainThread(ThreadWithExc):super().__init__()self._wu = wuself._settings = settings-+def run(self) -> None:# fixme: This actually redirects all output from all threads to the socketio, which is not what we wantwith redirect_stdout(self._wu.log_stream):@@ -83,7 +83,7 @@ class MainThread(ThreadWithExc):self._wu.up_log(str(e), level="critical")self._wu.finish_run()raise-+def stop(self):while self.is_alive():self.raise_exc(SystemExit)@@ -92,14 +92,14 @@ class MainThread(ThreadWithExc):self._wu.up_agent("Run stopped by user")[email protected]('/')[email protected]("/")def index():return render_template("index.html")[email protected]('connect')[email protected]("connect")def handle_connect():- print('Client connected')+ print("Client connected")def write_env_yaml(data: Dict[str, Any]) -> str:@@ -109,7 +109,7 @@ def write_env_yaml(data: Dict[str, Any]) -> str:return str(path)[email protected]('/run', methods=['GET', 'OPTIONS'])[email protected]("/run", methods=["GET", "OPTIONS"])def run():session_id = ensure_session_id_set()if request.method == "OPTIONS": # CORS preflight@@ -164,9 +164,10 @@ def run():thread = MainThread(defaults, wu)THREADS[session_id] = threadthread.start()- return 'Commands are being executed', 202+ return "Commands are being executed", 202+[email protected]('/stop')[email protected]("/stop")def stop():session_id = ensure_session_id_set()global THREADS@@ -178,19 +179,21 @@ def stop():thread.stop()else:print(f"Thread {thread} is not alive")- return 'Stopping computation', 202+ return "Stopping computation", 202+def _build_cors_preflight_response():response = make_response()response.headers.add("Access-Control-Allow-Origin", "*")- response.headers.add('Access-Control-Allow-Headers', "*")- response.headers.add('Access-Control-Allow-Methods', "*")+ response.headers.add("Access-Control-Allow-Headers", "*")+ response.headers.add("Access-Control-Allow-Methods", "*")return response+if __name__ == "__main__":# fixme:app.debug = True- # Setting this port to be 8000 due to the fact that on newer verions of macOS,+ # Setting this port to be 8000 due to the fact that on newer verions of macOS,# port 5000 and 7000 are reserved. Hence calls made to these 2 ports will be rejected and returned with 503 code.- # Source https://stackoverflow.com/questions/72795799/how-to-solve-403-error-with-flask-in-python- socketio.run(app, port=8000, debug=True)\ No newline at end of file+ # Source https://stackoverflow.com/questions/72795799/how-to-solve-403-error-with-flask-in-python+ socketio.run(app, port=8000, debug=True)diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pyindex 89e72d97..ec3bd9e4 100644--- a/sweagent/api/utils.py+++ b/sweagent/api/utils.py@@ -5,17 +5,18 @@ import threadingdef _async_raise(tid, exctype):- '''Raises an exception in the threads with id tid+ """Raises an exception in the threads with id tidThis code is modified from the following SO answer:Author: Philippe FPosted: Nov 28, 2008URL: https://stackoverflow.com/a/325528/- '''+ """if not inspect.isclass(exctype):raise TypeError("Only types can be raised (not instances)")- res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),- ctypes.py_object(exctype))+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(+ ctypes.c_long(tid), ctypes.py_object(exctype)+ )if res == 0:raise ValueError("invalid thread id")elif res != 1:@@ -26,14 +27,15 @@ def _async_raise(tid, exctype):class ThreadWithExc(threading.Thread):- '''A thread class that supports raising an exception in the thread from+ """A thread class that supports raising an exception in the thread fromanother thread.This code is modified from the following SO answer:Author: Philippe FPosted: Nov 28, 2008URL: https://stackoverflow.com/a/325528/- '''+ """+def _get_my_tid(self):"""determines this (self's) thread id@@ -79,12 +81,13 @@ class ThreadWithExc(threading.Thread):caller thread, to raise an exception in the context of thethread represented by this instance."""- _async_raise( self._get_my_tid(), exctype )+ _async_raise(self._get_my_tid(), exctype)# From Martijn Pieters at https://stackoverflow.com/a/14693789# 7-bit C1 ANSI sequences-_ANSI_ESCAPE = re.compile(r'''+_ANSI_ESCAPE = re.compile(+ r"""\x1B # ESC(?: # 7-bit C1 Fe (except CSI)[@-Z\\-_]@@ -94,7 +97,10 @@ _ANSI_ESCAPE = re.compile(r'''[ -/]* # Intermediate bytes[@-~] # Final byte)-''', re.VERBOSE)+""",+ re.VERBOSE,+)+def strip_ansi_sequences(string: str) -> str:- return _ANSI_ESCAPE.sub('', string)\ No newline at end of file+ return _ANSI_ESCAPE.sub("", string)