The apply_patch 工具允许 GPT-5.1 使用结构化差异在你的代码库中创建、更新和删除文件。模型不再只是建议修改,而是发出补丁操作,由你的应用程序负责应用并报告结果,从而实现迭代的多步代码编辑工作流。
何时使用
一些你会使用 apply_patch 的常见场景:
- 多文件重构 —— 跨多个文件重命名符号、提取辅助函数或重新组织模块。
- Bug 修复 —— 让模型既能诊断问题,也能输出精确的补丁。
- 测试与文档生成 —— 在修改代码的同时创建新的测试文件、测试固件和文档。
- 迁移与机械编辑 —— 执行重复性的结构化更新(API 迁移、类型标注、格式修复等)。
如果你能用文本描述你的代码仓库和预期变更,apply_patch 通常就能生成相应的差异。
将 apply patch 工具与 Responses API 结合使用
在宏观层面上,使用 apply_patch 与 Responses API 的流程如下:
- 使用以下参数调用 Responses API:
apply_patch工具- 在您的
input中提供有关可用文件(或摘要)的上下文信息,或者为模型提供用于探索文件系统的工具。 - 启用该工具
tools=[{"type": "apply_patch"}].
- 在您的
- 让模型返回一个或多个补丁操作
- 响应输出包含一个或多个
apply_patch_callobjects. - 每次调用描述一个单一的文件操作:创建、更新或删除。
- 响应输出包含一个或多个
- 在您的环境中应用补丁
- 运行一个补丁执行程序或脚本来:
- 解释
operation每个操作的 diffapply_patch_call. - 将补丁应用到您的工作目录或代码库。
- 记录每个补丁是否成功,以及任何日志或错误信息。
- 解释
- 运行一个补丁执行程序或脚本来:
- 将补丁结果报告回模型
- 再次调用 Responses API,可以使用
previous_response_id或者通过将对话项传回input. - 为每个
apply_patch_call_output包含一个call_id,并带有一个statusand optionaloutputstring. - 保持
tools=[{"type": "apply_patch"}]事件,以便模型可以在需要时继续编辑。
- 再次调用 Responses API,可以使用
- 让模型继续或解释更改
- 模型可能会发出更多
apply_patch_call操作,或者 - 提供面向用户的说明,解释其更改内容及原因。
- 模型可能会发出更多
示例:使用 Apply Patch Tool 重命名函数
步骤 1:要求模型进行规划并输出补丁
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"
}
}步骤 2:应用补丁并发送结果
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" and include a helpful 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"
}应用补丁操作
| 操作类型 | 目的 | 负载 |
|---|---|---|
create_file | 创建新文件于 path. | diff 是一个表示完整文件内容的 V4A diff。 |
update_file | 修改现有文件于 path. | diff 是一个包含添加、删除或替换的 V4A diff。 |
delete_file | 删除文件于 path. | No diff;完全删除该文件。 |
你的补丁执行器负责解析 V4A diff 格式并应用更改。有关参考实现,请参阅 Python Agents SDK or TypeScript Agents SDK code.
实现 patch harness
当使用 apply_patch 工具时,你不需要提供输入 schema;模型知道如何构造 operation 对象。你的任务是:
- 解析 Response 中的操作
- 扫描 Response 中具有以下特征的项:
type: "apply_patch_call". - For each call, inspect
operation.type,operation.path,以及任何潜在的diff.
- 扫描 Response 中具有以下特征的项:
- 应用文件操作
- For
create_fileandupdate_file,将 V4A 差异应用到文件系统或内存工作区。 - For
delete_file,移除该文件于path. - 记录每个操作是否成功,以及任何日志或错误消息。
- For
- 返回
apply_patch_call_output事件- For each
call_id,精确发出一个apply_patch_call_output事件包含以下内容:status: "completed"如果操作成功应用。status: "failed"如果遇到错误(包含一段简短的人类可读的output字符串)。
- For each
安全性与健壮性
- 路径验证:防止目录遍历并将编辑限制在允许的目录内。
- 备份:考虑在应用补丁前备份文件(或在副本中操作)。
- 错误处理:始终返回一个
failed状态并在 patch 无法应用时提供信息丰富的output字符串。 - 原子性:决定是否需要“全有或全无”语义(任何补丁失败即回滚),或者是单文件级别的成功/失败。
结合 Agents SDK 使用 apply patch 工具
或者,你也可以使用 Apps SDK 来使用 apply patch 工具。你仍然需要实现处理实际文件操作的 harness,但你可以使用 applyDiff 函数来处理 diff。
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 上找到完整的可用示例。
如何结合 Agents SDK 在 TypeScript 中使用 apply patch 工具的示例
如何结合 Agents SDK 在 Python 中使用 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):"
}然后模型可以根据这些错误消息调整后续的 diff(例如,通过在你的 prompt 中重新读取文件或简化更改)。
最佳实践
- 提供清晰的文件上下文
- 调用 Responses API 时,请包含文件的内联快照(如示例所示),或者为模型提供探索文件系统的工具(例如
shell工具)。
- 调用 Responses API 时,请包含文件的内联快照(如示例所示),或者为模型提供探索文件系统的工具(例如
- 考虑结合
shell工具- 使用。当与
shell工具结合使用时,模型可以探索文件系统目录、读取文件和 grep 关键词,从而实现智能代理式的文件发现和编辑。
- 使用。当与
- 鼓励小而集中的 diffs
- 在系统指令中,引导模型进行最小化、有针对性的编辑,而不是大规模重写。
- 确保更改顺利应用
- 在应用一系列 patch 之后,运行测试或 linter,并将失败信息反馈到下一个
input中,以便模型进行修复。
- 在应用一系列 patch 之后,运行测试或 linter,并将失败信息反馈到下一个
使用说明
| API 可用性 | 支持的模型 |
|---|---|
| GPT-5.5 GPT-5.4 GPT-5.2 GPT-5.1 |