### Setup Agent Instance Source: https://swe-agent.com/latest/reference/agent Initializes the agent for a specific problem instance, including directory creation, tool installation, and history population. This method is typically invoked by the run process. ```python def setup( self, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig, output_dir: Path = Path("."), ) -> None: """Setup the agent for a new instance. This includes formatting the system message and adding demonstrations to the history. This method is called by `self.run`. """ output_dir.mkdir(parents=True, exist_ok=True) # apply template configuration to multimodal problem statements if hasattr(problem_statement, "type") and problem_statement.type == "swe_bench_multimodal": from sweagent.agent.problem_statement import SWEBenchMultimodalProblemStatement if isinstance(problem_statement, SWEBenchMultimodalProblemStatement): # apply the global disable_image_processing setting if it's not explicitly set if not problem_statement.disable_image_processing and self.templates.disable_image_processing: problem_statement.disable_image_processing = True self._problem_statement = problem_statement self._env = env iid = self._problem_statement.id self.logger.info("Setting up agent for instance %s", iid) # Save/reset some attributes self.traj_path = output_dir / (self._problem_statement.id + ".traj") self.logger.info("Trajectory will be saved to %s", self.traj_path) self._chook.on_tools_installation_started() self.tools.install(self._env) self._chook.on_setup_attempt() self.info = AgentInfo() self.info["swe_agent_hash"] = get_agent_commit_hash() self.info["swe_agent_version"] = __version__ self.info["swe_rex_version"] = get_rex_version() self.info["swe_rex_hash"] = get_rex_commit_hash() assert self._env is not None assert self._problem_statement is not None self._env.set_env_variables({"PROBLEM_STATEMENT": self._problem_statement.get_problem_statement_for_env()}) self.add_system_message_to_history() self.add_demonstrations_to_history() self.add_instance_template_to_history(state=self.tools.get_state(self._env)) self._chook.on_setup_done() ``` -------------------------------- ### Example Tool Configuration (filemap) Source: https://swe-agent.com/latest/config/tools An example configuration for a 'filemap' tool. It defines the tool's signature, a docstring explaining its purpose, and its required arguments. ```yaml tools: filemap: signature: "filemap " docstring: "Print the contents of a Python file, skipping lengthy function and method definitions." arguments: - name: file_path type: string description: The path to the file to be read required: true ``` -------------------------------- ### Start Environment Source: https://swe-agent.com/latest/reference/env Initializes the deployment, resets the environment, and executes post-startup commands. ```python start() -> None ``` ```python def start(self) -> None: """Start the environment and reset it to a clean state.""" self._init_deployment() self.reset() for command in self._post_startup_commands: self.communicate(command, check="raise", timeout=self.post_startup_command_timeout) ``` -------------------------------- ### SWEEnv.start Source: https://swe-agent.com/latest/reference/env Starts the environment and resets it to a clean state, executing any configured post-startup commands. ```APIDOC ## SWEEnv.start ### Description Starts the environment and resets it to a clean state, then executes post-startup commands. ``` -------------------------------- ### Test Docker Installation Source: https://swe-agent.com/latest/installation/tips Run this command to verify if Docker is installed and functioning correctly. ```bash docker run hello-world ``` -------------------------------- ### Set Installation Timeout Source: https://swe-agent.com/latest/reference/tools_config Sets the timeout in seconds for each installation command. ```python install_timeout: int = 300 ``` -------------------------------- ### SWEEnv.from_config Source: https://swe-agent.com/latest/reference/env Creates an environment instance from a configuration object, which is the recommended approach for standard setups. ```APIDOC ## SWEEnv.from_config ### Description Creates an environment instance from a configuration object. ### Parameters - **config** (EnvironmentConfig) - Required - Configuration object used to initialize the environment. ``` -------------------------------- ### Environment configuration file example Source: https://swe-agent.com/latest/usage/cl_tutorial Specifies the repository URL for the environment. ```yaml env: repo: github_url: https://github.com/SWE-agent/test-repo ``` -------------------------------- ### Open setup.py for inspection Source: https://swe-agent.com/latest/usage/trajectories This action opens the setup.py file to inspect its contents. This is often a precursor to understanding how to install or build the project locally. ```bash open setup.py ``` -------------------------------- ### Install SWE-agent with Development Dependencies Source: https://swe-agent.com/latest/dev/contribute Install the repository from source with the `[dev]` option for development purposes. This ensures all necessary tools for development are included. ```bash pip install -e '.[dev]' ``` -------------------------------- ### Define post-startup commands Source: https://swe-agent.com/latest/reference/env_config Commands to execute in the agent shell after setup. Each command is provided as a string. ```python post_startup_commands: list[str] = [] ``` -------------------------------- ### Custom Dockerfile for SWE-agent Source: https://swe-agent.com/latest/config/environments Define a custom Docker environment for SWE-agent. This example installs Python 3.11, swe-rex for faster startup, and flake8. Ensure to build this Dockerfile and specify the image when running the agent. ```docker FROM python:3.11.10-bullseye ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Etc/UTC WORKDIR / # Install swe-rex for faster startup RUN pip install pipx RUN pipx install swe-rex RUN pipx ensurepath ENV PATH="$PATH:/root/.local/bin/" # Install any extra dependencies RUN pip install flake8 SHELL ["/bin/bash", "-c"] ``` -------------------------------- ### Example Tool Structure Source: https://swe-agent.com/latest/usage/adding_custom_tools Illustrates the basic directory structure for a SWE-agent tool bundle, including configuration and executable scripts. ```text tools/submit/ ├── config.yaml └── bin/ └── submit ``` -------------------------------- ### Agent configuration file example Source: https://swe-agent.com/latest/usage/cl_tutorial Defines the model name and cost limits for the agent instance. ```yaml agent: model: name: gpt-4o per_instance_cost_limit: 2.00 ``` -------------------------------- ### Tool Installation Script Source: https://swe-agent.com/latest/usage/adding_custom_tools An optional bash script (`install.sh`) for a tool bundle that installs necessary dependencies, such as Python packages, using pip. ```bash #!/bin/bash # This script runs when the tool bundle is installed # Example: Install Python packages pip install cowsay pip install colorama echo "Morale boost tools installed! Ready to spread joy! 🎉" ``` -------------------------------- ### RetryAgent setup Method Source: https://swe-agent.com/latest/reference/agent Configures the agent for a new problem instance. ```python setup(env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig, output_dir: Path = Path('.')) -> None ``` ```python def setup( self, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig, output_dir: Path = Path(".") ) -> None: """Setup the retry agent for a new problem instance. This is mostly a bookkeeping step. """ self._total_instance_attempt_stats = InstanceStats() self._problem_statement = problem_statement self._traj_path = output_dir / (self._problem_statement.id + ".traj") self._env = env self._output_dir = output_dir self._rloop = get_retry_loop_from_config(self.config.retry_loop, problem_statement=problem_statement) ``` -------------------------------- ### Run method implementation Source: https://swe-agent.com/latest/reference/agent The full implementation of the run method, which manages the setup, the action-observation loop, and trajectory saving. ```python def run( self, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig, output_dir: Path = Path("."), ) -> AgentRunResult: """Run the agent on a problem instance. This method contains the main loop that repeatedly calls `self._step` until the problem is solved. Args: setup_args: Arguments to pass to the agent's setup method. env: The environment to run the agent on. traj_dir: Directory to save the trajectory to """ self.setup(env=env, problem_statement=problem_statement, output_dir=output_dir) # Run action/observation loop self._chook.on_run_start() step_output = StepOutput() while not step_output.done: step_output = self.step() self.save_trajectory() self._chook.on_run_done(trajectory=self.trajectory, info=self.info) self.logger.info("Trajectory saved to %s", self.traj_path) # Here we want to return the "global" information (e.g., submission should # be the best submission instead of the last one, etc.), so we get it from the traj file data = self.get_trajectory_data() return AgentRunResult(info=data["info"], trajectory=data["trajectory"]) ``` -------------------------------- ### Tool Configuration with Arguments Source: https://swe-agent.com/latest/usage/adding_custom_tools An example of a tool configuration that includes arguments, specifying their names, types, descriptions, and whether they are required. ```yaml tools: print_animal: signature: "print_animal [--size=]" docstring: "Prints ASCII art of the specified animal" arguments: - name: animal_type type: string description: "Type of animal to print (cat, dog, elephant)" required: true - name: size type: string description: "Size of the art (small, medium, large)" required: false ``` -------------------------------- ### Model Configuration for Vision Source: https://swe-agent.com/latest/usage/multimodal Example configuration for a vision-capable model. ```yaml # model_configs/claude-sonnet-4-20250514_mm.yaml model: name: claude-sonnet-4-20250514 # Vision capabilities automatically detected ``` -------------------------------- ### Install Pdbpp Debugger Source: https://swe-agent.com/latest/dev/contribute Install `pdbpp`, an enhanced Python debugger, for improved debugging capabilities. ```bash pip install pdbpp ``` -------------------------------- ### ThoughtActionParser Example Source: https://swe-agent.com/latest/reference/parsers Example of the expected model response format for the ThoughtActionParser. ```text Let's look at the files in the current directory. Action: ``` ls -l ``` ``` -------------------------------- ### Install Marshmallow Package Source: https://swe-agent.com/latest/usage/trajectories Installs the marshmallow package using pip. Ensure you are in a virtual environment for best practices. ```bash d: pluggy<2.0,>=1.4 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from pytest) (1.4.0) Requirement already satisfied: exceptiongroup>=1.0.0rc8 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from pytest) (1.2.0) Requirement already satisfied: tomli>=1 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from pytest) (2.0.1) Requirement already satisfied: cachetools>=5.3.2 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (5.3.3) Requirement already satisfied: chardet>=5.2 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (5.2.0) Requirement already satisfied: colorama>=0.4.6 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (0.4.6) Requirement already satisfied: filelock>=3.13.1 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (3.13.3) Requirement already satisfied: platformdirs>=4.1 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (4.2.0) Requirement already satisfied: pyproject-api>=1.6.1 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from tox) (1.6.1) Requirement already satisfied: setuptools in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from nodeenv>=0.11.1->pre-commit~=2.4) (68.2.2) Requirement already satisfied: distlib<1,>=0.3.7 in /root/miniconda3/envs/marshmallow-code__marshmallow__3.13/lib/python3.9/site-packages (from virtualenv>=20.10.0->pre-commit~=2.4) (0.3.8) Checking if build backend supports build_editable: started Checking if build backend supports build_editable: finished with status 'done' Building wheels for collected packages: marshmallow Building editable for marshmallow (pyproject.toml): started Building editable for marshmallow (pyproject.toml): finished with status 'done' Created wheel for marshmallow: filename=marshmallow-3.13.0-0.editable-py3-none-any.whl size=4534 sha256=fcca61a41cd2783d4a5b8471ebc48cf886d36f6c66a29cc9b02761fc174a024d Stored in directory: /tmp/pip-ephem-wheel-cache-h335xxo8/wheels/4d/da/d4/e230bf0a3f16cad5a83d235ac24a34b55178ddda181cb64dae Successfully built marshmallow Installing collected packages: marshmallow Attempting uninstall: marshmallow Found existing installation: marshmallow 3.13.0 Uninstalling marshmallow-3.13.0: Successfully uninstalled marshmallow-3.13.0 Successfully installed marshmallow-3.13.0 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv ``` -------------------------------- ### Full Example Trajectory (v0.7.0) Source: https://swe-agent.com/latest/usage/trajectories This is a complete example of a trajectory from an older version of SWE-agent (v0.7.0). It illustrates the 'environment', 'trajectory' array, and the structure of individual steps including 'action', 'observation', 'response', 'state', and 'thought'. Note that newer versions may have a different format, particularly regarding the 'query' field. ```json { "environment": "swe_main", "trajectory": [ { "action": "ls -F\n", "observation": "AUTHORS.rst\nCHANGELOG.rst\nCODE_OF_CONDUCT.md\nCONTRIBUTING.rst\nLICENSE\nMANIFEST.in\nNOTICE\nREADME.rst\nRELEASING.md\nazure-pipelines.yml\ndocs/\nexamples/\nperformance/\npyproject.toml\nsetup.cfg\nsetup.py\nsrc/\ntests/\ntox.ini\n", "response": "Let's list out some of the files in the repository to get an idea of the structure and contents. We can use the `ls -F` command to list the files in the current directory.\n```\nls -F\n```", "state": "{\"open_file\": \"n/a\", \"working_dir\": \"/marshmallow-code__marshmallow\"}\n", "thought": "Let's list out some of the files in the repository to get an idea of the structure and contents. We can use the `ls -F` command to list the files in the current directory.\n" }, { "action": "open setup.py\n", ``` -------------------------------- ### Install Pre-commit Hooks Source: https://swe-agent.com/latest/dev/contribute Set up `pre-commit` to automatically check for formatting and basic syntax errors before each commit. Run this command from the repository root. ```bash pre-commit install ``` -------------------------------- ### EditFormat Parser Example Source: https://swe-agent.com/latest/reference/parsers Example of the expected model response format for the EditFormat parser. ```python import os os.listdir() ``` -------------------------------- ### Verify SWE-agent Installation Source: https://swe-agent.com/latest/installation/source Run this command to check if SWE-agent is installed correctly and to view available commands. If 'sweagent' is not found, try 'python -m sweagent'. ```bash sweagent --help ``` -------------------------------- ### Run SWE-agent with post-startup commands Source: https://swe-agent.com/latest/usage/cl_tutorial Executes additional commands within the container before the agent starts. Use single quotes to wrap the list syntax to avoid shell interpretation issues. ```bash sweagent run \ --agent.model.name=claude-3-7-sonnet-latest \ --env.post_startup_commands='["pip install flake8"]' \ ... ``` -------------------------------- ### Install SWE-agent with Pip Source: https://swe-agent.com/latest/installation/source Install SWE-agent in editable mode using pip from the repository root. It's recommended to use virtual environments for dependency management. ```bash python -m pip install --upgrade pip && pip install --editable . ``` -------------------------------- ### Configure History Processors in YAML Source: https://swe-agent.com/latest/reference/history_processor_config Example configuration for setting up history processors within the agent configuration file. ```yaml agent: history_processors: - type: last_n_observations n: 5 ``` -------------------------------- ### Clone SWE-agent Repository Source: https://swe-agent.com/latest/installation/source Clone the SWE-agent repository to your local machine using Git. This is the first step for source installation. ```bash git clone https://github.com/SWE-agent/SWE-agent.git ``` -------------------------------- ### Web Inspector with Custom Port Source: https://swe-agent.com/latest/usage/inspector Starts the web-based inspector on a specified port. Useful if the default port 8000 is already in use. ```bash sweagent inspector --port 8001 ``` -------------------------------- ### SWEEnv.__init__ Source: https://swe-agent.com/latest/reference/env Initializes a new SWEEnv instance with the specified deployment, repository configuration, and startup commands. ```APIDOC ## SWEEnv.__init__ ### Description Initializes the environment where tasks are solved. ### Parameters - **deployment** (AbstractDeployment) - Required - SWE-ReX deployment instance - **repo** (Repo | RepoConfig | None) - Required - Repository configuration object - **post_startup_commands** (list[str]) - Required - Commands to execute before starting the agent - **post_startup_command_timeout** (int) - Optional - Timeout for startup commands (default: 500) - **hooks** (list[EnvHook] | None) - Optional - Environment hooks for custom functionality - **name** (str) - Optional - Name of the environment (default: 'main') ``` -------------------------------- ### Serve Documentation Locally Source: https://swe-agent.com/latest/dev/contribute Build and serve the project documentation locally using `mkdocs`. Access it via your browser on port 8000. ```bash # cd repo root mkdocs serve ``` -------------------------------- ### Initialize Repository for Coding Challenge Source: https://swe-agent.com/latest/usage/coding_challenges Create a new directory, initialize it as a Git repository, and set up a .gitignore file to exclude binary files. This prepares the environment for SWE-agent. ```bash mkdir empty git init touch main.py echo "*.pyc" > .gitignore # to avoid binary files in patches ``` -------------------------------- ### Define demonstrations Source: https://swe-agent.com/latest/reference/template_config Sets the paths to demonstration files. ```python demonstrations: list[Path] ``` -------------------------------- ### Install Package with Development Dependencies Source: https://swe-agent.com/latest/usage/trajectories Install the marshmallow package in editable mode with all development dependencies. This command is useful for setting up the project for local development and testing. ```bash pip install -e .[dev] ``` -------------------------------- ### Build and Run Custom Docker Environment Source: https://swe-agent.com/latest/config/environments Instructions for building the custom Docker image and running the SWE-agent with the specified image. ```bash docker build -f tiny.Dockerfile -t swe-agent-tiny . sweagent run --env.deployment.image swe-agent-tiny ... ``` -------------------------------- ### Run SWE-agent with configuration file Source: https://swe-agent.com/latest/usage/cl_tutorial Demonstrates running the agent using a YAML configuration file. ```bash sweagent run --config my_run.yaml ``` ```yaml agent: model: name: gpt-4o per_instance_cost_limit: 2.00 env: repo: github_url: https://github.com/SWE-agent/test-repo problem_statement: github_url: https://github.com/SWE-agent/test-repo/issues/1 ``` -------------------------------- ### Define demonstration_template Source: https://swe-agent.com/latest/reference/template_config Sets the demonstration template. ```python demonstration_template: str | None = None ``` -------------------------------- ### Marshmallow setup.py file content Source: https://swe-agent.com/latest/usage/trajectories This snippet displays the content of the setup.py file for the Marshmallow project. It includes package metadata, dependencies, and configuration details for distribution. ```python import re from setuptools import setup, find_packages EXTRAS_REQUIRE = { "tests": ["pytest", "pytz", "simplejson"], "lint": [ "mypy==0.910", "flake8==4.0.1", "flake8-bugbear==21.9.2", "pre-commit~=2.4", ], "docs": [ "sphinx==4.2.0", "sphinx-issues==1.2.0", "alabaster==0.7.12", "sphinx-version-warning==1.1.2", "autodocsumm==0.2.7", ], } EXTRAS_REQUIRE["dev"] = EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["lint"] + ["tox"] def find_version(fname): """Attempts to find the version number in the file names fname. Raises RuntimeError if not found. """ version = "" with open(fname) as fp: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fp: m = reg.match(line) if m: version = m.group(1) break if not version: raise RuntimeError("Cannot find version information") return version def read(fname): with open(fname) as fp: content = fp.read() return content setup( name="marshmallow", version=find_version("src/marshmallow/__init__.py"), description=( "A lightweight library for converting complex " "datatypes to and from native Python datatypes." ), long_description=read("README.rst"), author="Steven Loria", author_email="sloria1@gmail.com", url="https://github.com/marshmallow-code/marshmallow", packages=find_packages("src", exclude=("test*", "examples")), package_dir={"": "src"}, package_data={"marshmallow": ["py.typed"]}, include_package_data=True, extras_require=EXTRAS_REQUIRE, license="MIT", zip_safe=False, keywords=[ "serialization", "rest", "json", "api", "marshal", "marshalling", "deserialization", "validation", "schema", ], python_requires=">=3.6", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ], test_suite="tests", project_urls={ "Changelog": "https://marshmallow.readthedocs.io/en/latest/changelog.html", "Issues": "https://github.com/marshmallow-code/marshmallow/issues", "Funding": "https://opencollective.com/marshmallow", "Tidelift": "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi", # noqa }, ) ``` -------------------------------- ### Perform hard reset of environment Source: https://swe-agent.com/latest/reference/env Completely restarts the deployment by closing and starting the environment. ```python hard_reset() ``` ```python def hard_reset(self): """Resets the environment and deployment, i.e., completely restarts the deployment. """ self.close() self.start() ``` -------------------------------- ### Implement get_instance_configs Source: https://swe-agent.com/latest/reference/batch_instances Abstract method for retrieving a list of environment configurations. ```python get_instance_configs() -> list[EnvironmentConfig] ``` -------------------------------- ### Get repository reset commands Source: https://swe-agent.com/latest/reference/repo Retrieves the git reset commands to be executed after copying or environment reset. ```python def get_reset_commands(self) -> list[str]: """Issued after the copy operation or when the environment is reset.""" return _get_git_reset_commands(self.base_commit) ``` -------------------------------- ### Specify problem statement via CLI Source: https://swe-agent.com/latest/reference/problem_statements Examples of using the --problem-statement flag with different input types. ```bash --problem-statement.text="This is a problem statement" --problem-statement.type=text ``` ```bash --problem-statement.path=path/to/file.txt --problem-statement.type=text_file ``` ```bash --problem-statement.url=https://github.com/org/repo/issues/123 --problem-statement.type=github_issue ``` -------------------------------- ### Load Instances from File Source: https://swe-agent.com/latest/usage/batch_mode Run SWE-agent in batch mode by loading instances from a local file. Supports `.jsonl`, `.json`, and `.yaml` formats. The `instance_id` key is supported for compatibility, though `id` was used previously. ```bash sweagent run-batch \ --config config/default.yaml \ --agent.model.name gpt-4o \ --instances.type file \ --instances.path instances.yaml \ --instances.slice :3 \ --instances.shuffle=True ``` -------------------------------- ### InstancesFromFile get_instance_configs Method Source: https://swe-agent.com/latest/reference/batch_instances Retrieves the list of batch instance configurations. ```python get_instance_configs() -> list[BatchInstance] ``` -------------------------------- ### Get trajectory data Source: https://swe-agent.com/latest/reference/agent Retrieves the data saved in .traj files, optionally including the best attempt information. ```python get_trajectory_data(choose: bool) -> dict[str, Any] ``` ```python def get_trajectory_data(self, choose: bool) -> dict[str, Any]: """Get all data that we save in .traj files.""" assert self._rloop is not None data = { "attempts": self._attempt_data, } if choose: try: best_attempt_idx = self._rloop.get_best() except TotalCostLimitExceededError: raise except Exception as e: self.logger.critical(f"Error getting best attempt index: {e}. Setting to 0.", exc_info=True) best_attempt_idx = 0 data |= copy.deepcopy(self._attempt_data[best_attempt_idx]) # type: ignore data["info"]["best_attempt_idx"] = best_attempt_idx data["info"]["rloop_model_stats"] = self._rloop.review_model_stats.model_dump() # Overwrite model stats with total stats data["info"]["model_stats"] = self._total_instance_stats.model_dump() if isinstance(self._rloop, ChooserRetryLoop): data["info"]["chooser"] = ( self._rloop._chooser_output.model_dump() if self._rloop._chooser_output else {} ) return data ``` -------------------------------- ### Run SWE-agent with multiple configurations Source: https://swe-agent.com/latest/usage/cl_tutorial Execute the agent by chaining multiple configuration files and providing a problem statement text. ```bash sweagent run --config agent.yaml --config env.yaml \ --problem_statement.text="Hey, can you fix all the bugs?" ``` -------------------------------- ### ExpertInstancesFromFile get_instance_configs method Source: https://swe-agent.com/latest/reference/batch_instances Retrieves the list of batch instance configurations. ```python get_instance_configs() -> list[BatchInstance] ``` -------------------------------- ### Configure repository via CLI Source: https://swe-agent.com/latest/reference/repo Use these flags with the sweagent run command to specify the repository type and location. ```bash --env.repo.repo_name="testbed" --env.repo.type=preexisting ``` ```bash --env.repo.path=/path/to/repo --env.repo.type=local ``` -------------------------------- ### Initialize SWEEnv Source: https://swe-agent.com/latest/reference/env Constructor for the SWEEnv class, defining the environment configuration and initial state. ```python SWEEnv(*, deployment: AbstractDeployment, repo: Repo | RepoConfig | None, post_startup_commands: list[str], post_startup_command_timeout: int = 500, hooks: list[EnvHook] | None = None, name: str = 'main') ``` ```python def __init__( self, *, deployment: AbstractDeployment, repo: Repo | RepoConfig | None, post_startup_commands: list[str], post_startup_command_timeout: int = 500, hooks: list[EnvHook] | None = None, name: str = "main", ): """This class represents the environment in which we solve the tasks. Args: deployment: SWE-ReX deployment instance repo: Repository configuration object, or anything following the `Repo` protocol post_startup_commands: Commands to execute before starting the agent hooks: Environment hooks (used to inject custom functionality) Equivalent to calling `add_hook` for each hook after initialization. name: Name of the environment """ super().__init__() self.deployment = deployment self.repo = repo self._post_startup_commands = post_startup_commands self.post_startup_command_timeout = post_startup_command_timeout self.logger = get_logger("swea-env", emoji="🪴") self.name = name self.clean_multi_line_functions = lambda x: x self._chook = CombinedEnvHooks() for hook in hooks or []: self.add_hook(hook) ``` -------------------------------- ### Add Instance Template to History Source: https://swe-agent.com/latest/reference/agent Adds the instance template or demonstrations to the history, typically used at the start of a new attempt. ```python def add_instance_template_to_history(self, state: dict[str, str]) -> None: """Add observation to history, as well as the instance template or demonstrations if we're at the start of a new attempt. """ templates: list[str] = [] # Determine observation template based on what prior observation was assert self.history[-1]["role"] == "system" or self.history[-1].get("is_demo", False) # Show instance template if prev. obs. was initial system message templates = [self.templates.instance_template] if self.templates.strategy_template is not None: templates.append(self.templates.strategy_template) self._add_templated_messages_to_history(templates, **state) # type: ignore ``` -------------------------------- ### Get model requery history Source: https://swe-agent.com/latest/reference/agent Queries the model to correct errors by adding temporary history based on an error template. ```python def get_model_requery_history( self, error_template: str, *, output: str, **kwargs: str | int | float | bool | None ) -> list[dict[str, str]]: """Ask the model to correct after a hitting one of the following errors: 1. Malformatted output (could not parse action) 2. Blocked action (command is on the blocklist) 3. Bash command syntax error At the time this function is called, the proposed action and observation are not part of the history yet. This function adds temporary history based on the error template and queries the model. If the model is able to correct itself, the records of the mistakes will not be part of the history (but they are saved in the trajectory). Args: error_template: error template output: model output **kwargs: keyword arguments to be passed to the error template Returns: model output after requery """ format_dict = {**kwargs, **self._get_format_dict()} error_template = Template(error_template).render(**format_dict) self.logger.warning(f"{error_template}") return self.messages + [ {"role": "assistant", "content": output, "agent": self.name, "message_type": "assistant"}, {"role": "user", "content": error_template, "agent": self.name, "message_type": "user"}, ] ``` -------------------------------- ### Convert SimpleBatchInstance to full instance Source: https://swe-agent.com/latest/reference/batch_instances Merges deployment options into a SimpleBatchInstance to create a full BatchInstance. ```python to_full_batch_instance(deployment: DeploymentConfig) -> BatchInstance ``` -------------------------------- ### Initialize Repository Configuration Source: https://swe-agent.com/latest/reference/repo Creates a RepoConfig object based on a local path, GitHub URL, or existing repository name. Automatically detects the type if set to 'auto'. ```python def repo_from_simplified_input( *, input: str, base_commit: str = "HEAD", type: Literal["local", "github", "preexisting", "auto"] = "auto" ) -> RepoConfig: """Get repo config from a simplified input. Args: input: Local path or GitHub URL type: The type of repo. Set to "auto" to automatically detect the type (does not work for preexisting repos). """ if type == "local": return LocalRepoConfig(path=Path(input), base_commit=base_commit) if type == "github": return GithubRepoConfig(github_url=input, base_commit=base_commit) if type == "preexisting": return PreExistingRepoConfig(repo_name=input, base_commit=base_commit) if type == "auto": if input.startswith("https://github.com/"): return GithubRepoConfig(github_url=input, base_commit=base_commit) else: return LocalRepoConfig(path=Path(input), base_commit=base_commit) msg = f"Unknown repo type: {type}" raise ValueError(msg) ``` -------------------------------- ### Get Trajectory Data Source: https://swe-agent.com/latest/reference/agent Retrieves the full trajectory data, including history and environment state, formatted for .traj file storage. ```python def get_trajectory_data(self) -> dict[str, Any]: """Get all data that we save in .traj files.""" assert self._env is not None # The deepcopy here is important because else the # data["info"]["model_stats"] update will create havoc! attempt_data = copy.deepcopy( { "trajectory": self.trajectory, "history": self.history, "info": self.info, } ) attempt_data["replay_config"] = self.replay_config.model_dump_json() if self.replay_config is not None else None attempt_data["environment"] = self._env.name return attempt_data ``` -------------------------------- ### Run SWE-agent on Multimodal SWE-bench Issues Source: https://swe-agent.com/latest/usage/batch_mode Process a batch of multimodal SWE-bench issues that include images. This requires a specific configuration file and uses a model capable of handling multimodal input. Images are automatically downloaded, converted to base64, and provided as context to the AI. ```bash sweagent run-batch \ --config config/default_mm_with_images.yaml \ --agent.model.name claude-sonnet-4-20250514 \ --agent.model.per_instance_cost_limit 2.00 \ --instances.type swe_bench \ --instances.subset multimodal \ --instances.split dev \ --instances.slice :3 \ --instances.shuffle=True ``` -------------------------------- ### Set Command Documentation Source: https://swe-agent.com/latest/reference/tools_config Provides documentation generated from loaded tool bundles. ```python command_docs: str = None ``` -------------------------------- ### Tool Bundle Directory Structure Source: https://swe-agent.com/latest/config/tools This is the standard directory structure for a tool bundle in SWE-agent. It includes executables, configuration, installation scripts, and project metadata. ```bash bundle/ ├── bin/ │ └── │ └── ├── config.yaml ├── install.sh ├── README.md └── pyproject.toml ``` -------------------------------- ### Create Tool Directory Source: https://swe-agent.com/latest/usage/adding_custom_tools Command to create the necessary directory structure for a new custom tool bundle. ```bash mkdir -p tools/morale_boost/bin ``` -------------------------------- ### Specify Repository via Command Line Source: https://swe-agent.com/latest/usage/cl_tutorial Use these flags to define the target repository for the agent using either a GitHub URL or a local file path. ```bash --env.repo.github_url=https://github.com/SWE-agent/test-repo --env.repo.path=/path/to/repo ``` -------------------------------- ### Example Union Type Error Command Source: https://swe-agent.com/latest/usage/cl_tutorial Demonstrates a command execution that triggers a union type error due to conflicting or missing configuration options. ```bash sweagent run --problem_statement.path="test" --problem_statement.github_url="asdf" ``` -------------------------------- ### SWE-agent Patch Application Instructions Source: https://swe-agent.com/latest/usage/coding_challenges Instructions on how to inspect and apply a patch file generated by SWE-agent. This includes commands to view the patch content and apply it to a local repository. ```bash # The patch has been saved to your local filesystem at: PATCH_FILE_PATH='/Users/fuchur/Documents/24/git_sync/SWE-agent/trajectories/fuchur/azure-gpt4__problem__coding_challenge__t-0.00__p-0 5__c-3.00__install-1/patches/26d111.patch' # Inspect it: cat "${PATCH_FILE_PATH}" # Apply it to a local repository: cd git apply "${PATCH_FILE_PATH}" ``` -------------------------------- ### Run agent on problem instance Source: https://swe-agent.com/latest/reference/agent Executes the main agent loop to solve a problem instance. This method handles environment setup, step iteration, and trajectory saving. ```python def run( self, env: SWEEnv, problem_statement: ProblemStatement | ProblemStatementConfig, output_dir: Path = Path("."), ) -> AgentRunResult: """Run the agent on a problem instance. This method contains the main loop that repeatedly calls `self._step` until the problem is solved. Args: env: The environment to run the agent on. problem_statement: The problem statement to run the agent on. output_dir: Directory to save the trajectory to """ output_dir.mkdir(parents=True, exist_ok=True) self.setup(env=env, problem_statement=problem_statement, output_dir=output_dir) assert self._rloop is not None # Run action/observation loop self._chook.on_run_start() step_output = StepOutput() self._setup_agent() assert self._agent is not None while not step_output.done: step_output = self.step() self.save_trajectory(choose=False) if step_output.done: self._rloop.on_submit( ReviewSubmission( trajectory=self._agent.trajectory, info=self._agent.info, model_stats=self._agent.model.stats, ) ) if isinstance(self._rloop, ScoreRetryLoop): self._agent.info["review"] = self._rloop.reviews[-1].model_dump() # type: ignore self._finalize_agent_run() self.save_trajectory(choose=False) if self._rloop.retry(): assert self._env is not None self._next_attempt() step_output.done = False self.save_trajectory(choose=True) # call again after we finalized self._chook.on_run_done(trajectory=self._agent.trajectory, info=self._agent.info) self.logger.info("Trajectory saved to %s", self._traj_path) # Here we want to return the "global" information (e.g., submission should # be the best submission instead of the last one, etc.), so we get it from the traj file data = self.get_trajectory_data(choose=True) return AgentRunResult(info=data["info"], trajectory=data["trajectory"]) ``` -------------------------------- ### Load Expert Instances from File Source: https://swe-agent.com/latest/usage/batch_mode Run SWE-agent in batch mode using expert-defined instances loaded from a YAML file. This allows for detailed configuration of environment, problem statement, and repository. ```bash sweagent run-batch \ ... \ --instances.type expert_file \ --instances.path instances.yaml ``` -------------------------------- ### Accessing and Setting Registry Variables in Python Source: https://swe-agent.com/latest/usage/adding_custom_tools Utilize the `registry` object in Python tools to get values (with fallbacks) and set new values. Data stored in the registry persists between tool invocations. ```python #!/usr/bin/env python3 from registry import registry def main(): # Get a simple value with a fallback setting = registry.get("MY_CUSTOM_SETTING", "default value") print(f"Setting: {setting}") # Get a list of messages messages = registry.get("MORALE_MESSAGES", []) if messages: import random message = random.choice(messages) print(f"🐱 {message}") # Set a value (persists across tool calls) registry["LAST_MORALE_BOOST"] = "2024-01-15 10:30:00" print("Morale boosted! 🚀") if __name__ == "__main__": main() ``` -------------------------------- ### Run SWE-agent on Multiple SWE-bench Issues Source: https://swe-agent.com/latest/usage/batch_mode Execute SWE-agent on a batch of SWE-bench issues. This command downloads issues automatically and processes them using specified configurations. Ensure Docker is installed for sandbox execution. ```bash sweagent run-batch \ --config config/default.yaml \ --agent.model.name gpt-4o \ --agent.model.per_instance_cost_limit 2.00 \ --instances.type swe_bench \ --instances.subset lite \ --instances.split dev \ --instances.slice :3 \ --instances.shuffle=True ``` -------------------------------- ### Create Environment from Config Source: https://swe-agent.com/latest/reference/env Factory method to instantiate SWEEnv from an EnvironmentConfig object. ```python from_config(config: EnvironmentConfig) -> Self ``` ```python @classmethod def from_config(cls, config: EnvironmentConfig) -> Self: """Create an environment instance from a configuration object. This is the recommended way to create an environment instance, unless you need more flexibility. """ # Always copy config to avoid shared state between different instances config = config.model_copy(deep=True) return cls( deployment=get_deployment(config.deployment), repo=config.repo, post_startup_commands=config.post_startup_commands, post_startup_command_timeout=config.post_startup_command_timeout, name=config.name, ) ``` -------------------------------- ### Basic Tool Configuration Source: https://swe-agent.com/latest/usage/adding_custom_tools Defines a simple tool named 'print_cat' with no arguments, suitable for SWE-agent integration. Includes its signature and a docstring for AI guidance. ```yaml tools: print_cat: signature: "print_cat" docstring: "Prints an ASCII art cat for morale boost. Use when you need encouragement!" arguments: [] ``` -------------------------------- ### Run Batch with Multimodal Configuration Source: https://swe-agent.com/latest/usage/multimodal Execute a batch run using the pre-configured multimodal settings. ```bash sweagent run-batch \ --config config/default_mm_with_images.yaml \ --instances.type swe_bench \ --instances.subset multimodal \ --instances.split dev ``` -------------------------------- ### Load Instances from Hugging Face Source: https://swe-agent.com/latest/usage/batch_mode Utilize SWE-agent in batch mode by loading instances directly from a Hugging Face dataset. Specify the dataset name, split, and slice as needed. ```bash sweagent run-batch \ ... \ --instances.type huggingface \ --instances.dataset_name "your_username/your_dataset" \ --instances.split "dev" \ --instances.slice :3 \ --instances.shuffle=True ``` -------------------------------- ### Configure Fallbacks and Threading Source: https://swe-agent.com/latest/reference/model_config Sets up model fallbacks and API key selection logic based on threads. ```python fallbacks: list[dict[str, Any]] = [] ``` ```python choose_api_key_by_thread: bool = True ``` -------------------------------- ### Alternative Verification Command Source: https://swe-agent.com/latest/installation/source Use this command if the primary 'sweagent --help' command is not found. This can help resolve path issues. ```bash python -m sweagent ``` -------------------------------- ### Define Reset Commands Source: https://swe-agent.com/latest/reference/tools_config Lists commands used to reset the environment state upon startup or reset. ```python reset_commands: list[str | list[str]] = [] ``` -------------------------------- ### Set post-startup command timeout Source: https://swe-agent.com/latest/reference/env_config Defines the timeout in seconds applied individually to each command in post_startup_commands. ```python post_startup_command_timeout: int = 500 ``` -------------------------------- ### DefaultAgent.__init__ Source: https://swe-agent.com/latest/reference/agent Initializes a new instance of the DefaultAgent. The agent handles the behavior of the model and how it interacts with the environment. ```APIDOC ## DefaultAgent.__init__ ### Description Initializes the DefaultAgent with necessary configurations, tools, and model instances. ### Signature DefaultAgent(*, templates: TemplateConfig, tools: ToolHandler, history_processors: list[HistoryProcessor], model: AbstractModel, max_requeries: int = 3, name: str = 'main', _catch_errors: bool = True, _always_require_zero_exit_code: bool = False, action_sampler_config: ActionSamplerConfig | None = None) ``` -------------------------------- ### Create Reproduction Script Source: https://swe-agent.com/latest/usage/trajectories Create a new Python file named 'reproduce.py' to house the code for reproducing the issue. This is a preparatory step before adding the specific reproduction logic. ```bash create reproduce.py ``` -------------------------------- ### Update Formatting Configuration Files Source: https://swe-agent.com/latest/dev/formatting_conflicts Checkout the latest `.pre-commit-config.yaml` and `pyproject.toml` files from the main branch of the upstream repository. This ensures your local environment uses the new formatting tools. ```bash git checkout upstream/main -- .pre-commit-config.yaml pyproject.toml git commit -m "Update formatting instructions" --no-verify ``` -------------------------------- ### handle_action Source: https://swe-agent.com/latest/reference/agent Runs an action proposed by the agent in the environment and returns the corresponding output. ```APIDOC ## handle_action(step: StepOutput) -> StepOutput ### Description Runs an action proposed by the agent in the environment and returns the corresponding output. ### Parameters - **step** (StepOutput) - Required - The step containing the action to run and model output for error handling. ### Returns - **action_execution_output** (StepOutput) - The result of the action execution. ``` -------------------------------- ### Define instance_template Source: https://swe-agent.com/latest/reference/template_config Sets the instance prompt template. ```python instance_template: str = '' ``` -------------------------------- ### Convert SWE-bench instances Source: https://swe-agent.com/latest/reference/batch_instances Class method to convert SWE-bench dataset instances to SimpleBatchInstance format. ```python from_swe_bench(instance: dict[str, Any]) -> Self ``` -------------------------------- ### Define deployment configuration Source: https://swe-agent.com/latest/reference/env_config Specifies the deployment options for the environment. ```python deployment: DeploymentConfig ``` -------------------------------- ### Submit Code Source: https://swe-agent.com/latest/usage/coding_challenges Adds all changes, creates a patch file, and prints it. This function assumes a git repository and a patch file named 'test.patch'. ```shell submit() { cd $ROOT # Check if the patch file exists and is non-empty if [ -s "/root/test.patch" ]; then # Apply the patch in reverse git apply -R < "/root/test.patch" fi git add -A git diff --cached > model.patch echo "<>" } ```