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]

Sort imports

Kilian Lieretf873761e6760
diff --git a/evaluation/aggregate_results.py b/evaluation/aggregate_results.py
index 8776538e..e282970f 100644
--- a/evaluation/aggregate_results.py
+++ b/evaluation/aggregate_results.py
@@ -1,14 +1,16 @@
import argparse
import glob
import json
-import numpy as np
import os
-import pandas as pd
import warnings
+import numpy as np
+import pandas as pd
+
warnings.filterwarnings("ignore")
from pathlib import Path
+
from rich import print
COLUMNS = [
diff --git a/evaluation/evaluation.py b/evaluation/evaluation.py
index 10037a64..2baeca0f 100644
--- a/evaluation/evaluation.py
+++ b/evaluation/evaluation.py
@@ -2,19 +2,19 @@ import argparse
import json
import os
import traceback
-
from collections import Counter
+
from rich import print
from swebench import (
KEY_INSTANCE_ID,
KEY_MODEL,
KEY_PREDICTION,
+ get_eval_refs,
get_eval_report,
get_logs_eval,
get_model_report,
get_resolution_status,
run_evaluation,
- get_eval_refs,
)
from swebench.harness.constants import (
INSTALL_FAIL,
diff --git a/inspector/server.py b/inspector/server.py
index 4e9eef7c..f9b73cd1 100644
--- a/inspector/server.py
+++ b/inspector/server.py
@@ -2,12 +2,12 @@ import http.server
import json
import os
import socketserver
-from typing import Any, Dict, Optional, List
-import yaml
-
-from pathlib import Path
from argparse import ArgumentParser
from functools import partial
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+import yaml
def append_exit(content):
diff --git a/inspector/static.py b/inspector/static.py
index ed36ddfc..508e857c 100644
--- a/inspector/static.py
+++ b/inspector/static.py
@@ -1,9 +1,10 @@
import json
import logging
-import yaml
+from argparse import ArgumentParser
from pathlib import Path
+
+import yaml
from tqdm.auto import tqdm
-from argparse import ArgumentParser
try:
from .server import load_content
diff --git a/make_demos/convert_traj_to_demo.py b/make_demos/convert_traj_to_demo.py
index 708a2ed8..078466f5 100644
--- a/make_demos/convert_traj_to_demo.py
+++ b/make_demos/convert_traj_to_demo.py
@@ -1,10 +1,10 @@
-import json
import io
-from ruamel.yaml import YAML
-from ruamel.yaml.scalarstring import LiteralScalarString as LSS
-from pathlib import Path
+import json
from argparse import ArgumentParser
+from pathlib import Path
+from ruamel.yaml import YAML
+from ruamel.yaml.scalarstring import LiteralScalarString as LSS
DEMO_COMMENT = """# This is a demo file generated from trajectory file:
# {traj_path}
diff --git a/pyproject.toml b/pyproject.toml
index 034ddb33..927f1170 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -114,7 +114,8 @@ target-version = "py39"
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
-select = ["F821", "F822", "E999", "E902", "F401", "F841"]
+# I001: Isort
+select = ["F821", "F822", "E999", "E902", "F401", "F841", "I001"]
ignore = []
# Allow fix for all enabled rules (when `--fix`) is provided.
diff --git a/run.py b/run.py
index 118e8ef2..1c1ebd73 100644
--- a/run.py
+++ b/run.py
@@ -12,25 +12,29 @@ import re
import subprocess
import traceback
from typing import Any, Dict, List, Optional
+
import rich.console
import rich.markdown
import rich.panel
-import rich.markdown
try:
from rich_argparse import RichHelpFormatter
except ImportError:
msg = "Please install the rich_argparse package with `pip install rich_argparse`."
raise ImportError(msg)
-import yaml
-from rich.markdown import Markdown
from dataclasses import dataclass
from getpass import getuser
from pathlib import Path
+
+import yaml
from rich.logging import RichHandler
+from rich.markdown import Markdown
from simple_parsing import parse
-from simple_parsing.helpers.serialization.serializable import FrozenSerializable
from simple_parsing.helpers.flatten import FlattenedAccess
+from simple_parsing.helpers.serialization.serializable import FrozenSerializable
+from swebench import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION
+from unidiff import PatchSet
+
from sweagent import (
Agent,
AgentArguments,
@@ -39,9 +43,6 @@ from sweagent import (
SWEEnv,
get_data_path_name,
)
-from swebench import KEY_INSTANCE_ID, KEY_MODEL, KEY_PREDICTION
-from unidiff import PatchSet
-
from sweagent.environment.utils import (
InvalidGithubURL,
get_associated_commit_urls,
diff --git a/run_replay.py b/run_replay.py
index 81573016..f2b5962f 100644
--- a/run_replay.py
+++ b/run_replay.py
@@ -2,10 +2,11 @@
import json
import os
-import yaml
-
from argparse import ArgumentParser
from typing import Any, Dict, List
+
+import yaml
+
import run as runscript
diff --git a/sweagent/__init__.py b/sweagent/__init__.py
index 388dace2..162e662c 100644
--- a/sweagent/__init__.py
+++ b/sweagent/__init__.py
@@ -1,20 +1,18 @@
__version__ = "0.2.0"
from pathlib import Path
+
from sweagent.agent.agents import (
Agent,
AgentArguments,
)
-
from sweagent.agent.models import (
ModelArguments,
)
-
from sweagent.environment.swe_env import (
EnvironmentArguments,
SWEEnv,
)
-
from sweagent.environment.utils import (
get_data_path_name,
)
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index e428ca3e..8d3d993b 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -1,12 +1,15 @@
import json
-import re
import logging
-
+import re
from dataclasses import dataclass
from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, TypedDict
+
from simple_parsing.helpers.fields import field
-from simple_parsing.helpers.serialization.serializable import FrozenSerializable
from simple_parsing.helpers.flatten import FlattenedAccess
+from simple_parsing.helpers.serialization.serializable import FrozenSerializable
+from tenacity import RetryError
+
from sweagent.agent.commands import Command, ParseCommand
from sweagent.agent.history_processors import HistoryProcessor
from sweagent.agent.models import (
@@ -16,11 +19,9 @@ from sweagent.agent.models import (
ModelArguments,
get_model,
)
-from sweagent.agent.parsing import ParseFunction, FormatError
-from sweagent.environment.utils import LOGGER_NAME
+from sweagent.agent.parsing import FormatError, ParseFunction
from sweagent.environment.swe_env import SWEEnv
-from tenacity import RetryError
-from typing import Dict, List, Optional, Tuple, Any, TypedDict
+from sweagent.environment.utils import LOGGER_NAME
logger = logging.getLogger(LOGGER_NAME)
diff --git a/sweagent/agent/commands.py b/sweagent/agent/commands.py
index 312d2305..c18a84d6 100644
--- a/sweagent/agent/commands.py
+++ b/sweagent/agent/commands.py
@@ -1,10 +1,10 @@
import re
-import yaml
-
from abc import abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional
+
+import yaml
from simple_parsing.helpers.serialization.serializable import FrozenSerializable
diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.py
index 978862ac..4f559b15 100644
--- a/sweagent/agent/history_processors.py
+++ b/sweagent/agent/history_processors.py
@@ -1,5 +1,4 @@
import re
-
from abc import abstractmethod
from dataclasses import dataclass
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 255320e5..275ff2cd 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -1,23 +1,24 @@
import json
import logging
import os
-import together
-
from collections import defaultdict
-from anthropic import Anthropic, AnthropicBedrock, HUMAN_PROMPT, AI_PROMPT
from dataclasses import dataclass, fields
-from openai import BadRequestError, OpenAI, AzureOpenAI
+from typing import Optional, Union
+
+import together
+from anthropic import AI_PROMPT, HUMAN_PROMPT, Anthropic, AnthropicBedrock
+from openai import AzureOpenAI, BadRequestError, OpenAI
+from rich.logging import RichHandler
from simple_parsing.helpers.serialization.serializable import FrozenSerializable, Serializable
-from sweagent.utils.config import Config
-from sweagent.agent.commands import Command
from tenacity import (
retry,
+ retry_if_not_exception_type,
stop_after_attempt,
wait_random_exponential,
- retry_if_not_exception_type,
)
-from typing import Optional, Union
-from rich.logging import RichHandler
+
+from sweagent.agent.commands import Command
+from sweagent.utils.config import Config
logger = logging.getLogger("api_models")
handler = RichHandler(show_time=False, show_path=False)
diff --git a/sweagent/agent/parsing.py b/sweagent/agent/parsing.py
index e5d2bfe3..9c89cc30 100644
--- a/sweagent/agent/parsing.py
+++ b/sweagent/agent/parsing.py
@@ -1,14 +1,14 @@
-import re
import json
+import re
import shlex
import string
import textwrap
-
from abc import abstractmethod
from dataclasses import dataclass
-from sweagent.agent.commands import Command
from typing import List
+from sweagent.agent.commands import Command
+
class FormatError(Exception):
pass
diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.py
index fcc7b58c..aa2b9db6 100644
--- a/sweagent/api/hooks.py
+++ b/sweagent/api/hooks.py
@@ -1,11 +1,11 @@
-from typing import Optional
-import sys
import io
+import sys
+from typing import Optional
-from sweagent import PACKAGE_DIR
-from sweagent.agent.agents import AgentHook
from flask_socketio import SocketIO
+from sweagent import PACKAGE_DIR
+from sweagent.agent.agents import AgentHook
from sweagent.api.utils import strip_ansi_sequences
from sweagent.environment.swe_env import EnvHook
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index 59554e65..41e73830 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -6,36 +6,35 @@ except ImportError as e:
"Please go to the root of the repository and run `pip install -e .`"
)
raise RuntimeError(msg) from e
-from contextlib import redirect_stderr, redirect_stdout
+import atexit
import copy
import json
import os
-from pathlib import Path
+import sys
+import tempfile
import time
import traceback
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
from typing import Any, Dict
-from flask import Flask, render_template, request, make_response
-import sys
+from uuid import uuid4
import yaml
+from flask import Flask, make_response, render_template, request, session
+from flask_cors import CORS
+from flask_socketio import SocketIO
+import sweagent.environment.utils as env_utils
from sweagent import CONFIG_DIR, PACKAGE_DIR
from sweagent.agent.agents import AgentArguments
from sweagent.agent.models import ModelArguments
-from sweagent.api.utils import ThreadWithExc, AttrDict
+from sweagent.api.hooks import AgentUpdateHook, EnvUpdateHook, MainUpdateHook, WebUpdate
+from sweagent.api.utils import AttrDict, ThreadWithExc
from sweagent.environment.swe_env import EnvironmentArguments
-from sweagent.api.hooks import EnvUpdateHook, WebUpdate, MainUpdateHook, AgentUpdateHook
-import sweagent.environment.utils as env_utils
-from flask_socketio import SocketIO
-from flask_cors import CORS
-from flask import session
-from uuid import uuid4
-import tempfile
-import atexit
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
-from run import ActionsArguments, ScriptArguments, Main
+from run import ActionsArguments, Main, ScriptArguments
app = Flask(__name__)
CORS(app)
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 49384d32..b586a38d 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -1,41 +1,41 @@
-from pathlib import Path
-import random
import datetime
-import docker
-import gymnasium as gym
import hashlib
import logging
import os
+import random
import re
import subprocess
-import traceback
import time
+import traceback
+from dataclasses import dataclass
+from pathlib import Path
+from typing import List, Optional, Tuple
+import gymnasium as gym
+import yaml
from ghapi.all import GhApi
-from dataclasses import dataclass
from git import Repo
from rich.logging import RichHandler
from simple_parsing.helpers.serialization.serializable import FrozenSerializable
-import yaml
+from swebench import MAP_VERSION_TO_INSTALL, get_environment_yml, get_requirements
+
+import docker
from sweagent.environment.utils import (
+ LOGGER_NAME,
PROCESS_DONE_MARKER_END,
PROCESS_DONE_MARKER_START,
InvalidGithubURL,
- image_exists,
copy_anything_to_container,
copy_file_to_container,
format_trajectory_markdown,
get_container,
get_gh_issue_data,
get_instances,
+ image_exists,
parse_gh_issue_url,
read_with_timeout,
- LOGGER_NAME,
read_with_timeout_experimental,
)
-from swebench import get_environment_yml, get_requirements, MAP_VERSION_TO_INSTALL
-from typing import List, Optional, Tuple
-
from sweagent.utils.config import Config
LONG_TIMEOUT = 500
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index d62f3c99..c4e7c5d8 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -1,26 +1,26 @@
import hashlib
-import platform
-import shlex
-import docker
import json
import logging
import os
+import platform
import re
+import shlex
import subprocess
import tarfile
import tempfile
import time
import traceback
-
-from datasets import load_dataset, load_from_disk
-from ghapi.all import GhApi
from io import BytesIO
from pathlib import Path
from subprocess import PIPE, STDOUT
-from typing import Any, List, Optional, Set, Tuple, Dict
+from typing import Any, Dict, List, Optional, Set, Tuple
+from datasets import load_dataset, load_from_disk
+from ghapi.all import GhApi
from git import InvalidGitRepositoryError, Repo
+import docker
+
LOGGER_NAME = "intercode"
START_UP_DELAY = 5
TIMEOUT_DURATION = 25
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index d10ae0bc..323ace99 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -1,8 +1,8 @@
import logging
-from typing import Any
-import config as config_file
import os
+from typing import Any
+import config as config_file
logger = logging.getLogger("config")
diff --git a/tests/conftest.py b/tests/conftest.py
index c0fe47ba..70a792ea 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,9 +1,10 @@
-import os
import json
+import os
import sys
from pathlib import Path
from pytest import fixture
+
import sweagent.environment.utils as env_utils
# this is a hack and should be removed when we have a better solution
diff --git a/tests/test_env.py b/tests/test_env.py
index e2d35341..0247e7ca 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -1,13 +1,15 @@
import dataclasses
import os
-from pathlib import Path
import subprocess
import time
+from contextlib import contextmanager
+from pathlib import Path
+
import pytest
import yaml
-from sweagent.environment.swe_env import EnvHook, EnvironmentArguments, SWEEnv
-from contextlib import contextmanager
+
import docker
+from sweagent.environment.swe_env import EnvHook, EnvironmentArguments, SWEEnv
@pytest.fixture(scope="module")
diff --git a/tests/test_models.py b/tests/test_models.py
index 2139dd92..49d37204 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -1,7 +1,9 @@
from unittest.mock import MagicMock, Mock, patch
-from sweagent.agent.models import OpenAIModel, ModelArguments, TogetherModel
+
import pytest
+from sweagent.agent.models import ModelArguments, OpenAIModel, TogetherModel
+
@pytest.fixture
def openai_mock_client():
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index e9411c3f..70bcc1f6 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -1,14 +1,15 @@
import pytest
+
from sweagent.agent.commands import Command
from sweagent.agent.parsing import (
- FormatError,
- ParseFunction,
ActionParser,
- ThoughtActionParser,
- XMLThoughtActionParser,
EditFormat,
+ FormatError,
Identity,
JsonParser,
+ ParseFunction,
+ ThoughtActionParser,
+ XMLThoughtActionParser,
)
diff --git a/tests/test_replay.py b/tests/test_replay.py
index 74bea1a7..30885ef0 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -1,8 +1,10 @@
-from pathlib import Path
import subprocess
-from run_replay import get_args, main
+from pathlib import Path
+
import pytest
+from run_replay import get_args, main
+
@pytest.fixture
def swe_agent_test_repo_clone(tmp_path):
diff --git a/tests/test_run.py b/tests/test_run.py
index 53f21bd5..9c1bfe8f 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -1,8 +1,9 @@
import json
import os
-from pathlib import Path
import subprocess
+from pathlib import Path
from typing import Any, Dict
+
import pytest
from run import ActionsArguments, Main, MainHook, OpenPRHook, ScriptArguments
diff --git a/tests/test_utils.py b/tests/test_utils.py
index bfe1aa1a..57f93232 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,21 +1,22 @@
import hashlib
import os
import subprocess
+
import pytest
+
from sweagent.environment.utils import (
+ _MARKDOWN_TRAJECTORY_EMOJI_MAPPING,
InvalidGithubURL,
format_trajectory_markdown,
- _MARKDOWN_TRAJECTORY_EMOJI_MAPPING,
+ get_associated_commit_urls,
get_instances,
+ is_github_issue_url,
is_github_repo_url,
- remove_triple_backticks,
- parse_gh_repo_url,
parse_gh_issue_url,
- is_github_issue_url,
- get_associated_commit_urls,
+ parse_gh_repo_url,
+ remove_triple_backticks,
)
-
_TOKEN = {"token": os.environ.get("GITHUB_TOKEN", "")}