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]
Web refactor: Split up server.py
Kilian Lieret3982fd3875e9
diff --git a/sweagent/api/__init__.py b/sweagent/api/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.pynew file mode 100644index 00000000..94a0d0cb--- /dev/null+++ b/sweagent/api/hooks.py@@ -0,0 +1,102 @@+from typing import Optional+import sys++from sweagent import PACKAGE_DIR+from sweagent.agent.agents import AgentHook+from flask_socketio import SocketIO++# baaaaaaad+sys.path.append(str(PACKAGE_DIR.parent))+from run import MainHook+++class WebUpdate:+ """This class talks to socketio. It's pretty much a wrapper around socketio.emit.+ """+ def __init__(self, socketio: SocketIO):+ self._socketio = socketio+++ def _emit(self, event, data):+ """Directly wrap around socketio.emit"""+ self._socketio.emit(event, data)++ def up_agent(+ self,+ message: str,+ title: str = "",+ format: str = "markdown",+ thought_idx: Optional[int] =None,+ ):+ """Update the agent feed"""+ self._emit('update', {'feed': 'agent', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})++ def up_env(+ self,+ message: str,+ format: str = "markdown",+ title="",+ thought_idx: Optional[int] =None,+ ):+ """Update the environment feed"""+ self._emit('update', {'feed': 'env', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})++++class MainUpdateHook(MainHook):+ def __init__(self, wu: WebUpdate):+ """This hooks into the Main class to update the web interface"""+ self._wu = wu++ def on_start(self):+ self._wu.up_env(message="Environment container initialized", format="text")++ def on_end(self):+ self._wu.up_agent(message="The run has ended", format="text")++ def on_instance_completed(self, *, info, trajectory):+ self._wu.up_agent(message=f"Instance completed")+++class AgentUpdateHook(AgentHook):+ def __init__(self, wu: WebUpdate):+ """This hooks into the Agent class to update the web interface"""+ self._wu = wu+ self._sub_action = None+ self._thought_idx = 0++ def on_actions_generated(self, *, thought: str, action: str, output: str):+ self._thought_idx += 1+ thought, _, discussion = thought.partition("DISCUSSION")+ self._wu.up_agent(title=f"Thought", message=thought, format="markdown", thought_idx=self._thought_idx)+ self._wu.up_agent(title=f"Discussion", message=discussion, format="markdown", thought_idx=self._thought_idx)++ def on_sub_action_started(self, *, sub_action: dict):+ msg = f"```bash\n{sub_action['action']}\n```"+ self._sub_action = sub_action["action"].strip()+ self._wu.up_env(message=msg, title=f"Action", thought_idx=self._thought_idx)++ def on_sub_action_executed(self, *, obs: str, done: bool):+ language = ""+ if self._sub_action == "submit":+ language = "diff"+ msg = f"```{language}\n{obs}\n```"+ self._wu.up_env(message=msg, thought_idx=self._thought_idx)++ def on_query_message_added(+ self,+ *,+ role: str,+ content: str,+ agent: str,+ is_demo: bool = False,+ thought: str = "",+ action: str = ""+ ):+ if role == "assistant":+ return+ if thought or action:+ return+ if is_demo:+ return self._wu.up_agent(title="Demo", message=content, thought_idx=self._thought_idx + 1)+ self._wu.up_agent(title="Query", message=content, thought_idx=self._thought_idx + 1)diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex 0916f3bb..87e51767 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -1,15 +1,14 @@-import ctypes-import inspectimport os-from typing import Dict, Optional+from typing import Dictfrom flask import Flask, render_template, request, make_response-import threadingimport sysfrom sweagent import CONFIG_DIR, PACKAGE_DIR-from sweagent.agent.agents import AgentArguments, AgentHook+from sweagent.agent.agents import AgentArgumentsfrom sweagent.agent.models import ModelArguments+from sweagent.api.utils import ThreadWithExcfrom sweagent.environment.swe_env import EnvironmentArguments+from sweagent.api.hooks import WebUpdate, MainUpdateHook, AgentUpdateHookimport sweagent.environment.utils as env_utilsfrom flask_socketio import SocketIOfrom flask_cors import CORS@@ -18,7 +17,7 @@ from uuid import uuid4# baaaaaaadsys.path.append(str(PACKAGE_DIR.parent))-from run import ActionsArguments, ScriptArguments, Main, MainHook+from run import ActionsArguments, ScriptArguments, Mainapp = Flask(__name__)CORS(app)@@ -26,104 +25,6 @@ socketio = SocketIO(app, cors_allowed_origins='*')THREADS: Dict[str, "MainThread"] = {}[email protected]('/')-def index():- return render_template("index.html")--[email protected]('connect')-def handle_connect():- print('Client connected')----class WebUpdate:- """This class talks to socketio. It's pretty much a wrapper around socketio.emit.- """- def _emit(self, event, data):- """Directly wrap around socketio.emit"""- socketio.emit(event, data)-- def up_agent(- self,- message: str,- title: str = "",- format: str = "markdown",- thought_idx: Optional[int] =None,- ):- """Update the agent feed"""- self._emit('update', {'feed': 'agent', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})-- def up_env(- self,- message: str,- format: str = "markdown",- title="",- thought_idx: Optional[int] =None,- ):- """Update the environment feed"""- self._emit('update', {'feed': 'env', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})----class MainUpdateHook(MainHook):- def __init__(self, wu: WebUpdate):- """This hooks into the Main class to update the web interface"""- self._wu = wu-- def on_start(self):- self._wu.up_env(message="Environment container initialized", format="text")-- def on_end(self):- self._wu.up_agent(message="The run has ended", format="text")-- def on_instance_completed(self, *, info, trajectory):- self._wu.up_agent(message=f"Instance completed")---class AgentUpdateHook(AgentHook):- def __init__(self, wu: WebUpdate):- """This hooks into the Agent class to update the web interface"""- self._wu = wu- self._sub_action = None- self._thought_idx = 0-- def on_actions_generated(self, *, thought: str, action: str, output: str):- self._thought_idx += 1- thought, _, discussion = thought.partition("DISCUSSION")- self._wu.up_agent(title=f"Thought", message=thought, format="markdown", thought_idx=self._thought_idx)- self._wu.up_agent(title=f"Discussion", message=discussion, format="markdown", thought_idx=self._thought_idx)-- def on_sub_action_started(self, *, sub_action: dict):- msg = f"```bash\n{sub_action['action']}\n```"- self._sub_action = sub_action["action"].strip()- self._wu.up_env(message=msg, title=f"Action", thought_idx=self._thought_idx)-- def on_sub_action_executed(self, *, obs: str, done: bool):- language = ""- if self._sub_action == "submit":- language = "diff"- msg = f"```{language}\n{obs}\n```"- self._wu.up_env(message=msg, thought_idx=self._thought_idx)-- def on_query_message_added(- self,- *,- role: str,- content: str,- agent: str,- is_demo: bool = False,- thought: str = "",- action: str = ""- ):- if role == "assistant":- return- if thought or action:- return- if is_demo:- return self._wu.up_agent(title="Demo", message=content, thought_idx=self._thought_idx + 1)- self._wu.up_agent(title="Query", message=content, thought_idx=self._thought_idx + 1)-def ensure_session_id_set():"""Ensures a session ID is set for this user"""@@ -134,85 +35,6 @@ def ensure_session_id_set():return session_id--def _async_raise(tid, exctype):- '''Raises an exception in the threads with id tid-- This code is modified from the following SO answer:- Author: Philippe F- Posted: Nov 28, 2008- URL: 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))- if res == 0:- raise ValueError("invalid thread id")- elif res != 1:- # "if it returns a number greater than one, you're in trouble,- # and you should call it again with exc=NULL to revert the effect"- ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)- raise SystemError("PyThreadState_SetAsyncExc failed")---class ThreadWithExc(threading.Thread):- '''A thread class that supports raising an exception in the thread from- another thread.-- This code is modified from the following SO answer:- Author: Philippe F- Posted: Nov 28, 2008- URL: https://stackoverflow.com/a/325528/- '''- def _get_my_tid(self):- """determines this (self's) thread id-- CAREFUL: this function is executed in the context of the caller- thread, to get the identity of the thread represented by this- instance.- """- if not self.is_alive():- raise threading.ThreadError("the thread is not active")-- # do we have it cached?- if hasattr(self, "_thread_id"):- return self._thread_id-- # no, look for it in the _active dict- for tid, tobj in threading._active.items():- if tobj is self:- self._thread_id = tid- return tid-- raise RuntimeError("could not determine the thread's id")-- def raise_exc(self, exctype):- """Raises the given exception type in the context of this thread.-- If the thread is busy in a system call (time.sleep(),- socket.accept(), ...), the exception is simply ignored.-- If you are sure that your exception should terminate the thread,- one way to ensure that it works is:-- t = ThreadWithExc( ... )- ...- t.raise_exc( SomeException )- while t.isAlive():- time.sleep( 0.1 )- t.raise_exc( SomeException )-- If the exception is to be caught by the thread, you need a way to- check that your thread has caught it.-- CAREFUL: this function is executed in the context of the- caller thread, to raise an exception in the context of the- thread represented by this instance.- """- _async_raise( self._get_my_tid(), exctype )--class MainThread(ThreadWithExc):def __init__(self, main: Main):super().__init__()@@ -225,6 +47,17 @@ class MainThread(ThreadWithExc):self.raise_exc(SystemExit)[email protected]('/')+def index():+ return render_template("index.html")++[email protected]('connect')+def handle_connect():+ print('Client connected')+++@app.route('/run', methods=['GET', 'OPTIONS'])def run():session_id = ensure_session_id_set()@@ -261,7 +94,7 @@ def run():actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),)main = Main(defaults)- wu = WebUpdate()+ wu = WebUpdate(socketio)main.add_hook(MainUpdateHook(wu))main.agent.add_hook(AgentUpdateHook(wu))thread = MainThread(main)diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pynew file mode 100644index 00000000..5b6c6482--- /dev/null+++ b/sweagent/api/utils.py@@ -0,0 +1,81 @@+import ctypes+import inspect+import threading+++def _async_raise(tid, exctype):+ '''Raises an exception in the threads with id tid++ This code is modified from the following SO answer:+ Author: Philippe F+ Posted: Nov 28, 2008+ URL: 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))+ if res == 0:+ raise ValueError("invalid thread id")+ elif res != 1:+ # "if it returns a number greater than one, you're in trouble,+ # and you should call it again with exc=NULL to revert the effect"+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)+ raise SystemError("PyThreadState_SetAsyncExc failed")+++class ThreadWithExc(threading.Thread):+ '''A thread class that supports raising an exception in the thread from+ another thread.++ This code is modified from the following SO answer:+ Author: Philippe F+ Posted: Nov 28, 2008+ URL: https://stackoverflow.com/a/325528/+ '''+ def _get_my_tid(self):+ """determines this (self's) thread id++ CAREFUL: this function is executed in the context of the caller+ thread, to get the identity of the thread represented by this+ instance.+ """+ if not self.is_alive():+ raise threading.ThreadError("the thread is not active")++ # do we have it cached?+ if hasattr(self, "_thread_id"):+ return self._thread_id++ # no, look for it in the _active dict+ for tid, tobj in threading._active.items():+ if tobj is self:+ self._thread_id = tid+ return tid++ raise RuntimeError("could not determine the thread's id")++ def raise_exc(self, exctype):+ """Raises the given exception type in the context of this thread.++ If the thread is busy in a system call (time.sleep(),+ socket.accept(), ...), the exception is simply ignored.++ If you are sure that your exception should terminate the thread,+ one way to ensure that it works is:++ t = ThreadWithExc( ... )+ ...+ t.raise_exc( SomeException )+ while t.isAlive():+ time.sleep( 0.1 )+ t.raise_exc( SomeException )++ If the exception is to be caught by the thread, you need a way to+ check that your thread has caught it.++ CAREFUL: this function is executed in the context of the+ caller thread, to raise an exception in the context of the+ thread represented by this instance.+ """+ _async_raise( self._get_my_tid(), exctype )\ No newline at end of file