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 per-instance log files
Kilian Lieret167bc51716f2
diff --git a/sweagent/__init__.py b/sweagent/__init__.pyindex c9d88c02..167c7347 100644--- a/sweagent/__init__.py+++ b/sweagent/__init__.py@@ -7,6 +7,13 @@ __version__ = "0.7.0"from logging import WARNING, getLoggerfrom pathlib import Path+import swerex.utils.log as log_swerex++from sweagent.utils.log import get_logger++# Monkey patch the logger to use our implementation+log_swerex.get_logger = get_logger+# See https://github.com/princeton-nlp/SWE-agent/issues/585getLogger("datasets").setLevel(WARNING)getLogger("numexpr.utils").setLevel(WARNING)diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 808e0936..e1517001 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -127,7 +127,7 @@ class Agent:self.tools = toolsself.history_processor = history_processorself.max_requeries = max_requeries- self.logger = get_logger(f"agent-{name}", emoji="π€ ")+ self.logger = get_logger("swea-agent", emoji="π€ ")# Set in run methodself._env: SWEEnv | None = Nonediff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex c5dd30aa..a91e0050 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -24,7 +24,7 @@ from sweagent.tools.commands import Commandfrom sweagent.types import History, HistoryItemfrom sweagent.utils.log import get_logger-logger = get_logger("lm", emoji="π€")+logger = get_logger("swea-lm", emoji="π€")class RetryConfig(PydanticBaseModel):diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.pyindex 6a0aeb3b..74c0a17c 100644--- a/sweagent/environment/config/problem_statement.py+++ b/sweagent/environment/config/problem_statement.py@@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom sweagent.utils.github import _get_problem_statement_from_github_issue, _parse_gh_issue_urlfrom sweagent.utils.log import get_logger-logger = get_logger("Config", emoji="π§")+logger = get_logger("swea-config", emoji="π§")class ProblemStatement(Protocol):diff --git a/sweagent/environment/config/repo.py b/sweagent/environment/config/repo.pyindex 7a1779b3..eb5c72e9 100644--- a/sweagent/environment/config/repo.py+++ b/sweagent/environment/config/repo.py@@ -13,7 +13,7 @@ from typing_extensions import Selffrom sweagent.utils.log import get_logger-logger = get_logger("Config", emoji="π§")+logger = get_logger("swea-config", emoji="π§")class Repo(Protocol):diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex dab66de0..d36b17d8 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -47,7 +47,7 @@ class SWEEnv:self.deployment = deploymentself.repo = repoself._startup_commands = startup_commands- self.logger = get_logger(f"env-{name}", emoji="π±")+ self.logger = get_logger("swea-env", emoji="π±")self.name = nameself.clean_multi_line_functions = lambda x: xself._chook = CombinedEnvHooks()diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex 9029f292..67c434ea 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -20,7 +20,7 @@ from sweagent.environment.config.repo import PreExistingRepofrom sweagent.environment.swe_env import EnvironmentConfigfrom sweagent.utils.log import get_logger-logger = get_logger("config", emoji="π§")+logger = get_logger("swea-config", emoji="π§")class AbstractInstanceSource(ABC):diff --git a/sweagent/run/common.py b/sweagent/run/common.pyindex 90cdb761..6246bae0 100644--- a/sweagent/run/common.py+++ b/sweagent/run/common.py@@ -18,7 +18,7 @@ class BasicCLI:def __init__(self, arg_type: type[BaseSettings], default_settings: bool = True):self.arg_type = arg_typeself.default_settings = default_settings- self.logger = get_logger("CLI", emoji="π§")+ self.logger = get_logger("swea-cli", emoji="π§")def get_args(self, args=None) -> BaseSettings:# The defaults if no config file is provideddiff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.pyindex 0334262c..e89f6950 100644--- a/sweagent/run/hooks/apply_patch.py+++ b/sweagent/run/hooks/apply_patch.py@@ -18,7 +18,7 @@ class SaveApplyPatchHook(RunHook):"""This hook saves patches to a separate directory and optionally applies them to a local repository."""def __init__(self, apply_patch_locally: bool = False):- self.logger = get_logger("SaveApplyPatchHook", emoji="β‘οΈ")+ self.logger = get_logger("swea-save_apply_patch", emoji="β‘οΈ")self._apply_patch_locally = apply_patch_locallydef on_init(self, *, run):diff --git a/sweagent/run/hooks/open_pr.py b/sweagent/run/hooks/open_pr.pyindex c98392b7..a901e966 100644--- a/sweagent/run/hooks/open_pr.py+++ b/sweagent/run/hooks/open_pr.py@@ -119,7 +119,7 @@ class OpenPRHook(RunHook):"""This hook opens a PR if the issue is solved and the user has enabled the option."""def __init__(self, config: OpenPRConfig):- self.logger = get_logger("β‘οΈ OpenPRHook")+ self.logger = get_logger("swea-open_pr", emoji="β‘οΈ")self._config = configdef on_init(self, *, run):diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.pyindex 6a008772..b1e0d5b2 100644--- a/sweagent/run/run_batch.py+++ b/sweagent/run/run_batch.py@@ -28,7 +28,13 @@ from sweagent.run.hooks.abstract import CombinedRunHooks, RunHookfrom sweagent.run.hooks.apply_patch import SaveApplyPatchHookfrom sweagent.types import AgentRunResultfrom sweagent.utils.config import load_environment_variables-from sweagent.utils.log import add_logger_names_to_stream_handlers, get_logger+from sweagent.utils.log import (+ add_file_handler,+ add_logger_names_to_stream_handlers,+ get_logger,+ register_thread_name,+ set_default_stream_level,+)class RunBatchConfig(BaseSettings, cli_implicit_flags=True):@@ -43,7 +49,7 @@ class RunBatchConfig(BaseSettings, cli_implicit_flags=True):"""Number of parallel workers to use. Default is 1 (sequential execution)."""random_delay_multiplier: float = 0.3"""We will wait for a random amount of time between 0 and `random_delay_multiplier`- times the number of instances at the start of each instance. This is to avoid any+ times the number of workers at the start of each instance. This is to avoid anypotential race conditions."""@@ -83,7 +89,7 @@ class RunBatch:hooks: If not specified, the default hooks will be used.num_workers: Number of parallel workers to use. Default is 1 (sequential execution)."""- self.logger = get_logger("Run", emoji="π")+ self.logger = get_logger("swea-run", emoji="π")self.instances = instancesself.agent_config = agent_configself.output_dir = output_dir@@ -91,7 +97,7 @@ class RunBatch:self._raise_exceptions = raise_exceptionsself._chooks = CombinedRunHooks()self._redo_existing = redo_existing- self._num_workers = num_workers+ self._num_workers = min(num_workers, len(instances))for hook in hooks or [SaveApplyPatchHook()]:self.add_hook(hook)@@ -102,7 +108,7 @@ class RunBatch:load_environment_variables(config.env_var_path)config.set_default_output_dir()config.output_dir.mkdir(parents=True, exist_ok=True)- logger = get_logger("RunBatch", emoji="π")+ logger = get_logger("run", emoji="π")logger.debug("Loading instances from %s", f"{config.instances!r}")instances = config.instances.get_instance_configs()logger.info("Loaded %d instances", len(instances))@@ -128,6 +134,7 @@ class RunBatch:self._hooks.append(hook)def main(self) -> None:+ self.logger.info("Starting run. Find output files at %s", self.output_dir)self._chooks.on_start()if self._num_workers <= 1:@@ -153,6 +160,7 @@ class RunBatch:def main_multi_worker(self) -> None:add_logger_names_to_stream_handlers()+ set_default_stream_level(logging.WARNING)with Live(self._progress_manager.render_group):with ThreadPoolExecutor(max_workers=self._num_workers) as executor:@@ -171,8 +179,10 @@ class RunBatch:self._progress_manager.print_report()def run_instance(self, instance: BatchInstance) -> None:+ register_thread_name(instance.problem_statement.id)+ self._add_instance_log_file_handlers(instance.problem_statement.id, multi_worker=self._num_workers > 1)# Let's add some randomness to avoid any potential race conditions- time.sleep(random.random() * 0.3 * (len(self.instances) - 1))+ time.sleep(random.random() * 0.3 * (self._num_workers - 1))self._progress_manager.on_instance_start(instance.problem_statement.id)@@ -207,18 +217,14 @@ class RunBatch:def _run_instance(self, instance: BatchInstance) -> AgentRunResult:self.agent_config.name = f"{instance.problem_statement.id}"agent = Agent.from_config(self.agent_config)- agent.logger.setLevel(logging.DEBUG if self._num_workers == 1 else logging.WARNING)agent.add_hook(SetStatusAgentHook(instance.problem_statement.id, self._progress_manager.update_instance_status))self._progress_manager.update_instance_status(instance.problem_statement.id, "Starting environment")instance.env.name = f"{instance.problem_statement.id}"env = SWEEnv.from_config(instance.env)- env.deployment.logger = get_logger(f"rex-{instance.problem_statement.id}", emoji="π¦")- env.deployment.logger.setLevel(logging.DEBUG if self._num_workers == 1 else logging.WARNING)env.add_hook(SetStatusEnvironmentHook(instance.problem_statement.id, self._progress_manager.update_instance_status))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.deployment.add_hook(SetStatusDeploymentHook(instance.problem_statement.id, self._progress_manager.update_instance_status))@@ -263,6 +269,12 @@ class RunBatch:self.logger.info(f"βοΈ Skipping existing trajectory: {log_path}")return True+ def _add_instance_log_file_handlers(self, instance_id: str, multi_worker: bool = False) -> None:+ filename_template = f"{instance_id}.{{level}}.log"+ for level in ["trace", "debug", "info"]:+ filter = instance_id if multi_worker else ""+ add_file_handler(self.output_dir / filename_template.format(level=level), filter=filter, level=level)+def run_from_config(args: RunBatchConfig):RunBatch.from_config(args).main()diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.pyindex 82f32eaf..fc76e52e 100644--- a/sweagent/run/run_replay.py+++ b/sweagent/run/run_replay.py@@ -62,7 +62,7 @@ class RunReplay:self.repo = repoself.output_dir = output_dirself._replay_action_trajs_path = Path(tempfile.NamedTemporaryFile(suffix=".json").name)- self.logger = get_logger("RunReplay", emoji="π")+ self.logger = get_logger("swea-run", emoji="π")self._catch_errors = _catch_errorsself._require_zero_exit_code = _require_zero_exit_codediff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.pyindex 337841ec..4175a338 100644--- a/sweagent/run/run_single.py+++ b/sweagent/run/run_single.py@@ -81,7 +81,7 @@ class RunSingle:"""Note: When initializing this class, make sure to add the hooks that are required by your actions.See `from_config` for an example."""- self.logger = get_logger("Run", emoji="π")+ self.logger = get_logger("swea-run", emoji="π")self.env = envself.agent = agentself.output_dir = output_dir@@ -100,7 +100,7 @@ class RunSingle:@classmethoddef from_config(cls, config: RunSingleConfig) -> Self:- logger = get_logger("Run", emoji="π")+ logger = get_logger("swea-run", emoji="π")if config.print_config:config_str = yaml.dump(config.model_dump())logger.info(f"Config:\n {config_str}")diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.pyindex 4fe5788b..19792163 100644--- a/sweagent/tools/tools.py+++ b/sweagent/tools/tools.py@@ -148,7 +148,7 @@ class ToolHandler:# partially initialized in `install_commands`.self._reset_commands = []self._command_patterns = self._get_command_patterns()- self.logger = get_logger("Tools", emoji="π§°")+ self.logger = get_logger("swea-tools", emoji="π§°")# For testing: Return this state instead of querying the environmentself.mock_state: dict[str, str] | None = {"open_file": "", "working_dir": ""}diff --git a/sweagent/utils/config.py b/sweagent/utils/config.pyindex 4d957f80..638d8cc9 100644--- a/sweagent/utils/config.py+++ b/sweagent/utils/config.py@@ -8,7 +8,7 @@ from dotenv import load_dotenvfrom sweagent import REPO_ROOTfrom sweagent.utils.log import get_logger-logger = get_logger("config", emoji="π§")+logger = get_logger("swea-config", emoji="π§")def _convert_path_to_abspath(path: Path | str) -> Path:diff --git a/sweagent/utils/log.py b/sweagent/utils/log.pyindex f29221a2..c154ad98 100644--- a/sweagent/utils/log.py+++ b/sweagent/utils/log.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport loggingimport os+import threadingfrom pathlib import PurePathfrom rich.logging import RichHandler@@ -14,21 +15,33 @@ logging.TRACE = 5 # type: ignorelogging.addLevelName(logging.TRACE, "TRACE") # type: ignore-def _interpret_level_from_env(level: str | None, *, default=logging.DEBUG) -> int:+def _interpret_level(level: int | str | None, *, default=logging.DEBUG) -> int:if not level:return default+ if isinstance(level, int):+ return levelif level.isnumeric():return int(level)return getattr(logging, level.upper())-_STREAM_LEVEL = _interpret_level_from_env(os.environ.get("SWE_AGENT_LOG_STREAM_LEVEL"))-_FILE_LEVEL = _interpret_level_from_env(os.environ.get("SWE_AGENT_LOG_FILE_LEVEL"), default=logging.TRACE) # type: ignore+_STREAM_LEVEL = _interpret_level(os.environ.get("SWE_AGENT_LOG_STREAM_LEVEL"))+_FILE_LEVEL = _interpret_level(os.environ.get("SWE_AGENT_LOG_FILE_LEVEL"), default=logging.TRACE) # type: ignore_INCLUDE_LOGGER_NAME_IN_STREAM_HANDLER = False+_THREAD_NAME_TO_LOG_SUFFIX: dict[str, str] = {}+"""Mapping from thread name to suffix to add to the logger name."""+++def register_thread_name(name: str) -> None:+ """Register a suffix to add to the logger name for the current thread."""+ thread_name = threading.current_thread().name+ _THREAD_NAME_TO_LOG_SUFFIX[thread_name] = name+class _RichHandlerWithEmoji(RichHandler):def __init__(self, emoji: str, *args, **kwargs):+ """Subclass of RichHandler that adds an emoji to the log message."""super().__init__(*args, **kwargs)if not emoji.endswith(" "):emoji += " "@@ -43,8 +56,11 @@ def get_logger(name: str, *, emoji: str = "") -> logging.Logger:"""Get logger. Use this instead of `logging.getLogger` to ensurethat the logger is set up with the correct handlers."""+ thread_name = threading.current_thread().name+ if thread_name != "MainThread":+ name = name + "-" + _THREAD_NAME_TO_LOG_SUFFIX.get(thread_name, thread_name)logger = logging.getLogger(name)- if name in _SET_UP_LOGGERS:+ if logger.hasHandlers():# Already set upreturn loggerhandler = _RichHandlerWithEmoji(@@ -58,27 +74,34 @@ def get_logger(name: str, *, emoji: str = "") -> logging.Logger:logger.propagate = False_SET_UP_LOGGERS.add(name)for handler in _ADDITIONAL_HANDLERS:- logger.addHandler(handler)+ if getattr(handler, "my_filter", "") in name:+ logger.addHandler(handler)if _INCLUDE_LOGGER_NAME_IN_STREAM_HANDLER:- add_logger_name_to_stream_handler(logger)+ _add_logger_name_to_stream_handler(logger)return logger-def add_file_handler(path: PurePath | str) -> None:+def add_file_handler(path: PurePath | str, *, filter: str = "", level: int | str = _FILE_LEVEL) -> None:"""Adds a file handler to all loggers that we have set upand all future loggers that will be set up with `get_logger`.++ Args:+ filter: If provided, only add the handler to loggers that contain the filter string."""handler = logging.FileHandler(path)- formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")handler.setFormatter(formatter)- handler.setLevel(_FILE_LEVEL)+ handler.setLevel(_interpret_level(level))for name in _SET_UP_LOGGERS:+ if filter and filter not in name:+ continuelogger = logging.getLogger(name)logger.addHandler(handler)+ handler.my_filter = filter # type: ignore_ADDITIONAL_HANDLERS.append(handler)-def add_logger_name_to_stream_handler(logger: logging.Logger) -> None:+def _add_logger_name_to_stream_handler(logger: logging.Logger) -> None:for handler in logger.handlers:if isinstance(handler, _RichHandlerWithEmoji):formatter = logging.Formatter("[%(name)s] %(message)s")@@ -86,10 +109,17 @@ def add_logger_name_to_stream_handler(logger: logging.Logger) -> None:def add_logger_names_to_stream_handlers() -> None:+ """Add the logger name to the stream handler for all loggers that we have set up."""global _INCLUDE_LOGGER_NAME_IN_STREAM_HANDLER_INCLUDE_LOGGER_NAME_IN_STREAM_HANDLER = Truefor logger in _SET_UP_LOGGERS:- add_logger_name_to_stream_handler(logging.getLogger(logger))+ _add_logger_name_to_stream_handler(logging.getLogger(logger))default_logger = get_logger("swe-agent")+++def set_default_stream_level(level: int) -> None:+ """Set the default stream level. Note: Can only be used to lower the level, not raise it."""+ global _STREAM_LEVEL+ _STREAM_LEVEL = level