Article
swe-agentautonomous-codingbug-fixingopen-sourcepythonprinceton-nlpagent-computer-interfacedocker
Fix Code Autonomously with Princeton's SWE-agent
Use SWE-agent, an open-source agent, to autonomously fix bugs and complete software engineering tasks. This guide shows how to install, configure, and run the agent on a real GitHub issue.
intermediate30 min5 steps
The play
- Install SWE-agent and DependenciesFirst, clone the official repository. SWE-agent uses Docker to create a safe, contained environment for code execution, so ensure Docker is running. Then, create a Python virtual environment and install the required packages.
- Configure Your LLM API KeySWE-agent requires a Large Language Model to function. Configure your API key as an environment variable. The agent is optimized for GPT-4 models, but also supports Anthropic's Claude models.
- Define the ProblemCreate a JSON file that describes the task for the agent. This file contains an `instance_id` (a unique identifier for the task) and a `problem_statement` detailing the bug or feature request.
- Run the AgentExecute the main script (`run.py`) to start the agent. Specify the model, the problem description file, and the instance ID. SWE-agent will then get to work, creating a trajectory of thoughts and actions to solve the problem.
- Review the Generated PatchOnce the agent completes its task, it will generate a patch file. You can find this file in the `trajectories/` directory. This patch contains the code changes proposed by SWE-agent to fix the issue.
Starter code
#!/bin/bash
# This script runs SWE-agent to fix a known bug in Django.
# Prerequisites:
# 1. Git, Python 3.10+, and Docker are installed.
# 2. You have cloned the SWE-agent repo and are in its root directory.
# 3. You have run `pip install -e .` in your virtual environment.
# Set your OpenAI API key (replace with your actual key)
export OPENAI_API_KEY="sk-replace-with-your-key"
if [ "$OPENAI_API_KEY" == "sk-replace-with-your-key" ]; then
echo "Error: Please replace 'sk-replace-with-your-key' with your actual OpenAI API key."
exit 1
fi
# Define the problem to solve from the SWE-bench benchmark
INSTANCE_ID="django__django-12989"
PROBLEM_STATEMENT="In Django, the QuerySet.explain() method fails when used on a query that involves a subquery. The goal is to make .explain() work correctly for such queries."
# Create a JSON file for the problem description
cat <<EOF > ./problem.json
{
"$INSTANCE_ID": {
"instance_id": "$INSTANCE_ID",
"problem_statement": "$PROBLEM_STATEMENT"
}
}
EOF
echo "Starting SWE-agent to fix Django issue: $INSTANCE_ID"
echo "This will take some time and consume API credits. The agent will work within a Docker container."
# Run SWE-agent
python run.py \
--model_name gpt-4-turbo-preview \
--data_path ./problem.json \
--instance_id "$INSTANCE_ID" \
--config_file ./config/default_from_swe-bench.yaml \
--skip_existing
echo "Run complete. Check the 'trajectories/' directory for the generated .patch file."