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 status to tasks spinners
Kilian Lieretadfd1420f8db
diff --git a/docker/tiny_test.Dockerfile b/docker/tiny_test.Dockerfilenew file mode 100644index 00000000..c45180c4--- /dev/null+++ b/docker/tiny_test.Dockerfile@@ -0,0 +1,7 @@+FROM alpine:latest++WORKDIR /++RUN mkdir -p /root/tools/defaults/lib+COPY tools/defaults/ /root/tools/defaults/+RUN touch /root/tools/defaults/lib/utils.shdiff --git a/sweagent/agent/hooks/status.py b/sweagent/agent/hooks/status.pynew file mode 100644index 00000000..3cc3d456--- /dev/null+++ b/sweagent/agent/hooks/status.py@@ -0,0 +1,17 @@+from collections.abc import Callable++from sweagent.agent.hooks.abstract import AbstractAgentHook+++class SetStatusAgentHook(AbstractAgentHook):+ def __init__(self, id: str, callable: Callable[[str, str], None]):+ self._callable = callable+ self._id = id+ self._i_step = 0++ def _update(self, message: str):+ self._callable(self._id, message)++ def on_step_start(self):+ self._i_step += 1+ self._update(f"Step {self._i_step}")diff --git a/sweagent/environment/hooks/abstract.py b/sweagent/environment/hooks/abstract.pyindex 1db69fe2..78ddd2d3 100644--- a/sweagent/environment/hooks/abstract.py+++ b/sweagent/environment/hooks/abstract.py@@ -15,6 +15,9 @@ class EnvHook:def on_copy_repo_started(self, repo: RepoConfig | Repo) -> None:"""Gets called when the repository is being cloned to the container"""+ def on_start_deployment(self) -> None:+ """Gets called when the deployment is being started"""+def on_install_env_started(self) -> None:"""Called when we start installing the environment"""@@ -40,6 +43,10 @@ class CombinedEnvHooks(EnvHook):for hook in self._hooks:hook.on_copy_repo_started(repo=repo)+ def on_start_deployment(self) -> None:+ for hook in self._hooks:+ hook.on_start_deployment()+def on_install_env_started(self) -> None:for hook in self._hooks:hook.on_install_env_started()diff --git a/sweagent/environment/hooks/status.py b/sweagent/environment/hooks/status.pynew file mode 100644index 00000000..00dbd3b4--- /dev/null+++ b/sweagent/environment/hooks/status.py@@ -0,0 +1,28 @@+from collections.abc import Callable++from sweagent.environment.config.repo import Repo, RepoConfig+from sweagent.environment.hooks.abstract import EnvHook+++class SetStatusEnvironmentHook(EnvHook):+ def __init__(self, id: str, callable: Callable[[str, str], None]):+ self._callable = callable+ self._id = id++ def _update(self, message: str):+ self._callable(self._id, message)++ def on_copy_repo_started(self, repo: RepoConfig | Repo):+ self._update(f"Copying repo {repo.repo_name}")++ def on_start_deployment(self):+ self._update("Starting deployment")++ def on_install_env_started(self):+ self._update("Installing environment")++ def on_environment_startup(self):+ self._update("Starting environment")++ def on_close(self):+ self._update("Closing environment")diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex a3c4b8e4..21978672 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -136,6 +136,7 @@ class SWEEnv:"""Handles container initialization. Defines container name and creates it.If cached_image is provided, it will use that image name instead of the default."""+ self._chook.on_start_deployment()asyncio.run(self.deployment.start())asyncio.run(self.deployment.runtime.create_session(CreateBashSessionRequest(startup_source=["/root/.bashrc"])))self.logger.info("Environment Initialized")diff --git a/sweagent/run/rich_test.py b/sweagent/run/rich_test.pynew file mode 100644index 00000000..dc56d6a7--- /dev/null+++ b/sweagent/run/rich_test.py@@ -0,0 +1,91 @@+import logging+import time+from concurrent.futures import ThreadPoolExecutor+from random import random+from threading import Lock++from rich.console import Group+from rich.live import Live+from rich.logging import RichHandler+from rich.progress import (+ BarColumn,+ Progress,+ SpinnerColumn,+ TaskID,+ TaskProgressColumn,+ TextColumn,+ TimeElapsedColumn,+ TimeRemainingColumn,+)++logging.basicConfig(level="NOTSET", handlers=[RichHandler(level="NOTSET")])+logger = logging.getLogger("rich")++# Lock for thread-safe progress updates+progress_lock = Lock()+++class RunBatch:+ def __init__(self):+ self.tasks = list(range(10)) # Reduced to 10 tasks for example clarity+ self._main_progress_bar: Progress | None = None+ self._task_progress_bar: Progress | None = None+ self._spinner_tasks: dict[TaskID, TaskID] = {}++ def do_task(self, task_id: TaskID):+ assert self._main_progress_bar is not None+ assert self._task_progress_bar is not None++ # Create a spinner for this task+ with progress_lock:+ spinner_task_id = self._task_progress_bar.add_task(f"Task {task_id}", total=None)++ logger.info("Starting task %d", task_id)+ # Startup+ time.sleep(random() * 4.5)+ # Work+ with progress_lock:+ self._task_progress_bar.update(spinner_task_id, description=f"Task {task_id} (working)")+ time.sleep(random() * 4.5 + 2)+ logger.info("Finished task %d", task_id)++ # Remove spinner and update main progress+ with progress_lock:+ self._task_progress_bar.remove_task(spinner_task_id)+ self._main_progress_bar.update(TaskID(0), advance=1)++ def main(self):+ # Custom progress columns+ self._main_progress_bar = Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TaskProgressColumn(),+ TimeElapsedColumn(),+ TimeRemainingColumn(),+ )+ self._task_progress_bar = Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ TimeElapsedColumn(),+ )++ group = Group(self._main_progress_bar, self._task_progress_bar)++ with Live(group):+ # Add main progress bar+ self._main_task_id = self._main_progress_bar.add_task("[cyan]Overall Progress", total=len(self.tasks))++ # Create thread pool and run tasks+ with ThreadPoolExecutor(max_workers=5) as executor:+ # Submit all tasks+ futures = [executor.submit(self.do_task, task_id) for task_id in self.tasks]++ # Wait for all tasks to complete+ for future in futures:+ future.result()+++if __name__ == "__main__":+ run_batch = RunBatch()+ run_batch.main()diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.pyindex 4dd94b96..72969053 100644--- a/sweagent/run/run_batch.py+++ b/sweagent/run/run_batch.py@@ -27,6 +27,8 @@ from rich.progress import ()from sweagent.agent.agents import Agent, AgentConfig+from sweagent.agent.hooks.status import SetStatusAgentHook+from sweagent.environment.hooks.status import SetStatusEnvironmentHookfrom sweagent.environment.swe_env import SWEEnvfrom sweagent.run.batch_instances import BatchInstance, BatchInstanceSourceConfigfrom sweagent.run.common import BasicCLI, save_predictions@@ -97,7 +99,7 @@ class RunBatch:self._main_progress_bar: Progress | None = Noneself._task_progress_bar: Progress | None = None- self._spinner_tasks: dict[TaskID, TaskID] = {}+ self._spinner_tasks: dict[str, TaskID] = {}self._progress_lock = Lock()@classmethod@@ -166,7 +168,8 @@ class RunBatch:)self._task_progress_bar = Progress(SpinnerColumn(),- TextColumn("[progress.description]{task.description}"),+ TextColumn("{task.fields[instance_id]}: "),+ TextColumn("{task.fields[status]}"),TimeElapsedColumn(),)self._main_progress_bar.add_task("[cyan]Overall Progress", total=len(self.instances))@@ -201,7 +204,12 @@ class RunBatch:def run_instance(self, instance: BatchInstance):if self._task_progress_bar is not None:with self._progress_lock:- spinner_task_id = self._task_progress_bar.add_task(f"Task {instance.problem_statement.id}", total=None)+ self._spinner_tasks[instance.problem_statement.id] = self._task_progress_bar.add_task(+ description=f"Task {instance.problem_statement.id}",+ status="Task initialized",+ total=None,+ instance_id=instance.problem_statement.id,+ )# Either catch and silence exception, or raise _BreakLoop to stop the loop# over the instances@@ -223,16 +231,24 @@ class RunBatch:if self._task_progress_bar is not None:assert self._main_progress_bar is not Nonewith self._progress_lock:- self._task_progress_bar.remove_task(spinner_task_id)+ self._task_progress_bar.remove_task(self._spinner_tasks[instance.problem_statement.id])self._main_progress_bar.update(TaskID(0), advance=1)+ def _update_task_progress(self, instance_id: str, message: str):+ assert self._task_progress_bar is not None+ assert self._main_progress_bar is not None+ with self._progress_lock:+ self._task_progress_bar.update(self._spinner_tasks[instance_id], status=message, instance_id=instance_id)+def _run_instance(self, instance: BatchInstance):if self.should_skip(instance):returnagent = Agent.from_config(self.agent_config)agent.logger.setLevel(logging.DEBUG if self._num_workers == 1 else logging.WARNING)- self.logger.info("Starting environment")+ agent.add_hook(SetStatusAgentHook(instance.problem_statement.id, self._update_task_progress))+ self._update_task_progress(instance.problem_statement.id, "Starting environment")env = SWEEnv.from_config(instance.env)+ env.add_hook(SetStatusEnvironmentHook(instance.problem_statement.id, self._update_task_progress))env.logger.setLevel(logging.DEBUG if self._num_workers == 1 else logging.INFO)env.deployment.logger.setLevel(logging.DEBUG if self._num_workers == 1 else logging.WARNING) # type: ignoreenv.start()diff --git a/tests/test_data/data_sources/simple_instances_long.yaml b/tests/test_data/data_sources/simple_instances_long.yamlnew file mode 100644index 00000000..c0988ace--- /dev/null+++ b/tests/test_data/data_sources/simple_instances_long.yaml@@ -0,0 +1,30 @@+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "1"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "2"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "3"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "4"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "5"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "6"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "7"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "8"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "9"+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "10"