SWE-agent 源码解析:从实例加载到补丁提交的完整链路
对象:SWE-agent
v1.1.0(源码提交3ea751c)目录:
/home/username/swe_agent_bench/SWE-agent目标:从源码角度讲清三件事------
- SWE-agent 的代码结构是怎么组织的;
- 一次任务从加载实例到产出补丁的完整运行原理;
- 如何用 SWE-bench 官方 harness 评估 Agent 的性能,以及本仓库实测结果如何解读。
本文只基于仓库中的实际源码与本地实测数据编写。文中的 文件:行号 均可在当前源码中直接定位。
目录
- [1. 项目定位与整体架构](#1. 项目定位与整体架构)
- [2. 源码目录与模块职责](#2. 源码目录与模块职责)
- [3. 配置系统](#3. 配置系统)
- [4. 实例加载:从 SWE-bench 数据集到 BatchInstance](#4. 实例加载:从 SWE-bench 数据集到 BatchInstance)
- [5. 运行环境:SWEEnv、SWE-ReX 与 ACI 工具](#5. 运行环境:SWEEnv、SWE-ReX 与 ACI 工具)
- [6. Agent 主循环](#6. Agent 主循环)
- [7. 提交、补丁导出与预测文件](#7. 提交、补丁导出与预测文件)
- [8. 批量运行、并发与断点续跑](#8. 批量运行、并发与断点续跑)
- [9. 用 SWE-bench 评估 Agent 性能](#9. 用 SWE-bench 评估 Agent 性能)
- [10. 扩展点:怎样改造成自己的 Agent](#10. 扩展点:怎样改造成自己的 Agent)
- [11. 关键代码阅读路线](#11. 关键代码阅读路线)
- [12. 已知坑与版本注意事项](#12. 已知坑与版本注意事项)
1. 项目定位与整体架构
1.1 一句话概括
SWE-agent 是一个让语言模型在真实代码仓库里自主改代码的 Agent 运行时:
- 输入:一个仓库(通常已放在容器里)+ 一段问题描述(GitHub issue / PR 描述);
- 过程:模型不断输出「思考 + 一条命令」,SWE-agent 在容器的 bash 会话里执行命令,把输出作为观察结果回填给模型;
- 输出:仓库的
git diff补丁、逐步轨迹(.traj)、日志、SWE-bench 格式的预测文件(.pred/preds.json)。
它本身不负责判分 。判分由 SWE-bench 官方 harness 或 sb-cli 完成;SWE-agent 只负责把补丁产出来。
1.2 分层架构
text
┌─────────────────────────────────────────────────────────────────────┐
│ CLI 层:sweagent run / run-batch / inspect / merge-preds ... │
│ sweagent/run/run.py → run_single.py / run_batch.py │
├─────────────────────────────────────────────────────────────────────┤
│ 编排层:RunSingle / RunBatch │
│ - 解析配置、加载实例、并发调度、断点续跑、汇总 preds.json │
│ - RunHook 机制(保存补丁、提交评测、状态展示) │
├─────────────────────────────────────────────────────────────────────┤
│ Agent 层:AbstractAgent → DefaultAgent / RetryAgent / ShellAgent │
│ - 提示词模板、历史管理、模型查询、动作解析、错误重试、提交处理 │
│ - Model 层:LiteLLMModel / HumanModel / ReplayModel │
├─────────────────────────────────────────────────────────────────────┤
│ 环境层:SWEEnv │
│ - 仓库准备与 reset、命令执行、文件读写、环境变量 │
│ - 真正的容器/远端执行由 SWE-ReX Deployment + Runtime 完成 │
├─────────────────────────────────────────────────────────────────────┤
│ 工具层:ToolHandler + tools/* bundle(ACI) │
│ - bash、submit、str_replace_editor、filemap、review 等命令 │
│ - 以「命令 + 文档」的形式暴露给模型,而不是直接暴露 Python API │
├─────────────────────────────────────────────────────────────────────┤
│ 执行后端:SWE-ReX(本地 Docker、Modal、Fargate、本地进程等) │
└─────────────────────────────────────────────────────────────────────┘
1.3 与 SWE-ReX 的关系
sweagent/environment/swe_env.py 中的 SWEEnv 是一个很薄的封装:
SWEEnv.start()负责启动 deployment、创建 bash session、重置仓库、执行 startup 命令;SWEEnv.communicate()把一条命令交给deployment.runtime.run_in_session(BashAction(...));- 具体的容器创建、镜像拉取、远端连接,全部由 SWE-ReX 的
Deployment/Runtime实现。
因此 SWE-agent 可以做到「同一套 Agent 代码,跑在本地 Docker 或云端的 Modal/Fargate 上」,差别只在 DeploymentConfig。
1.4 一次 run-batch 的宏观时序
text
用户命令
│
├─ run.py 解析子命令 → RunBatchConfig
├─ BasicCLI 读取 YAML + CLI 覆盖 → pydantic 配置对象
├─ Instances.get_instance_configs()
│ └─ HuggingFace 数据集 → SimpleBatchInstance → BatchInstance
├─ RunBatch.main()
│ ├─ 单线程:for instance in instances
│ └─ 多线程:ThreadPoolExecutor(max_workers)
│ └─ run_instance()
│ ├─ 创建 Agent(每个实例一个)
│ ├─ SWEEnv.from_config().start()
│ │ ├─ SWE-ReX 启动容器
│ │ ├─ 创建 bash session
│ │ └─ 校验/重置 /testbed
│ ├─ agent.run()
│ │ ├─ setup():ToolHandler.install() 上传并安装工具
│ │ └─ while not done: step() 模型↔环境循环
│ ├─ 保存 .traj / .pred / .patch
│ └─ env.close()
├─ merge_predictions() → preds.json
└─ 可选:SweBenchEvaluate hook → sb-cli
2. 源码目录与模块职责
2.1 规模
sweagent/下共 60 个.py文件 ,约 11433 行 (不含tools/下的 bash/python 工具脚本);- 核心复杂度集中在
agent/agents.py(1294 行)、agent/models.py(903 行)、tools/parsing.py(621 行)、agent/reviewer.py(664 行)。
2.2 目录树(省略 __pycache__)
text
SWE-agent/
├── sweagent/
│ ├── __init__.py # 版本号、路径常量、日志/HF 告警降级
│ ├── __main__.py # python -m sweagent
│ ├── types.py # StepOutput / Trajectory / History / AgentRunResult
│ ├── exceptions.py # 各类错误类型
│ ├── agent/
│ │ ├── agents.py # ★ Agent 主循环、配置、错误处理、提交
│ │ ├── models.py # ★ LiteLLM 封装、成本/调用次数限制、重试
│ │ ├── problem_statement.py # 问题描述对象(文本/GitHub issue/多模态)
│ │ ├── history_processors.py# 历史裁剪、cache_control、正则清理
│ │ ├── action_sampler.py # 多采样选动作(ask_colleagues 等)
│ │ ├── reviewer.py # RetryAgent 的评审/打分/选择循环
│ │ ├── extra/shell_agent.py # shell 型 Agent
│ │ └── hooks/ # Agent 生命周期钩子
│ ├── environment/
│ │ ├── swe_env.py # ★ 环境封装(SWE-ReX)
│ │ ├── repo.py # 仓库来源:preexisting/local/github/swesmith
│ │ └── hooks/ # 环境生命周期钩子
│ ├── tools/
│ │ ├── tools.py # ★ ToolConfig / ToolHandler
│ │ ├── commands.py # Command / Argument / BASH_COMMAND
│ │ ├── parsing.py # ★ 输出解析器(function_calling 等)
│ │ ├── bundle.py # 工具 bundle 的加载与校验
│ │ └── utils.py # 多行命令保护、命令文档生成
│ ├── run/
│ │ ├── run.py # CLI 总入口与子命令分发
│ │ ├── run_single.py # 单实例运行
│ │ ├── run_batch.py # ★ 批量运行
│ │ ├── batch_instances.py # ★ 实例加载(含 SWE-bench)
│ │ ├── common.py # BasicCLI、save_predictions
│ │ ├── merge_predictions.py # .pred → preds.json
│ │ ├── hooks/apply_patch.py # 保存补丁
│ │ ├── hooks/swe_bench_evaluate.py # sb-cli 评测
│ │ └── _progress.py # rich 进度条/状态表
│ ├── inspector/ # Web 轨迹查看器
│ └── utils/ # 日志、补丁格式化、GitHub、序列化
├── config/ # 默认配置与论文复现配置
├── tools/ # ACI 工具 bundle(bash 脚本 + config.yaml)
└── docs/ # 官方文档源文件
2.3 模块职责表
| 模块 | 关键类/函数 | 职责 |
|---|---|---|
run/run.py |
main() |
子命令分发:run、run-batch、inspect、merge-preds 等 |
run/common.py |
BasicCLI、save_predictions() |
YAML + CLI 合并成 pydantic 配置;写 .pred |
run/run_single.py |
RunSingleConfig、RunSingle |
单实例编排:建环境 → 跑 Agent → 存补丁 |
run/run_batch.py |
RunBatchConfig、RunBatch |
批量编排、并发、跳过已完成实例、合并预测 |
run/batch_instances.py |
SWEBenchInstances、SimpleBatchInstance |
数据集加载、镜像名推导、BatchInstance 组装 |
agent/agents.py |
DefaultAgent、RetryAgent |
提示词渲染、step 循环、错误处理、提交 |
agent/models.py |
LiteLLMModel、get_model() |
调模型、统计 token/成本、限流与重试 |
tools/tools.py |
ToolConfig、ToolHandler |
工具安装、命令文档、动作解析、blocklist、state |
tools/parsing.py |
FunctionCallingParser 等 |
把模型输出解析成 (thought, action) |
tools/bundle.py |
Bundle |
读取 tools/*/config.yaml,生成 Command |
environment/swe_env.py |
SWEEnv |
启动/重置环境、执行命令、读写文件 |
environment/repo.py |
PreExistingRepoConfig 等 |
仓库来源与 reset 命令 |
types.py |
StepOutput、AgentRunResult |
模块间数据契约 |
run/hooks/* |
SaveApplyPatchHook、SweBenchEvaluate |
运行过程扩展点 |
2.4 数据流中的四种核心对象
text
BatchInstance
├─ env: EnvironmentConfig(deployment + repo + startup commands)
└─ problem_statement: ProblemStatementConfig(文本 + id + extra_fields)
│ 交给
▼
StepOutput(一步)
query / thought / action / output / observation
execution_time / done / exit_status / submission / state / tool_calls
│ 累积成
▼
Trajectory = list[TrajectoryStep] # 执行轨迹,用于分析和 replay
History = list[HistoryItem] # 真正发给模型的消息序列
│ 最终产出
▼
AgentRunResult
├─ info: exit_status / submission / model_stats / edited_files*
└─ trajectory
3. 配置系统
3.1 两套机制拼在一起
SWE-agent 的配置不是简单的 argparse,而是:
- pydantic-settings :所有配置类都继承
BaseSettings/BaseModel,字段即配置项,自带类型校验; BasicCLI(sweagent/run/common.py) :先用argparse单独接住--config、--help、--print_config、--no_config_file,再把剩余的--a.b.c value交给CliApp.run()。
关键代码在 run/common.py:187 的 BasicCLI.get_config():
text
Step 1 argparse 只解析 --config / -h / --help_option / --no_config_file / --print_config
Step 2 如果没有 --config,且 default_settings=True,就自动加载 config/default.yaml
Step 3 用 yaml.safe_load 读取所有 --config,按顺序 merge_nested_dicts
Step 4 CliApp.run(<ConfigType>, remaining_args, **config_merged)
------ 同时把 YAML 和 CLI 参数注入 pydantic
因此优先级是:
text
命令行参数 > --config 指定的 YAML(后加载的覆盖先加载的) > config/default.yaml > 字段默认值
--print_config 会打印最终合并结果后退出,是排查配置问题最快的办法。
3.2 RunBatchConfig 字段
定义在 sweagent/run/run_batch.py:75:
| 字段 | 默认值 | 说明 |
|---|---|---|
instances |
必填 | 实例来源,判别字段 type:swe_bench / huggingface / file / expert_file / swesmith |
agent |
必填 | Agent 配置,判别字段 type:default / retry / shell |
output_dir |
DEFAULT |
为 DEFAULT 时按 trajectories/<用户>/<config>__<model>___<实例源>[__suffix] 自动生成 |
suffix |
"" |
自动目录名的后缀 |
raise_exceptions |
False |
出错时是抛出还是跳过该实例 |
redo_existing |
False |
是否重跑已有 .traj 的实例 |
num_workers |
1 |
并发线程数(注意是线程,不是进程) |
random_delay_multiplier |
0.3 |
启动时随机延迟,避免多容器同时启动打爆机器 |
progress_bar |
True |
是否显示 rich 进度条 |
env_var_path |
None |
额外的 .env 文件 |
模型配置 GenericAPIModelConfig(agent/models.py:66)里最常用的字段:
| 字段 | 说明 |
|---|---|
name |
litellm 模型名,如 openai/deepseek-flash、anthropic/claude-... |
api_base |
OpenAI 兼容接口地址 |
api_key |
支持 $ENV_VAR 写法;支持 key1:::key2 多 key |
per_instance_cost_limit |
单实例成本上限,0 表示关闭 |
total_cost_limit |
全局成本上限,0 表示关闭 |
per_instance_call_limit |
单实例 API 调用次数上限,0 表示关闭 |
max_input_tokens |
上下文上限,0 表示不检查 |
temperature / top_p |
采样参数 |
completion_kwargs |
原样透传给 litellm 的额外参数 |
retry |
RetryConfig:重试次数、最小/最大等待 |
convert_system_to_user |
某些模型不支持 system 消息时转成 user |
api_key 的处理逻辑在 agent/models.py:155 的 get_api_keys():
- 以
$开头 → 读取对应环境变量; - 含
:::→ 拆成多个 key; choose_api_key_by_thread=True时按线程轮转,适合多 worker 并发;- 否则随机挑一个。
3.3 config/default.yaml 解剖
默认配置只有 69 行,但信息量很大:
yaml
agent:
templates:
system_template: "You are a helpful assistant ..."
instance_template: |-
<uploaded_files>{{working_dir}}</uploaded_files>
... {{problem_statement}} ...
next_step_template: |-
OBSERVATION:
{{observation}}
next_step_no_output_template: ...
tools:
env_variables: {PAGER: cat, MANPAGER: cat, ...}
bundles:
- path: tools/registry
- path: tools/edit_anthropic
- path: tools/review_on_submit_m
registry_variables:
USE_FILEMAP: 'true'
SUBMIT_REVIEW_MESSAGES: [...]
enable_bash_tool: true
parse_function:
type: function_calling
history_processors:
- type: cache_control
last_n_messages: 2
它决定了:
- 模型看到的第一条消息长什么样(
instance_template); - 每一步看到的环境输出长什么样(
next_step_template); - 暴露哪些工具(
bundles); - 用哪种解析器把模型输出变成动作(
function_calling); - 历史如何裁剪(
cache_control处理器)。
注意:default.yaml 里没有 agent.model ,模型必须通过 CLI 或另一个 YAML 提供。若完全不给,pydantic 会因 DefaultAgentConfig.model 必填而报错。
3.4 .env 加载
run_batch.from_config() 第一行就是 load_environment_variables(config.env_var_path)(run_batch.py:197)。查找顺序:
- 显式传入的
env_var_path; - 当前工作目录的
.env; - 仓库根目录的
.env。
这也是本仓库 setup_env.sh 之外的另一条密钥注入路径。实际跑分时我们用的是 setup_env.sh 导出环境变量 + --agent.model.api_key '$DEEPSEEK_API_KEY'。
3.5 输出目录与配置快照
RunBatch.from_config() 会做三件事:
config.set_default_output_dir():自动生成输出目录;mkdir -p;- 把完整配置写到
run_batch.config.yaml。
每个实例目录里还会写一份 <instance_id>.config.yaml(run_batch.py:343),内容是 RunSingleConfig 的序列化。这份快照非常有用:以后复现某个实例时,直接看它当时的 agent/env/problem_statement 配置即可,不依赖记忆。
4. 实例加载:从 SWE-bench 数据集到 BatchInstance
4.1 五种实例源
batch_instances.py 定义了统一的抽象:
python
class AbstractInstanceSource(ABC):
@abstractmethod
def get_instance_configs(self) -> list[BatchInstance]: ...
具体实现与判别字段:
type |
类 | 用途 |
|---|---|---|
swe_bench |
SWEBenchInstances |
直接读 HuggingFace 上的 SWE-bench 数据集 |
huggingface |
InstancesFromHuggingFace |
任意 HF 数据集,字段需符合 SimpleBatchInstance |
file |
InstancesFromFile |
本地 JSON/JSONL,元素为 SimpleBatchInstance |
expert_file |
ExpertInstancesFromFile |
本地文件,元素是完整的 BatchInstance(可逐实例配 deployment) |
swesmith |
SWESmithInstances |
SWE-smith 数据集 |
4.2 SWEBenchInstances 做了什么
定义在 batch_instances.py:270,关键字段:
python
subset: Literal["lite", "verified", "full", "multimodal", "multilingual"] = "lite"
split: Literal["dev", "test"] = "dev"
path_override: str | Path | None = None
deployment: DeploymentConfig = DockerDeploymentConfig(image="python:3.11")
filter / slice / shuffle
evaluate: bool = False
_get_dataset_path() 的映射:
| subset | HuggingFace 数据集 |
|---|---|
full |
princeton-nlp/SWE-Bench |
verified |
princeton-nlp/SWE-Bench_Verified |
lite |
princeton-nlp/SWE-Bench_Lite |
multimodal |
princeton-nlp/SWE-Bench_Multimodal |
multilingual |
swe-bench/SWE-Bench_Multilingual |
注意:path_override 可以指向本地数据集或镜像数据集,国内网络下很实用。
get_instance_configs() 的核心只有几行:
python
ds = load_dataset(self._get_dataset_path(), split=self.split)
if isinstance(self.deployment, DockerDeploymentConfig):
self.deployment.platform = "linux/amd64"
instances = [
SimpleBatchInstance.from_swe_bench(instance).to_full_batch_instance(self.deployment)
for instance in ds
]
return _filter_batch_items(instances, filter_=self.filter, slice_=self.slice, shuffle=self.shuffle)
两个细节:
- 强制
linux/amd64:SWE-bench 官方镜像是 x86_64 的,Apple Silicon/ARM 机器上必须模拟,否则镜像跑不起来; - 每个实例深拷贝 deployment :
to_full_batch_instance()里deployment.model_copy(deep=True),避免多个实例共享同一个可变配置对象。
4.3 镜像名是怎么推导出来的
SimpleBatchInstance.from_swe_bench()(batch_instances.py:173):
python
iid = instance["instance_id"]
image_name = instance.get("image_name")
if image_name is None:
id_docker_compatible = iid.replace("__", "_1776_")
image_name = f"docker.io/swebench/sweb.eval.x86_64.{id_docker_compatible}:latest".lower()
为什么要把 __ 换成 _1776_?因为 Docker 镜像名不允许连续下划线。比如:
text
django__django-11099
→ docker.io/swebench/sweb.eval.x86_64.django_1776_django-11099:latest
如果数据集里自带 image_name 字段,则直接使用,不再推导。这为自定义镜像(例如已经预装依赖的镜像)留了口子。
同时:
python
repo_name = "testbed"
base_commit = instance["base_commit"]
SWE-bench 官方镜像已经把仓库放在 /testbed,所以这里用 PreExistingRepoConfig,而不是重新 clone。
4.4 to_full_batch_instance():组装 BatchInstance
batch_instances.py:114:
python
deployment = deployment.model_copy(deep=True)
if "issue_images" in extra_fields:
problem_statement = SWEBenchMultimodalProblemStatement(...)
else:
problem_statement = TextProblemStatement(
text=self.problem_statement,
id=self.instance_id,
extra_fields=self.extra_fields,
)
仓库字段的判定顺序:
- 空字符串 →
repo = None; - GitHub URL →
GithubRepoConfig; - 不含
/→PreExistingRepoConfig(SWE-bench 走这条,repo_name="testbed"); - 其它 →
LocalRepoConfig。
最后把 deployment.image 覆盖成实例自己的镜像;如果 python_standalone_dir 还是 None,再设为 "/root"(SWE-ReX 需要把 standalone Python 放到容器里)。
4.5 真正被 Agent 使用的实例信息
最终 BatchInstance 只有两个字段:
python
class BatchInstance(BaseModel):
env: EnvironmentConfig
problem_statement: ProblemStatementConfig
TextProblemStatement 的 extra_fields 会进入模板渲染字典(agents.py:_get_format_dict()),SWE-bench 场景下至少包含:
problem_statement:issue 正文;repo:testbed;working_dir:/testbed;- 以及数据集里的额外字段。
这也是为什么自定义数据集只要提供 problem_statement + instance_id + base_commit + image_name,就能直接复用整套 SWE-bench 流程。
5. 运行环境:SWEEnv、SWE-ReX 与 ACI 工具
5.1 EnvironmentConfig
environment/swe_env.py:24:
python
class EnvironmentConfig(BaseModel):
deployment: DeploymentConfig = Field(
default_factory=lambda: DockerDeploymentConfig(
image="python:3.11", python_standalone_dir="/root"
)
)
repo: RepoConfig | None = None
post_startup_commands: list[str] = []
post_startup_command_timeout: int = 500
name: str = "main"
deployment:怎么把环境跑起来(Docker/Modal/Fargate/Local/Dummy);repo:仓库从哪里来、reset 到哪个 commit;post_startup_commands:环境启动后、Agent 开始前的额外命令(例如装依赖);name:实例名,日志和状态展示用。
5.2 SWEEnv.start() 的真实顺序
SWEEnv.start()(swe_env.py:109)只做三件事:
python
self._init_deployment() # 启动 deployment + 建 bash session
self.reset() # cd / → 准备仓库 → reset 到 base_commit
for command in self._post_startup_commands:
self.communicate(command, check="raise", timeout=...)
_init_deployment()(swe_env.py:176):
python
asyncio.run(self.deployment.start())
asyncio.run(self.deployment.runtime.create_session(
CreateBashSessionRequest(startup_source=["/root/.bashrc"], startup_timeout=10)
))
self.set_env_variables({
"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8",
"PIP_PROGRESS_BAR": "off", "PAGER": "cat",
})
也就是说,Agent 后续所有命令都复用同一个持久 bash session ,cd、export、shell 变量都会跨步骤保留。这正是它能像人一样「先 cd 再操作」的基础。
reset()(swe_env.py:135):
text
cd /
_copy_repo() # ls 检查仓库目录是否存在;不存在才 clone/copy
_reset_repository() # cd /testbed; export ROOT=$(pwd -P); git fetch/status/restore/reset/checkout/clean
on_environment_startup()
PreExistingRepoConfig 的 copy() 是空操作,get_reset_commands() 返回(repo.py:31):
bash
git fetch
git status
git restore .
git reset --hard
git checkout <base_commit>
git clean -fdq
这保证每个实例都从干净的 base commit 开始,不会把上一个实例的修改带进来。
5.3 communicate():一切命令的入口
swe_env.py:197:
python
r = asyncio.run(
self.deployment.runtime.run_in_session(
BashAction(command=input, timeout=timeout, check=rex_check)
)
)
几个关键点:
check="ignore"时不解析退出码 ,只拿输出。这是默认值,因为很多探索性命令(grep没匹配、ls不存在)返回非零很正常;check="raise"用于环境准备、工具安装等必须成功的命令;- 超时由
BashAction.timeout控制,默认来自ToolConfig.execution_timeout=30秒; - 命令和输出都会以 TRACE 级别写入日志,调试时非常有用。
除了 communicate(),SWEEnv 还提供:
| 方法 | 用途 |
|---|---|
read_file() / write_file() |
直接读写容器文件(走 runtime,不经过 shell) |
execute_command() |
在 session 之外起子进程执行命令 |
set_env_variables() |
批量 export |
interrupt_session() |
命令超时后中断当前 shell |
hard_reset() |
关掉重开整个 deployment |
close() |
停止 deployment |
5.4 工具(ACI)不是 Python API,而是容器里的命令
这是 SWE-agent 设计上很重要的一点:模型看到的工具是 bash 可执行文件 + 一段文档,不是函数调用式的 Python 对象。
ToolConfig(tools/tools.py:75)关键字段:
python
filter: ToolFilterConfig # 禁用交互式/危险命令
bundles: list[Bundle] # 工具包目录
propagate_env_variables: list[str]# 从宿主机透传环境变量
env_variables: dict[str, Any] # 容器内环境变量
registry_variables: dict[str, Any]# 写入 /root/.swe-agent-env
submit_command: str = "submit" # 提交命令名
parse_function: ParseFunction # 输出解析器
enable_bash_tool: bool = True # 是否额外提供 bash 工具
execution_timeout: int = 30
install_timeout: int = 300
total_execution_timeout: int = 1800
max_consecutive_execution_timeouts: int = 3
一个 bundle 的标准结构:
text
tools/edit_anthropic/
├── config.yaml # 工具签名、文档、参数
├── install.sh # 可选:安装依赖
├── bin/
│ ├── str_replace_editor
│ └── _state_anthropic
└── lib/ # 可选:Python 依赖
Bundle(tools/bundle.py)在加载时会:
- 校验目录存在;
- 读取
config.yaml; - 把每个工具项转成
Command; - 校验
hidden_tools是否合法。
config.yaml 里最核心的是 signature 和 docstring。例如 tools/review_on_submit_m/config.yaml:
yaml
tools:
submit:
signature: "submit"
docstring: "submits the current file"
Command.get_function_calling_tool() 会把它转成 OpenAI function calling 的 schema;如果是 thought_action 解析器,generate_command_docs() 会把所有工具的签名和文档拼成一段文本塞进系统提示词。
5.5 工具安装流程
DefaultAgent.setup() 会调用 ToolHandler.install(env)(tools/tools.py:252),后者分两步:
第一步:_install_commands(env)
text
设置 env_variables
pwd 记录当前目录
把每个 bundle 上传到 /root/tools/<bundle名>
export PATH=/root/tools/<bundle名>/bin:$PATH
chmod +x bin/*
如果存在 install.sh,则 source 它
再次 chmod +x bin/*
恢复原目录
对每个命令执行 which <name>,确认可用
install.sh 常用于装依赖。例如 tools/edit_anthropic/install.sh:
bash
pip install 'tree-sitter==0.21.3' || true
pip install 'tree-sitter-languages' || true
注意 || true:依赖装失败不会直接终止,只是编辑器能力可能退化。
第二步:reset(env)
python
env.set_env_variables(env_variables)
env.write_file("/root/.swe-agent-env", json.dumps(registry_variables))
env.write_file("/root/state.json", "{}")
env.communicate(" && ".join(self._reset_commands), ...)
/root/.swe-agent-env 是跨进程共享状态的文件(环境变量在子进程里设不住,所以用 JSON 文件);state.json 用来存放每步的附加状态。
5.6 工具状态(state)
ToolConfig.state_commands 会收集所有 bundle 声明的 state_command。每步执行完动作后,ToolHandler.get_state():
- 在 shell 里依次执行这些 state 命令;
- 读取
/root/state.json; - 返回 dict,合并进模板变量。
例如 tools/diff_state/config.yaml:
yaml
tools: {}
state_command: "_state_diff_state"
它的作用是把当前 git diff 放进 state,于是 next_step_template 里可以直接引用 {``{diff}}。默认配置没有启用 diff_state,但 review_on_submit_m 的提交流程会用 git diff 生成待评审补丁。
5.7 命令过滤(blocklist)
ToolFilterConfig 默认禁用:
text
vim, vi, emacs, nano, nohup, gdb, less, tail -f,
python -m venv, make
以及完全匹配时禁用:
text
python, python3, ipython, bash, sh, /bin/bash, /bin/sh,
nohup, vi, vim, emacs, nano, su
原因很直接:
- 交互式编辑器/分页器会占住 shell,Agent 永远等不到输出;
- 直接起
python/bash会进入 REPL,同样卡死; make/tail -f可能长时间不返回。
被拦截时抛出 _BlockedActionError,Agent 会把 blocklist_error_template 渲染成一条消息,让模型换命令重试。
5.8 多行命令保护
模型可能输出:
bash
cat > /tmp/x.py <<'EOF'
print(1)
EOF
也可能输出 str_replace_editor 这种需要多行参数的工具。guard_multiline_input()(tools/utils.py)会检查命令是否以某个 end_name 结尾,如果没有,就自动在首行补上 heredoc 终止符:
text
str_replace_editor create /testbed/x.py <<'EOF'
...
EOF
这样多行内容才能安全地通过一个 BashAction 送进 shell。
6. Agent 主循环
6.1 类关系
text
AbstractAgent
├── DefaultAgent # 默认实现,单次尝试
├── RetryAgent # 多次尝试 + reviewer 选最优
└── ShellAgent # 只跑 shell 命令的简化 Agent
get_agent_from_config()(agents.py:242)按 agent.type 分发。绝大多数 SWE-bench 跑分使用 default。
6.2 配置与构造
DefaultAgentConfig(agents.py:149):
python
templates: TemplateConfig
tools: ToolConfig
history_processors: list[HistoryProcessor]
model: ModelConfig
max_requeries: int = 3
action_sampler: ActionSamplerConfig | None = None
type: Literal["default"] = "default"
DefaultAgent.from_config() 会 model_copy(deep=True),然后创建:
get_model(config.model, config.tools)→LiteLLMModel(或 Human/Replay);ToolHandler(config.tools);DefaultAgent(...)。
深拷贝的目的:每个实例、每个线程都有独立的 model/tools 配置,避免并发时互相污染。
6.3 setup():把提示词和历史准备好
DefaultAgent.setup()(agents.py:561)按顺序做:
- 设置
traj_path = output_dir/<instance_id>.traj; tools.install(env):上传并安装所有工具;- 写入版本信息(
swe_agent_version、swe_rex_version、commit hash); - 把问题描述写进容器环境变量
PROBLEM_STATEMENT(给 submit/review 工具用); add_system_message_to_history():渲染system_template;add_demonstrations_to_history():可选的 few-shot 示例;add_instance_template_to_history(state=tools.get_state(env)):渲染instance_template,把 issue 正文、仓库路径、初始状态交给模型。
此时 history 大致是:
text
[system] You are a helpful assistant ...
[user] <uploaded_files>/testbed</uploaded_files>
... <pr_description> ... </pr_description>
... 请修改代码 ...
6.4 主循环:run() 与 step()
DefaultAgent.run()(agents.py:1265)短得惊人:
python
self.setup(env=env, problem_statement=problem_statement, output_dir=output_dir)
step_output = StepOutput()
while not step_output.done:
step_output = self.step()
self.save_trajectory()
step()(agents.py:1235):
python
step_output = self.forward_with_handling(self.messages)
self.add_step_to_history(step_output)
self.info["submission"] = step_output.submission
self.info["exit_status"] = step_output.exit_status
self.info["edited_files30/50/70"] = ...
self.info["model_stats"] = self.model.stats.model_dump()
self.add_step_to_trajectory(step_output)
注意几个设计点:
self.messages是经过 history_processors 处理后的 历史,不是原始self.history;add_step_to_history()把「模型输出」和「环境观察」分别追加为 assistant / user(tool) 消息;step()结束时把补丁上下文(edited_files30/50/70)也算进 info,方便日志和调试;- 每步都写一次
.traj,所以进程被杀也能保留已完成的步骤。
6.5 forward():一次模型查询 + 一次动作执行
forward()(agents.py:1006)是核心中的核心:
python
step = StepOutput()
step.query = deepcopy(history)
# 1. 调模型
output = self.model.query(history) # 或 action_sampler
step.output = output["message"]
# 2. 解析成 thought + action
step.thought, step.action = self.tools.parse_actions(output)
step.thinking_blocks = output.get("thinking_blocks", [])
if output.get("tool_calls"):
step.tool_call_ids = [...]
step.tool_calls = output["tool_calls"]
# 3. 执行动作
return self.handle_action(step)
如果中途抛异常,会把 step 挂到异常对象上(e.step = step),这样上层重试逻辑还能拿到「模型原本说了什么」,用于构造纠错提示。
6.6 handle_action():动作执行的完整逻辑
handle_action()(agents.py:936)按顺序处理:
-
blocklist 检查 :命中就抛
_BlockedActionError; -
exit特判 :直接结束,exit_status="exit_command"; -
多行命令保护 :
guard_multiline_input(); -
执行命令 :
pythonstep.observation = self._env.communicate( input=run_action, timeout=self.tools.config.execution_timeout, check="raise" if self._always_require_zero_exit_code else "ignore", ) -
超时处理 :连续超时达到
max_consecutive_execution_timeouts=3次就退出;否则中断 session,并把command_cancelled_timeout_template作为观察结果; -
收集 state :
step.state = self.tools.get_state(env); -
特殊 token :
###SWE-AGENT-RETRY-WITH-OUTPUT###→_RetryWithOutput###SWE-AGENT-RETRY-WITHOUT-OUTPUT###→_RetryWithoutOutput###SWE-AGENT-EXIT-FORFEIT###→_ExitForfeit
-
提交检测 :
handle_submission(step)。
这些特殊 token 是给工具脚本用的「控制通道」。例如 tools/review_on_submit_m/bin/submit 会输出 <<SWE_AGENT_SUBMISSION>> 包裹的补丁,ToolHandler.check_for_submission_cmd() 检测到后就会读取 /root/model.patch。
6.7 错误处理与重试矩阵
真正包住 forward() 的是 forward_with_handling()(agents.py:1062)。它最多重试 max_requeries=3 次,不同异常走不同策略:
| 异常 | 处理方式 | 最终 exit_status |
|---|---|---|
FormatError(解析不出动作) |
用 format_error_template 要求模型重新输出 |
重试耗尽后 exit_format |
_BlockedActionError |
用 blocklist_error_template 提示换命令 |
重试耗尽后 exit_format |
ContentPolicyViolationError |
直接重采样 | 重试耗尽后 exit_format |
BashIncorrectSyntaxError |
用 shell_check_error_template 附上 bash -n 输出 |
重试耗尽后 exit_format |
_RetryWithOutput |
用 next_step_template 带上当前观察重问 |
继续循环 |
_RetryWithoutOutput |
用上一步同样的模板重问 | 继续循环 |
_ExitForfeit |
自动提交后退出 | exit_forfeit |
_TotalExecutionTimeExceeded |
自动提交后退出 | exit_total_execution_time |
CommandTimeoutError |
自动提交后退出 | exit_command_timeout |
ContextWindowExceededError |
自动提交后退出 | exit_context |
CostLimitExceededError |
自动提交后退出 | exit_cost |
TotalCostLimitExceededError |
向上抛出,整个 batch 停止 | 由 RunBatch 处理 |
RetryError(litellm 重试耗尽) |
自动提交后退出 | exit_api |
SwerexException |
自动提交后退出 | exit_environment_error |
RuntimeError / 其它 Exception |
自动提交后退出 | exit_error |
两个容易忽略的点:
exit_status不等于失败 。submitted (exit_cost)这种表示「虽然因为成本限制退出,但还是把当前补丁提交了」;- 格式错误不会立刻杀死实例。只要模型能在 3 次内改对,轨迹里甚至不会留下错误步骤(错误步骤只进 trajectory,不进 history)。
6.8 历史处理器(History Processors)
self.messages 每次都会把 self.history 过一遍处理器链。常见处理器:
| 类型 | 作用 |
|---|---|
DefaultHistoryProcessor |
默认空操作,保证接口统一 |
LastNObservations |
只保留最近 N 条观察,前面替换成占位文本 |
TagToolCallObservations |
给工具调用对应的观察打标签 |
ClosedWindowHistoryProcessor |
窗口化编辑:只保留当前打开文件的相关观察 |
CacheControlHistoryProcessor |
给最近 N 条消息加 cache_control,配合 Anthropic prompt caching |
RemoveRegex |
用正则删除敏感/冗余内容 |
ImageParsingHistoryProcessor |
多模态:把图片转成模型可接受的格式 |
config/default.yaml 默认启用:
yaml
history_processors:
- type: cache_control
last_n_messages: 2
这也是为什么 LiteLLMModel._history_to_messages() 里要专门处理 cache_control 字段。
6.9 动作解析器(Parse Functions)
tools/parsing.py 里定义了 11 种解析器,核心区别是「模型输出格式」:
| 类型 | 适用场景 |
|---|---|
function_calling |
模型原生支持 tool calling(默认) |
thought_action |
纯文本模型,输出 THOUGHT: ... ACTION: ... |
xml_thought_action |
用 XML 标签包裹思考和动作 |
xml_function_calling |
XML 形式的工具调用 |
json |
输出 JSON 对象 |
action_only |
人类模式:只输入动作 |
all_bash_code_blocks |
从 Markdown 的 bash 代码块提取命令 |
single_bash_code_block |
只取第一个代码块 |
edit_format |
兼容 Aider 风格编辑格式 |
identity |
不做解析 |
action |
直接当动作 |
FunctionCallingParser 的额外职责:
- 把
tool_calls转成可执行命令; - 校验参数是否齐全;
- 生成
format_error_template; - 处理
tool_call_id,让观察消息能以role="tool"回填。
ToolConfig.use_function_calling 就是判断解析器是否为 FunctionCallingParser;只有它为真时,才会把工具 schema 传给 litellm,并在模型响应里读取 tool_calls。
6.10 模型层:成本、限流与重试
LiteLLMModel(agent/models.py:578)封装了 litellm:
查询前
- 用
litellm.utils.token_counter()估算输入 token; - 超过
max_input_tokens直接抛ContextWindowExceededError; api_base只在设置时传给 litellm;- function calling 模式下附带
tools=self.tools.tools; - Anthropic 模型强制设置
max_tokens; - 加
User-Agent: swe-agent/1.1.0。
查询后
- 用
litellm.cost_calculator.completion_cost()计算成本; - 算不出来时:如果开了成本限制就报
ModelConfigurationError,否则成本记 0; - 累加
InstanceStats:tokens_sent、tokens_received、api_calls、instance_cost; - 检查三个上限:
total_cost_limit→TotalCostLimitExceededErrorper_instance_cost_limit→InstanceCostLimitExceededErrorper_instance_call_limit→InstanceCallLimitExceededError
重试
用 tenacity.Retrying 包裹,指数退避(min_wait/max_wait),但以下异常不重试:
text
ContextWindowExceededError, CostLimitExceededError, RuntimeError,
UnsupportedParamsError, NotFoundError, PermissionDeniedError,
APIError, ContentPolicyViolationError, TypeError,
AuthenticationError, ModelConfigurationError, KeyboardInterrupt, IndexError
全局统计
GLOBAL_STATS + GLOBAL_STATS_LOCK(models.py:283,锁在 models.py:288)在所有实例之间共享总成本。这也是 total_cost_limit 能跨实例生效的原因。
其它模型类型:
| 类型 | 用途 |
|---|---|
HumanModel |
人在终端输入动作,调试/演示 |
HumanThoughtModel |
人输入思考和动作 |
ReplayModel |
回放已有轨迹,用于测试 |
InstantEmptySubmitModel |
立刻提交空补丁,用于基线/流程验证 |
6.11 多动作采样与 RetryAgent
ActionSampler(agent/action_sampler.py):一次让模型生成多个候选动作,再由策略挑选。支持ask_colleagues等模式。RetryAgent(agents.py:257):把同一个问题跑多次DefaultAgent,每次尝试后由reviewer.py打分/比较,选最优提交。配置类型是retry,常用于论文复现配置(config/benchmarks/*.yaml)。
对大多数工程使用,default + 合理的 max_requeries 已经够用;retry 的提升通常伴随成倍成本。
7. 提交、补丁导出与预测文件
7.1 submit 工具的协议
默认配置加载 tools/review_on_submit_m,它的 bin/submit 做三件事:
- 在仓库根目录执行
git add -A && git diff --cached > /root/model.patch; - 根据
SUBMIT_REVIEW_MESSAGES做多阶段自检(先让模型 review 自己的 diff,再要求重新 submit); - 最终输出:
text
<<SWE_AGENT_SUBMISSION>>
<patch 内容>
<<SWE_AGENT_SUBMISSION>>
ROOT 不是 registry 主动注入的:环境 reset 时 _reset_repository() 会先执行 export ROOT=$(pwd -P)(swe_env.py:157),工具脚本再通过 registry.get("ROOT", os.getenv("ROOT")) 读取;registry.get() 在文件里找不到时会回退到同名环境变量。所以脚本不依赖当前工作目录。
7.2 handle_submission():把补丁读回来
agents.py:870:
python
is_submission = self.tools.check_for_submission_cmd(observation)
if is_submission or force_submission:
submission = self._env.read_file("/root/model.patch", ...)
step.submission = submission if submission.strip() else None
step.observation = submission
step.exit_status = "submitted"
step.done = True
关键点:
- 补丁不是从 stdout 解析的 ,而是从容器里的
/root/model.patch读取。stdout 只用来判断「是否提交」; - 空补丁会被设为
None,最终预测里就是空 patch; done=True让主循环退出。
7.3 出错时的自动提交
attempt_autosubmission_after_error()(agents.py:823)是 SWE-agent 很实用的一个设计:即使 Agent 因为超时/成本/API 错误退出,也尽量把当前工作区保存下来。
逻辑:
text
如果 runtime 还活着:
执行 git add -A && git diff --cached > /root/model.patch
强制 handle_submission(force_submission=True)
否则:
从最后一步 trajectory 的 state["diff"] 里取补丁
这就是为什么很多 exit_cost / exit_api 的实例仍然能产出可用补丁。
7.4 补丁文件与预测文件
SaveApplyPatchHook (run/hooks/apply_patch.py)在每个实例完成时:
text
<output_dir>/<instance_id>/<instance_id>.patch
内容就是 info["submission"]。如果 apply_patch_locally=True 且仓库是本地路径,还会尝试 git apply。
save_predictions() (run/common.py:370)写:
text
<output_dir>/<instance_id>/<instance_id>.pred
内容:
json
{
"model_name_or_path": "<output_dir 的名字>",
"instance_id": "django__django-11099",
"model_patch": "diff --git ..."
}
merge_predictions() (run/merge_predictions.py)在 batch 结束时扫描所有 *.pred:
- 以
instance_id为 key 合并; - 重复 instance 直接报错;
model_patch=None转成空字符串;- 输出
<output_dir>/preds.json。
preds.json 就是 SWE-bench harness 需要的输入格式。
7.5 单个实例的输出目录
text
runs/lite_5/
├── run_batch.config.yaml # 本次运行的完整配置
├── run_batch.log # 批量级日志
├── run_batch_exit_statuses.yaml # 每个实例的退出状态汇总
├── preds.json # 合并后的预测
├── django__django-11099/
│ ├── django__django-11099.traj # 轨迹(history + info)
│ ├── django__django-11099.pred # 单实例预测
│ ├── django__django-11099.patch # 补丁
│ ├── django__django-11099.config.yaml # 单实例配置快照
│ ├── django__django-11099.trace.log
│ ├── django__django-11099.debug.log
│ └── django__django-11099.info.log
└── ... 其它实例
排查问题时,推荐顺序:
*.info.log:看每步的 thought/action/observation;*.traj:看完整 history 和 model_stats;*.patch:确认补丁是否符合预期;run_batch_exit_statuses.yaml:确认是submitted还是exit_*。
8. 批量运行、并发与断点续跑
8.1 RunBatch.main()
run_batch.py:240:
python
self._chooks.on_start()
if self._num_workers <= 1:
self.main_single_worker()
else:
self.main_multi_worker()
# 所有实例结束后
merge_predictions(output_dirs, self.output_dir / "preds.json")
self._chooks.on_end()
注意 preds.json 是最后统一合并 的;即使某个实例失败,只要它之前写出过 .pred,也会被合并(取决于是否被跳过)。
8.2 单线程 vs 多线程
单线程 (main_single_worker):
python
with Live(progress):
for instance in instances:
try: self.run_instance(instance)
except _BreakLoop: break
多线程 (main_multi_worker):
python
with ThreadPoolExecutor(max_workers=self._num_workers) as executor:
futures = [executor.submit(self.run_instance, instance) for instance in instances]
for future in as_completed(futures):
future.result()
几个细节:
num_workers = min(num_workers, len(instances)),不会开多余线程;- 多线程时把 stream handler 调到 WARNING,避免日志互相刷屏;每个实例仍然有自己的文件日志;
- 启动时
sleep(random() * random_delay_multiplier * (num_workers - 1)),避免所有容器同时拉镜像/启动; KeyboardInterrupt会取消未开始的任务,但等待正在跑的任务结束。
这里的「并发」是线程并发,不是进程并发。因为主要时间花在「等模型 API」和「等容器命令」上,Python 线程足够;真正吃 CPU 的是容器内的测试,不在 Agent 进程里。
8.3 run_instance() 的异常策略
run_instance()(run_batch.py:291)区分三类异常:
| 异常 | 行为 |
|---|---|
KeyboardInterrupt |
抛 _BreakLoop,停止整个 batch |
SystemExit / ModelConfigurationError / TotalCostLimitExceededError |
记录 critical,抛 _BreakLoop,停止整个 batch |
其它 Exception |
记录 traceback,标记该实例失败,继续下一个 |
raise_exceptions=True 时,前两类也会直接抛出,适合调试。
_run_instance() 的 finally 一定执行 env.close(),所以即使 Agent 崩了,容器也会被清理。
8.4 断点续跑:should_skip()
run_batch.py:376:
text
如果 redo_existing=True → 不跳过
如果 <instance_id>.traj 不存在 → 不跳过
如果 traj 为空 → 删除,不跳过
如果 traj 的 info.exit_status 缺失或等于 "early_exit" → 删除,不跳过
否则 → 跳过,返回之前的 exit_status
这带来一个很实用的工作流:
bash
# 第一次跑,部分实例失败/超时
sweagent run-batch ... --output_dir runs/exp1
# 第二次直接重跑同一目录,已完成的会自动跳过
sweagent run-batch ... --output_dir runs/exp1
注意:should_skip() 只检查 .traj,不检查 .pred。如果 .traj 存在但 .pred 缺失(例如写 pred 前进程被杀),该实例会被跳过,最终 preds.json 里可能没有它。遇到这种情况,删掉对应 .traj 或加 --redo_existing。
8.5 进度与状态
RunBatchProgressManager(run/_progress.py)用 rich 展示:
- 总进度条:完成数/总数、总成本、ETA;
- 每个实例一行 spinner,显示当前阶段(Starting environment / Step N / Installing tools 等);
- 结束时打印按 exit_status 分组的报表;
- 同时把结果写进
run_batch_exit_statuses.yaml。
状态更新通过 hook 注入:
SetStatusAgentHook:Step N、成本;SetStatusEnvironmentHook:环境启动/重置;SetStatusDeploymentHook:容器启动。
9. 用 SWE-bench 评估 Agent 性能
9.1 两条评测路径
SWE-agent 只产出 preds.json,判分有两条路:
路径 A:内置 sb-cli(云端)
bash
sweagent run-batch \
--instances.type swe_bench \
--instances.subset lite \
--instances.split test \
--instances.evaluate True \
...
当 instances.evaluate=True 时,RunBatch.from_config() 会挂上 SweBenchEvaluate hook(run_batch.py:224)。它做两件事:
- 每 30 秒把当前
preds.json增量提交给sb-cli submit(continuous_submission_every=30); - 全部结束后提交最终
preds.json,并把sb-cli-reports/*.json重命名为results.json。
限制:
sb-cli只支持lite/verified/multimodal三个 subset;- 需要
sb-cli安装和凭据/网络; evaluate=True与redo_existing=True互斥(RunBatchConfig.evaluate_and_redo_existing校验),否则会把旧预测重复提交。
路径 B:本地官方 harness(本仓库采用)
bash
python -m swebench.harness.run_evaluation \
--dataset_name SWE-bench/SWE-bench_Lite \
--split test \
--predictions_path runs/lite_5/preds.json \
--run_id lite_5 \
--max_workers 1 \
--timeout 1800 \
--report_dir runs/lite_5/report
优点:
- 完全本地、可重复、可离线缓存镜像;
- 能直接看每个实例的测试日志;
- 不依赖
sb-cli的账号和网络。
缺点:
- 需要本地 Docker 和足够磁盘(Lite 全量镜像很大);
- 单个实例要起容器、跑测试,速度慢;
- 需要自己处理镜像源/网络。
本仓库的封装脚本是 eval_swebench.sh,它做了三件事:
source setup_env.sh(HF 镜像、HF_HOME、venv PATH、DEEPSEEK_API_KEY);- 检查
<run_dir>/preds.json; - 调用
python -m swebench.harness.run_evaluation,报告写到<run_dir>/report/。
9.2 harness 的输入与输出
输入
| 参数 | 含义 |
|---|---|
--dataset_name |
SWE-bench/SWE-bench_Lite(新版数据集名) |
--split |
test / dev |
--predictions_path |
preds.json |
--run_id |
本次评测 ID,决定日志目录 logs/run_evaluation/<run_id>/ |
--max_workers |
并行评测容器数 |
--timeout |
单实例测试超时(秒) |
--report_dir |
汇总报告输出目录 |
preds.json 的格式:
json
{
"django__django-11099": {
"model_name_or_path": "lite_5",
"instance_id": "django__django-11099",
"model_patch": "diff --git a/... b/..."
}
}
输出
text
<report_dir>/<model_name_or_path>.<run_id>.json # 汇总
logs/run_evaluation/<run_id>/<model_name_or_path>/<instance_id>/ # / 会替换为 __
├── report.json # 单实例判定
├── run_instance.log # 容器执行日志
├── test_output.txt # 测试原始输出
└── ...
汇总报告的关键字段(实测 runs/lite_5/report/lite_5.lite_5.json):
json
{
"total_instances": 300,
"submitted_instances": 5,
"completed_instances": 5,
"resolved_instances": 4,
"unresolved_instances": 1,
"infra_failure_instances": 0,
"ambiguous_failure_instances": 0,
"empty_patch_instances": 0,
"error_instances": 0
}
注意 total_instances 是数据集大小(Lite test=300),不是本次提交数;本次只提交了 5 条,所以看 submitted_instances 和 resolved_instances。
单实例 report.json:
json
{
"psf__requests-2317": {
"patch_is_None": false,
"patch_exists": true,
"patch_successfully_applied": true,
"resolved": false,
"infra_failure": false,
"tests_status": {
"FAIL_TO_PASS": {"success": [...], "failure": [...]},
"PASS_TO_PASS": {"success": [...], "failure": [...]}
}
}
}
9.3 harness 内部做了什么
text
1. 读取数据集,构造 TestSpec
├─ instance_id
├─ repo / base_commit
├─ FAIL_TO_PASS / PASS_TO_PASS
└─ 测试命令、日志解析器
2. 准备镜像
├─ 优先使用本地缓存的 swebench/sweb.eval.x86_64.<iid>:latest
└─ 没有则拉取/构建
3. 启动容器,checkout base_commit
4. 应用模型补丁
├─ 写入 /tmp/patch.diff
├─ git apply / patch -p1
└─ 记录 APPLY_PATCH_PASS / APPLY_PATCH_FAIL
5. 运行测试
├─ 执行该仓库对应的 test command
├─ 捕获 stdout/stderr
└─ 交给 log parser 解析成 {test_name: PASSED/FAILED/...}
6. 与 gold 结果对比
├─ FAIL_TO_PASS:之前失败、修复后应该通过
├─ PASS_TO_PASS:之前通过、修复后仍应通过
└─ 计算 resolved
9.4 resolved 的判定规则
swebench.harness.grading 的核心逻辑:
python
f2p = compute_fail_to_pass(report) # 1.0 表示 F2P 全过
p2p = compute_pass_to_pass(report) # 1.0 表示 P2P 全过
if f2p == 1 and p2p == 1:
return ResolvedStatus.FULL # RESOLVED_FULL
elif 0 < f2p < 1 and p2p == 1:
return ResolvedStatus.PARTIAL # RESOLVED_PARTIAL
else:
return ResolvedStatus.NO # RESOLVED_NO
换句话说:
- FULL :所有
FAIL_TO_PASS都通过,且所有PASS_TO_PASS都通过; - PARTIAL:修复了一部分 F2P,但没有全过,且 P2P 没退化;
- NO:F2P 没过,或 P2P 出现退化。
报告里的 resolved: true 对应 FULL。PARTIAL 在大多数排行榜口径里不算 resolved。
9.5 应该看哪些指标
| 指标 | 来源 | 说明 |
|---|---|---|
resolved_rate |
resolved_instances / submitted_instances |
最核心指标;不要用 total_instances 当分母 |
empty_patch_instances |
汇总报告 | 模型没产出补丁,通常是环境/解析/提交问题 |
error_instances |
汇总报告 | harness 自身执行错误 |
infra_failure_instances |
汇总报告 | 基础设施失败(镜像、网络、容器) |
patch_successfully_applied |
单实例报告 | 补丁应用失败说明 diff 格式或 baseline 不对 |
tests_status |
单实例报告 | 精确定位是 F2P 没过还是 P2P 退化 |
model_stats |
.traj 的 info |
token、成本、API 调用次数 |
exit_status |
.traj 的 info |
submitted / exit_cost / exit_context 等 |
| 步数 | len(trajectory) |
效率;步数过多通常意味着模型在反复试错 |
| 补丁大小 | .patch 字节数 |
过大多半是改了无关文件或格式混乱 |
9.6 本仓库实测结果
运行目录:runs/lite_5,SWE-agent 1.1.0,模型 openai/deepseek-flash,2 并发。
| 实例 | 步数 | 补丁大小 | 结果 |
|---|---|---|---|
django__django-11099 |
19 | 901 B | resolved |
mwaskom__seaborn-3010 |
31 | 465 B | resolved |
pallets__flask-4045 |
42 | 2041 B | resolved |
psf__requests-2317 |
33 | 1329 B | unresolved |
pytest-dev__pytest-6116 |
27 | 618 B | resolved |
汇总:
text
Instances submitted: 5
Instances completed: 5
Instances resolved: 4
Instances unresolved: 1
Instances with errors: 0
Instances with empty patches: 0
resolved_rate: 80.0%
Agent 阶段总耗时约 45 分 27 秒 ,total_cost: 0(自定义模型未接入价格表,成本统计为 0 不代表免费)。
9.7 唯一失败实例分析
psf__requests-2317:
json
{
"patch_successfully_applied": true,
"resolved": false,
"tests_status": {
"FAIL_TO_PASS": {"success": [6 条], "failure": [2 条]},
"PASS_TO_PASS": {"success": [129 条], "failure": [4 条]}
}
}
补丁成功应用 ,大部分测试也通过,失败集中在依赖外网 httpbin / pyOpenSSL 的用例:
text
TypeError: getresponse() got an unexpected keyword argument 'buffering'
requests.exceptions.ConnectionError: ...
结论:这不是「补丁没生效」,而是该实例的测试环境需要稳定访问 httpbin.org。在国内网络/离线环境下,这类实例天然不适合作为 Agent 能力指标;要么给评测容器配代理,要么在统计时单独标注。
9.8 复现命令
bash
cd ~/swe_agent_bench
source setup_env.sh
# 1. 跑 Agent,产出 runs/lite_5/preds.json
NUM_WORKERS=2 MAX_CALLS=60 ./run_swebench.sh runs/lite_5 \
'django__django-11099|pallets__flask-4045|psf__requests-2317|pytest-dev__pytest-6116|mwaskom__seaborn-3010' 0:5
# 2. 官方 harness 判分
./eval_swebench.sh runs/lite_5
# 3. 汇总
./venv/bin/python summarize_results.py runs/lite_5
run_swebench.sh 的关键参数:
bash
sweagent run-batch \
--config SWE-agent/config/default.yaml \
--instances.type swe_bench \
--instances.subset lite \
--instances.split test \
--instances.filter "$FILTER" \
--instances.slice "$SLICE" \
--agent.model.name "$MODEL" \
--agent.model.api_base https://api.deepseek.com/v1 \
--agent.model.api_key '$DEEPSEEK_API_KEY' \
--agent.model.per_instance_cost_limit 0 \
--agent.model.total_cost_limit 0 \
--agent.model.max_input_tokens 0 \
--agent.model.per_instance_call_limit "${MAX_CALLS:-60}" \
--num_workers "${NUM_WORKERS:-1}" \
--output_dir "$OUT"
把成本/上下文限制设为 0 是为了避免未接入价格表时误触发;同时用 per_instance_call_limit=60 兜底,防止模型陷入死循环。
9.9 评测常见坑
| 坑 | 现象 | 处理 |
|---|---|---|
| 数据集名用错 | DatasetNotFoundError |
Lite 用 SWE-bench/SWE-bench_Lite;旧名 princeton-nlp/SWE-Bench_Lite 也可,但不要混用 split |
split 用错 |
加载到 dev 或空集 | Lite 评测固定 test |
| ARM 机器 | 镜像 manifest 不匹配 | SWE-agent 已强制 platform="linux/amd64";确保 Docker 支持模拟 |
| 镜像拉不动 | pull access denied / timeout |
配 registry mirror;或提前 docker pull |
| 补丁应用失败 | patch_successfully_applied=false |
检查 .patch 是否基于正确 base_commit;检查是否包含二进制/CRLF |
| 空补丁 | empty_patch_instances>0 |
查 .traj 的 exit_status;常见是 exit_context / exit_cost / 解析失败 |
| 测试依赖外网 | 大量 ConnectionError |
配代理,或单独排除这类实例(如 requests 的 httpbin 测试) |
| P2P 退化 | F2P 全过但 unresolved | 补丁改了测试/公共代码;看 PASS_TO_PASS.failure |
evaluate=True + redo_existing=True |
启动即报错 | 二者互斥,分开跑 |
run_id 复用 |
日志/报告覆盖 | 每次评测用不同 run_id,或先删 logs/run_evaluation/<run_id> |
max_workers 太大 |
OOM/容器启动失败 | Lite 单实例测试很吃内存,建议 1--4 |
preds.json 缺实例 |
报告里 submitted 少 | 检查 should_skip() 是否跳过了只有 .traj 没有 .pred 的实例 |
9.10 exit_status 与 resolved 的关系
这两个维度互相独立:
exit_status=submitted只表示「Agent 认为自己提交了补丁」,不代表补丁正确;exit_status=exit_cost/exit_api也可能是好补丁(自动提交兜底);resolved只由 harness 的测试结果决定。
因此分析结果时,建议同时看:
text
exit_status → 过程是否健康
patch_successfully_applied → 补丁格式是否可用
tests_status → 补丁是否真正解决问题
10. 扩展点:怎样改造成自己的 Agent
10.1 加一个工具(最常见)
不需要改 Python 代码,只要加一个 bundle:
text
tools/my_tool/
├── config.yaml
├── install.sh # 可选
└── bin/
└── my_tool
config.yaml:
yaml
tools:
my_tool:
signature: "my_tool <path> [<line>]"
docstring: |
对文件做某件事。
path: 文件路径
line: 可选行号
arguments:
- name: path
type: string
description: 文件路径
required: true
- name: line
type: integer
description: 行号
required: false
然后在 config/default.yaml 的 agent.tools.bundles 里加上:
yaml
bundles:
- path: tools/registry
- path: tools/edit_anthropic
- path: tools/review_on_submit_m
- path: tools/my_tool
启动时 ToolHandler._install_commands() 会:
- 上传到
/root/tools/my_tool; - 把
bin/加进PATH; chmod +x;- 执行
install.sh; - 用
which my_tool校验。
如果要给模型提供状态,在 config.yaml 里加:
yaml
state_command: "_state_my_tool"
并在 bin/_state_my_tool 里把结果写进 /root/state.json。
10.2 换解析器
如果模型不支持原生 function calling,把:
yaml
parse_function:
type: function_calling
改成:
yaml
parse_function:
type: thought_action
对应 ThoughtActionParser,要求模型输出:
text
THOUGHT: ...
ACTION: ...
如果模型的输出格式很特殊,可以实现新的 AbstractParseFunction 子类,并加入 parse_function.py 末尾的 ParseFunction 联合类型(parsing.py:609)。
10.3 换历史策略
在 agent.history_processors 里增删即可:
yaml
history_processors:
- type: last_n_observations
n: 5
- type: cache_control
last_n_messages: 2
可选类型见 history_processors.py:390 的 HistoryProcessor 联合类型。自定义处理器只需实现 __call__(history) -> history,然后加入联合类型。
10.4 换模型 / 加自定义模型
- 绝大多数 OpenAI 兼容模型:只改
agent.model.name+api_base+api_key,走LiteLLMModel; - 需要特殊协议:继承
AbstractModel,实现query()和_update_stats(),然后在ModelConfig联合类型(models.py:263)和get_model()(models.py:875)里注册。
注意 AbstractModel.query() 的返回契约:
python
# 单条
{"message": str, "tool_calls": list | None, "thinking_blocks": list | None}
# 多条(n>1)
list[dict]
10.5 换执行后端
EnvironmentConfig.deployment 直接换成 SWE-ReX 的其它 DeploymentConfig:
yaml
env:
deployment:
type: modal
...
SWE-agent 侧不需要改代码,因为 SWEEnv 只依赖 AbstractDeployment 接口。Docker 之外的选项包括 Local、Modal、Fargate 等(具体字段以 swerex.deployment.config 为准)。
10.6 加生命周期钩子
三类 hook:
| 基类 | 位置 | 能做什么 |
|---|---|---|
RunHook |
run/hooks/abstract.py |
batch/单实例开始结束、实例完成、提交评测 |
AbstractAgentHook |
agent/hooks/abstract.py |
模型查询前后、动作生成/执行、每步开始结束 |
EnvHook |
environment/hooks/abstract.py |
deployment 启动、仓库复制、环境启动、关闭 |
SaveApplyPatchHook 和 SweBenchEvaluate 都是 RunHook 的实现,可以直接照抄。
10.7 多尝试 + 评审
如果单次尝试不够,用 RetryAgent:
yaml
agent:
type: retry
agent_configs:
- ... # 第一次尝试的 DefaultAgentConfig
retry_loop:
type: chooser # 或 score
...
reviewer.py 提供:
ChooserRetryLoop:把多次尝试的轨迹交给评审模型选一个;ScoreRetryLoop:给每次尝试打分,选最高分;Preselector:先粗筛,降低评审成本。
这条路线在论文复现配置里很常见,但成本会随尝试次数线性增长。
11. 关键代码阅读路线
如果只想快速吃透源码,建议按下面顺序读(每步都给出入口):
| 顺序 | 文件 | 重点 |
|---|---|---|
| 1 | sweagent/run/run.py:70 |
CLI 子命令分发(get_cli() 在 :37),先建立全局地图 |
| 2 | sweagent/run/run_batch.py:75 |
RunBatchConfig,看清所有可配项 |
| 3 | sweagent/run/run_batch.py:240 |
main() / run_instance() / _run_instance(),批量编排 |
| 4 | sweagent/run/batch_instances.py:173 |
from_swe_bench(),理解镜像名与 repo 来源 |
| 5 | sweagent/run/batch_instances.py:114 |
to_full_batch_instance(),理解 BatchInstance |
| 6 | sweagent/environment/swe_env.py:109 |
start() / reset(),环境如何准备 |
| 7 | sweagent/tools/tools.py:252 |
install() / _install_commands(),工具如何进容器 |
| 8 | sweagent/agent/agents.py:561 |
setup(),提示词与历史如何初始化 |
| 9 | sweagent/agent/agents.py:1006 |
forward(),模型查询 + 解析 + 执行 |
| 10 | sweagent/agent/agents.py:1062 |
forward_with_handling(),错误重试矩阵 |
| 11 | sweagent/agent/agents.py:936 |
handle_action(),命令执行与提交检测 |
| 12 | sweagent/agent/agents.py:870 |
handle_submission(),补丁如何读回 |
| 13 | sweagent/agent/models.py:578 |
LiteLLMModel,成本/限流/重试 |
| 14 | sweagent/tools/parsing.py:371 |
FunctionCallingParser,动作如何解析 |
| 15 | sweagent/run/hooks/swe_bench_evaluate.py:19 |
SweBenchEvaluate,内置评测路径 |
| 16 | swebench.harness.grading(第三方包) |
get_eval_report() / get_resolution_status() |
配套阅读:
docs/background/architecture.md:官方架构说明(比本文更概览);config/default.yaml:最小可用配置;config/benchmarks/*.yaml:论文/榜单配置,能看到retry、reviewer、多模型 fallback 的真实用法;tests/(若仓库包含):每个模块的边界条件。
12. 已知坑与版本注意事项
12.1 版本约束
sweagent/__init__.py要求 Python >= 3.11;- SWE-ReX:
sweagent/__init__.py:17-18的运行时下限检查仍是 1.2.0 、推荐 1.2.1 ;但 v1.1.0 的pyproject.toml:60安装约束已经写成swe-rex>=1.4.0(本机实际 1.4.0,兼容); - 版本不匹配时,
get_rex_version()/get_rex_commit_hash()会写进.traj的info,排查环境问题时先看这里。
12.2 从 1.0 迁移的坑
RunSingleConfig._get_auto_correct() 明确列出已废弃参数:
| 旧参数 | 新写法 |
|---|---|
--model |
--agent.model.name |
--per_instance_cost_limit |
--agent.model.per_instance_cost_limit |
--config_file |
--config |
--data_path |
--problem_statement.path 或 --problem_statement.github_url |
--repo_path |
--env.repo.path |
如果启动时看到 Auto-correct suggestions 面板,说明用了旧参数。
12.3 默认配置不包含模型
config/default.yaml 只有 templates/tools/history,没有 agent.model。直接:
bash
sweagent run-batch --instances.type swe_bench
会因为 model 必填而失败。必须补:
bash
--agent.model.name ... --agent.model.api_key ...
12.4 function_calling 不是所有模型都支持
LiteLLMModel.__init__ 会检查:
python
if tools.use_function_calling and not litellm.utils.supports_function_calling(model=name):
logger.warning("... use parse_function='thought_action' instead")
如果模型实际不支持但仍走 function calling,常见表现是:
- 模型返回纯文本,
tool_calls为空; - 解析器报格式错误,反复 requery 后
exit_format; - 补丁为空。
解决:换 thought_action,或换支持 tool calling 的模型。
12.5 30 秒命令超时
ToolConfig.execution_timeout=30。跑测试、装依赖、编译很容易超过 30 秒。三种处理:
- 把长任务放到
env.post_startup_commands(默认 500 秒超时); - 调大
agent.tools.execution_timeout; - 让 Agent 用
timeout/后台任务/日志文件绕开(不推荐,容易引入竞态)。
连续 3 次超时会直接退出实例(max_consecutive_execution_timeouts=3)。
12.6 git fetch 可能需要网络
PreExistingRepoConfig 的 reset 命令包含 git fetch。在离线容器里,如果 base_commit 已在本地,通常仍能继续;但如果 git fetch 以非零退出,_reset_repository() 用的是 check="raise",会直接失败。
处理:
- 给容器配可用的 git 镜像/代理;
- 或自定义 repo 配置,把
git fetch从 reset 命令里去掉(需要改repo.py或用自己的Repo实现)。
12.7 成本统计为 0 不一定是免费
litellm.cost_calculator.completion_cost() 对未注册价格的模型会抛异常,代码里降级为 cost=0。所以:
total_cost: 0只表示「没算出来」,不代表真的没花钱;- 想准确统计,给 litellm 注册模型价格(
litellm_model_registry),或接自己的计费。
12.8 cache_control 的兼容性
CacheControlHistoryProcessor 会给消息加 cache_control 字段,主要用于 Anthropic 的 prompt caching。非 Anthropic 模型可能:
- 忽略该字段;
- 或被某些严格校验的 OpenAI 兼容服务拒绝。
如果遇到 400,先把 history_processors 里的 cache_control 去掉再试。
12.9 多线程下不要共享可变配置
源码里大量 model_copy(deep=True) 不是多余:ToolConfig、ModelConfig、DeploymentConfig 都会在实例之间共享引用。自定义扩展时如果直接改 self.config.xxx,很可能污染其它线程。照抄现有的深拷贝习惯。
12.10 .traj 存在但 .pred 缺失
should_skip() 只看 .traj,不看 .pred。如果进程在「写完 traj、还没写 pred」之间被杀,下次会跳过该实例,导致 preds.json 缺条目。
处理:
bash
# 方法一:删掉该实例的 traj
rm runs/exp/<instance_id>/<instance_id>.traj
# 方法二:强制重跑
sweagent run-batch ... --redo_existing True
12.11 评测与重跑不要同时开
instances.evaluate=True + redo_existing=True 会直接抛 ValueError,因为增量提交的旧预测会污染最终结果。正确做法:
text
先跑 Agent(不 evaluate)→ 确认 preds.json 完整 → 再单独跑 harness
附录 A:核心符号速查
| 符号 | 位置 | 一句话 |
|---|---|---|
RunBatchConfig |
run/run_batch.py:75 |
批量运行的全部配置 |
RunBatch.run_instance |
run/run_batch.py:291 |
单实例调度与异常隔离 |
SWEBenchInstances |
run/batch_instances.py:270 |
SWE-bench 数据集加载 |
SimpleBatchInstance.from_swe_bench |
run/batch_instances.py:173 |
数据集行 → 镜像名/repo |
SWEEnv.start |
environment/swe_env.py:109 |
启动环境 |
SWEEnv.communicate |
environment/swe_env.py:197 |
执行一条命令 |
ToolHandler.install |
tools/tools.py:252 |
安装工具 bundle |
ToolHandler.get_state |
tools/tools.py:337 |
收集工具状态 |
DefaultAgent.setup |
agent/agents.py:561 |
初始化提示词/历史/工具 |
DefaultAgent.forward |
agent/agents.py:1006 |
查询模型 + 解析 + 执行 |
DefaultAgent.forward_with_handling |
agent/agents.py:1062 |
错误重试 |
DefaultAgent.handle_action |
agent/agents.py:936 |
执行动作 |
DefaultAgent.handle_submission |
agent/agents.py:870 |
读回补丁 |
LiteLLMModel |
agent/models.py:578 |
模型调用/成本/重试 |
FunctionCallingParser |
tools/parsing.py:371 |
function calling 解析 |
SweBenchEvaluate |
run/hooks/swe_bench_evaluate.py:19 |
sb-cli 评测 hook |
save_predictions |
run/common.py:370 |
写 .pred |
merge_predictions |
run/merge_predictions.py:13 |
合并 preds.json |
附录 B:术语表
| 术语 | 含义 |
|---|---|
| ACI | Agent-Computer Interface,Agent 与计算机交互的接口;SWE-agent 用「bash 命令 + 文档」实现 |
| trajectory | 一次任务的全部步骤记录(动作、观察、模型输出、状态) |
| history | 真正发给模型的消息序列,可能经过裁剪/加工 |
| bundle | 一组工具的集合,包含 config.yaml、bin/、install.sh |
| state | 每步结束后从容器收集的附加信息(cwd、diff 等) |
| harness | SWE-bench 官方评测程序,负责应用补丁、跑测试、判 resolved |
| F2P / P2P | FAIL_TO_PASS / PASS_TO_PASS,SWE-bench 的两组金标准测试 |
| resolved | F2P 全过且 P2P 全过(RESOLVED_FULL) |
| preds.json | SWE-bench 评测输入,instance_id → 补丁的映射 |
结语
SWE-agent 的代码量不大,但把「Agent 运行时」这件事拆得很干净:
- 编排 (
RunBatch)只关心实例、并发、产物; - 环境 (
SWEEnv+ SWE-ReX)只关心容器和命令; - Agent (
DefaultAgent)只关心「模型输出 → 动作 → 观察 → 历史」; - 工具(bundle)只关心「命令怎么实现、怎么文档化」;
- 评测交给外部 harness,不耦合进 Agent。
理解这条边界之后,无论是换模型、加工具、改提示词,还是接自己的评测集,都只需要动对应的那一层。对本仓库而言,这套结构也解释了为什么 SWE-agent 与 OpenCode 可以共用同一份 preds.json 和同一套 harness:Agent 只负责产补丁,判分标准是统一的。