apply_patch 工具允许 GPT-5.1 使用结构化差异在您的代码库中创建、更新和删除文件。模型不仅是建议编辑,还会发出补丁操作,由您的应用程序应用并反馈结果,从而实现迭代式的多步代码编辑工作流。
使用场景
使用 apply_patch 的一些常见场景
- 多文件重构 —— 同时重命名符号、提取辅助函数或重组多个模块。
- Bug 修复 —— 让模型诊断问题并生成精确的补丁。
- 测试与文档生成 —— 在修改代码的同时创建新的测试文件、固件和文档。
- 迁移与机械化编辑 —— 应用重复的、结构化的更新(API 迁移、类型注解、格式修复等)。
如果您能用文字描述代码库和期望的变更,apply_patch 通常就能生成相应的补丁(diffs)。
在 Responses API 中使用 apply patch 工具
概括来说,在 Responses API 中使用 apply_patch 的流程如下:
- 调用带有
apply_patch工具的 Responses API- 在
input中向模型提供可用文件的上下文(或摘要),或为模型提供用于探索文件系统的工具。 - 通过
tools=[{"type": "apply_patch"}]启用该工具。
- 在
- 让模型返回一个或多个补丁操作
- Response 输出中包含一个或多个
apply_patch_call对象。 - 每个调用描述一个文件操作:创建、更新或删除。
- Response 输出中包含一个或多个
- 在您的环境中应用补丁
- 运行补丁执行脚本或工具,执行以下操作:
- 解析每个
apply_patch_call的operation差异。 - 将补丁应用到您的工作目录或代码库。
- 记录每个补丁是否成功,以及任何日志或错误信息。
- 解析每个
- 运行补丁执行脚本或工具,执行以下操作:
- 将补丁结果反馈给模型
- 再次调用 Responses API,可以使用
previous_response_id,或者将您的对话项传回input。 - 为每个
call_id包含一个apply_patch_call_output事件,附带status和可选的output字符串。 - 保持
tools=[{"type": "apply_patch"}]开启,以便模型在必要时继续编辑。
- 再次调用 Responses API,可以使用
- 让模型继续执行或解释更改
- 模型可能会发布更多
apply_patch_call操作,或者 - 提供对所更改内容及其原因的人性化解释。
- 模型可能会发布更多
示例:使用 Apply Patch 工具重命名函数
第一步:请求模型规划并发出补丁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from openai import OpenAI
client = OpenAI()
# For brevity, we are including file context in the example input.
# Most agentic use cases should instead equip the model with tools
# for exploring file system state.
RESPONSE_INPUT = """
The user has the following files:
<BEGIN_FILES>
===== lib/fib.py
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
===== run.py
from lib.fib import fib
def main():
print(fib(42))
<END_FILES>
You are a helpful coding assistant that should assist the user with whatever they
ask.
User query:
Help me rename the fib() function to fibonacci()
"""
response = client.responses.create(
model="gpt-5.1",
input=RESPONSE_INPUT,
tools=[{"type": "apply_patch"}],
)
# response.output may contain multiple apply_patch_call entries, e.g.:
# - update lib/fib.py
# - update run.py
patch_calls = [
item for item in response.output
if item["type"] == "apply_patch_call"
]apply_patch_call 对象示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"id": "apc_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe",
"type": "apply_patch_call",
"status": "completed",
"call_id": "call_Rjsqzz96C5xzPb0jUWJFRTNW",
"operation": {
"type": "update_file",
"diff": "
@@
-def fib(n):
+def fibonacci(n):
if n <= 1:
return n
- return fib(n-1) + fib(n-2) + return fibonacci(n-1) + fibonacci(n-2),
",
"path": "lib/fib.py"
}
}第二步:应用补丁并反馈结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from apply_patch_harness import apply_operation # your implementation
results = []
for call in patch_calls:
op = call["operation"]
success, maybe_log_output = apply_operation(op)
results.append({
"type": "apply_patch_call_output",
"call_id": call["call_id"],
"status": "completed" if success else "failed",
"output": maybe_log_output,
})
followup = client.responses.create(
model="gpt-5.1",
previous_response_id=response.id,
input=results,
tools=[{"type": "apply_patch"}],
)如果补丁失败(例如,文件未找到),设置 status: "failed" 并包含一个有帮助的 output 字符串,以便模型可以进行恢复。
1
2
3
4
5
6
{
"type": "apply_patch_call_output",
"call_id": "call_cNWm41dB3RyQcLNOVTIPBWZU",
"status": "failed",
"output": "Could not apply patch to lib/foo.py — file not found on disk"
}应用补丁的操作
| 操作类型 | 目的 | 载荷(Payload) |
|---|---|---|
create_file | 在 path 处创建一个新文件。 | diff 是一个表示完整文件内容的 V4A 差异。 |
update_file | 修改在 path 处存在的现有文件。 | diff 是一个包含添加、删除或替换操作的 V4A 差异。 |
delete_file | 移除在 path 处的文件。 | 没有 diff;直接删除整个文件。 |
您的补丁执行器负责解析 V4A 差异格式并应用更改。参考实现,请查看 Python Agents SDK 或 TypeScript Agents SDK 代码。
实现补丁执行器
使用 apply_patch 工具时,无需提供输入模式;模型知道如何构建 operation 对象。您的工作是:
- 从 Response 中解析操作
- 扫描 Response 中
type: "apply_patch_call"的项。 - 对于每个调用,检查
operation.type、operation.path和任何可能的diff。
- 扫描 Response 中
- 应用文件操作
- 对于
create_file和update_file,将 V4A 差异应用到文件系统或内存工作区。 - 对于
delete_file,移除path处的文件。 - 记录每个操作是否成功,并捕获任何日志或错误信息。
- 对于
- 返回
apply_patch_call_output事件- 对于每个
call_id,精确发送一个apply_patch_call_output事件,包含:- 如果操作成功应用,则为
status: "completed"。 - 如果您遇到错误,则为
status: "failed"(包含一个简短易懂的output字符串)。
- 如果操作成功应用,则为
- 对于每个
安全与鲁棒性
- 路径验证:防止目录遍历攻击,并将编辑限制在允许的目录内。
- 备份:在应用补丁前,考虑备份文件(或在临时副本上工作)。
- 错误处理:当补丁无法应用时,始终返回
failed状态和一条信息量充足的output字符串。 - 原子性:决定您想要“全有或全无”的语义(若任一补丁失败则回滚),还是基于每个文件的成功/失败处理。
在 Agents SDK 中使用 apply patch 工具
或者,您也可以使用 Agents SDK 来使用 apply patch 工具。您仍然需要实现处理实际文件操作的执行器,但可以使用 applyDiff 函数来处理差异的处理过程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { applyDiff, Agent, run, applyPatchTool, Editor } from "@openai/agents";
class WorkspaceEditor implements Editor {
async createFile(operation) {
// convert the diff to the file content
const content = applyDiff("", operation.diff, "create");
// write the file content to the file system
return { status: "completed", output: `Created ${operation.path}` };
}
async updateFile(operation) {
// read the file content from the file system
const current = "";
// convert the diff to the new file content
const newContent = applyDiff(current, operation.diff);
// write the updated file content to the file system
return { status: "completed", output: `Updated ${operation.path}` };
}
async deleteFile(operation) {
// delete the file from the file system
return { status: "completed", output: `Deleted ${operation.path}` };
}
}
const editor = new WorkspaceEditor();
const agent = new Agent({
name: "Patch Assistant",
model: "gpt-5.1",
instructions: "You can edit files inside the /tmp directory using the apply_patch tool.",
tools: [
applyPatchTool({
editor,
// could also be a function for you to determine if approval is needed
needsApproval: true,
onApproval: async (_ctx, _approvalItem) => {
// create your own approval logic
return { approve: true };
},
}),
],
});
const result = await run(
agent,
"Create tasks.md with a shopping checklist of 5 entries."
);
console.log(`\nFinal response:\n${result.finalOutput}`);您可以在 GitHub 上找到完整的运行示例。
如何在 TypeScript 中通过 Agents SDK 使用 apply patch 工具的示例
如何在 Python 中通过 Agents SDK 使用 apply patch 工具的示例
处理常见错误
使用 status: "failed" 加上清晰的 output 消息来帮助模型进行恢复。
1
2
3
4
5
6
{
"type": "apply_patch_call_output",
"call_id": "call_abc",
"status": "failed",
"output": "Error: File not found at path 'lib/baz.py'"
}1
2
3
4
5
6
{
"type": "apply_patch_call_output",
"call_id": "call_abc",
"status": "failed",
"output": "Error: Invalid Context:\n@@ def fib(n):"
}模型随后可以根据这些错误信息调整后续的补丁(例如,通过重新读取提示词中的文件或简化变更)。
最佳实践
- 提供清晰的文件上下文
- 当您调用 Responses API 时,可以包含文件的内联快照(如示例所示),或者为模型提供探索文件系统的工具(如
shell工具)。
- 当您调用 Responses API 时,可以包含文件的内联快照(如示例所示),或者为模型提供探索文件系统的工具(如
- 考虑与
shell工具结合使用- 当与
shell工具结合使用时,模型可以探索文件系统目录、读取文件并使用 grep 搜索关键字,从而实现智能化的文件发现与编辑。
- 当与
- 鼓励小巧、聚焦的补丁
- 在您的系统指令中,引导模型进行最小化、针对性的编辑,而不是进行大规模的重写。
- 确保变更能干净地应用
- 在一系列补丁之后,运行您的测试或代码检查工具,并将失败结果反馈到下一个
input中,以便模型进行修复。
- 在一系列补丁之后,运行您的测试或代码检查工具,并将失败结果反馈到下一个
使用说明
| API 可用性 | 支持的模型 |
|---|---|
| GPT-5.5 GPT-5.4 GPT-5.2 GPT-5.1 |