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 feat: Display log messages (partially broken)
Kilian Lieret8f3fe2a4fd86
diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex 87e51767..db34d17b 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -1,3 +1,4 @@+from contextlib import redirect_stderr, redirect_stdoutimport osfrom typing import Dictfrom flask import Flask, render_template, request, make_response@@ -6,13 +7,14 @@ import sysfrom sweagent import CONFIG_DIR, PACKAGE_DIRfrom sweagent.agent.agents import AgentArgumentsfrom sweagent.agent.models import ModelArguments-from sweagent.api.utils import ThreadWithExc+from sweagent.api.utils import ThreadWithExc, strip_ansi_sequencesfrom sweagent.environment.swe_env import EnvironmentArgumentsfrom sweagent.api.hooks import WebUpdate, MainUpdateHook, AgentUpdateHookimport sweagent.environment.utils as env_utilsfrom flask_socketio import SocketIOfrom flask_cors import CORSfrom flask import session+import iofrom uuid import uuid4# baaaaaaad@@ -26,6 +28,7 @@ socketio = SocketIO(app, cors_allowed_origins='*')THREADS: Dict[str, "MainThread"] = {}+def ensure_session_id_set():"""Ensures a session ID is set for this user"""session_id = session.get('session_id', None)@@ -35,13 +38,29 @@ def ensure_session_id_set():return session_id+class StreamToSocketIO(io.StringIO):+ def __init__(self, socketio, ):+ super().__init__()+ self._socketio = socketio++ def write(self, message):+ message = strip_ansi_sequences(message)+ self._socketio.emit("log_message", {'message': message})++ def flush(self):+ pass++class MainThread(ThreadWithExc):def __init__(self, main: Main):super().__init__()self._main = maindef run(self) -> None:- self._main.main()+ # fixme: This actually redirects all output from all threads to the socketio, which is not what we want+ with redirect_stdout(StreamToSocketIO(socketio)):+ with redirect_stderr(StreamToSocketIO(socketio)):+ self._main.main()def stop(self):self.raise_exc(SystemExit)diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pyindex 5b6c6482..89e72d97 100644--- a/sweagent/api/utils.py+++ b/sweagent/api/utils.py@@ -1,5 +1,6 @@import ctypesimport inspect+import reimport threading@@ -78,4 +79,22 @@ 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 )\ No newline at end of file+ _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'''+ \x1B # ESC+ (?: # 7-bit C1 Fe (except CSI)+ [@-Z\\-_]+ | # or [ for CSI, followed by a control sequence+ \[+ [0-?]* # Parameter bytes+ [ -/]* # Intermediate bytes+ [@-~] # Final byte+ )+''', re.VERBOSE)++def strip_ansi_sequences(string: str) -> str:+ return _ANSI_ESCAPE.sub('', string)\ No newline at end of filediff --git a/sweagent/frontend/src/App.css b/sweagent/frontend/src/App.cssindex c1d22da2..5966783b 100644--- a/sweagent/frontend/src/App.css+++ b/sweagent/frontend/src/App.css@@ -64,3 +64,12 @@.highlight {background-color: #eac2c2;}++#log {+ height: 300px;+ max-width: 50%;+ border: 1px solid #ccc;+ border-radius: 5px;+ padding: 10px;+ overflow-y: auto;+}\ No newline at end of filediff --git a/sweagent/frontend/src/App.js b/sweagent/frontend/src/App.jsindex 983e78b9..c5a5c405 100644--- a/sweagent/frontend/src/App.js+++ b/sweagent/frontend/src/App.js@@ -13,6 +13,7 @@ function App() {const [agentFeed, setAgentFeed] = useState([]);const [envFeed, setEnvFeed] = useState([]);const [highlightedStep, setHighlightedStep] = useState(null);+ const [logs, setLogs] = useState('');const agentFeedRef = useRef(null);const envFeedRef = useRef(null);@@ -27,9 +28,10 @@ function App() {// Handle form submissionconst handleSubmit = async (event) => {event.preventDefault();+ setAgentFeed([]);+ setEnvFeed([]);+ setLogs('');try {- setAgentFeed([]); // Clear the agent feed messages- setEnvFeed([]); // Clear the environment feed messagesawait axios.get(`/run`, { params: { data_path: dataPath, test_run: testRun } });} catch (error) {console.error('Error:', error);@@ -53,10 +55,17 @@ function App() {updateFeed(prevMessages => [...prevMessages, { title: data.title, message: data.message, format: data.format, step: data.thought_idx }]);};+ const handleLogMessage = (data) => {+ console.log("Log message: ", data.message);+ setLogs(prevLogs => prevLogs + data.message);+ }+socket.on('update', handleUpdate);+ socket.on('log_message', handleLogMessage);return () => {socket.off('update', handleUpdate);+ socket.off('log_message', handleLogMessage);};}, []);@@ -76,6 +85,10 @@ function App() {<Feed feed={agentFeed} highlightedStep={highlightedStep} handleMouseEnter={handleMouseEnter} selfRef={agentFeedRef} otherRef={envFeedRef} title="Agent Feed" /><Feed feed={envFeed} highlightedStep={highlightedStep} handleMouseEnter={handleMouseEnter} selfRef={envFeedRef} otherRef={agentFeedRef} title="Environment Feed" /></div>+ <div id="log">+ <h3>Logs</h3>+ <pre>{logs}</pre>+ </div></div>);}