在 Responses API 中使用 apply_patch,模型就可以通过结构化差异提出创建、更新和删除文件的建议。您的应用程序负责执行每项操作并返回结果。本文示例使用 gpt-6.2-astra。
您可以使用 apply_patch 完成以下任务:
- 多文件重构:一次性在多个文件中重命名符号、提取辅助函数或重新组织模块。
- 修复错误:让模型诊断问题并生成精确的补丁。
- 生成测试和文档:在修改代码的同时创建测试文件、测试夹具和文档。
- 迁移和批量修改:按统一规则执行重复性更新,例如迁移 API、添加类型注解或修正格式。
如果您能用文字描述代码仓库和所需的更改,apply_patch 通常就能生成相应的差异。
在 Responses API 中使用 apply_patch 的基本流程如下:
- 调用 Responses API 并启用
apply_patch 工具
- 在
input 中向模型提供可用文件的上下文或摘要,也可以向模型提供用于浏览文件系统的工具。
- 使用
tools=[{"type": "apply_patch"}] 启用该工具。
- 让模型返回一个或多个补丁操作
- 响应的输出包含一个或多个
apply_patch_call 对象。
- 每次调用描述对一个文件执行的一项操作:创建、更新或删除。
- 在您的环境中应用补丁
- 运行补丁执行框架或脚本,完成以下操作:
- 解析
operation 中的差异,对每个 apply_patch_call 分别处理。
- 将补丁应用到工作目录或代码仓库。
- 记录每个补丁是否应用成功,以及相关日志或错误消息。
- 将补丁执行结果反馈给模型
- 再次调用 Responses API,使用
previous_response_id,或将对话中的各项内容重新传入 input。
- 返回
apply_patch_call_output 事件,每个 call_id 对应一个事件,其中包含 status 和可选的 output 字符串。
- 保留
tools=[{"type": "apply_patch"}],以便模型在需要时继续编辑。
- 让模型继续编辑或解释更改
- 模型可以继续发起
apply_patch_call 操作,
- 也可以向用户说明修改了哪些内容以及修改的原因。
第 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
35import OpenAI from "openai";
// Application-owned helper; see "Implementing the patch harness" in the guide.
// This demo only applies exact updates to the two in-memory files below.
import { applyOperation } from "../../support/apply-patch.mjs";
const client = new OpenAI();
const 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
print(fib(42))
`,
};
const fileContext = `The user has the following files:
<BEGIN_FILES>
${Object.entries(files)
.map(([path, content]) => `===== ${path}\n${content}`)
.join("\n")}
<END_FILES>
Help me rename the fib() function to fibonacci().`;
let response = await client.responses.create({
model: "gpt-6.2-astra",
input: fileContext,
tools: [{ type: "apply_patch" }],
});
let patchCalls = response.output.filter(
(item) => item.type === "apply_patch_call"
);
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
42from 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-6.2-astra",
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.model_dump() for item in response.output if item.type == "apply_patch_call"
]
1
2
3
4
5
6
7
8response, err := client.Responses.New(ctx, responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(responseInput)},
Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},
})
if err != nil {
return err
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ApplyPatchTool;
import com.openai.models.responses.ResponseCreateParams;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.input(
"Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.")
.addTool(ApplyPatchTool.builder().build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.applyPatchCall().stream())
.forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10
11
12
13require "openai"
client = OpenAI::Client.new
files = {
"lib/fib.py" => "def fib(n):\n if n <= 1:\n return n\n return fib(n-1) + fib(n-2)\n",
"run.py" => "from lib.fib import fib\n\ndef main():\n print(fib(42))\n"
}
context = files.map { |path, content| "===== #{path}\n#{content}" }.join
response = client.responses.create(
model: "gpt-6.2-astra",
input: "The user has the following files:\n<BEGIN_FILES>\n#{context}<END_FILES>\nHelp me rename fib() to fibonacci() in both existing files.",
tools: [{ type: :apply_patch }]
)
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
21
22
23
24
25
26
27
28for (let turn = 0; patchCalls.length > 0; turn++) {
if (turn === 8) throw new Error("Patch workflow exceeded eight tool turns.");
const results = patchCalls.map((call): OpenAI.Responses.ResponseInputItem => {
const { success, output } = applyOperation(files, call.operation);
return {
type: "apply_patch_call_output",
call_id: call.call_id,
status: success ? "completed" : "failed",
output,
};
});
response = await client.responses.create({
model: "gpt-6.2-astra",
previous_response_id: response.id,
input: results,
tools: [{ type: "apply_patch" }],
});
patchCalls = response.output.filter(
(item) => item.type === "apply_patch_call"
);
}
console.log(response.output_text);
for (const [path, content] of Object.entries(files)) {
process.stdout.write(`===== ${path}\n${content}`);
}
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
33from apply_patch_harness import apply_operation # your implementation
for turn in range(9):
if response.status != "completed":
raise RuntimeError(f"Patch response ended with status {response.status}")
if not patch_calls:
break
if turn == 8:
raise RuntimeError("Patch workflow exceeded eight tool turns")
results = []
for call in patch_calls:
success, log_output = apply_operation(call["operation"])
results.append(
{
"type": "apply_patch_call_output",
"call_id": call["call_id"],
"status": "completed" if success else "failed",
"output": log_output,
}
)
response = client.responses.create(
model="gpt-6.2-astra",
previous_response_id=response.id,
input=results,
tools=[{"type": "apply_patch"}],
)
patch_calls = [
item.model_dump() for item in response.output if item.type == "apply_patch_call"
]
print(response.output_text)
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
38for turn := 0; ; turn++ {
if response.Status != responses.ResponseStatusCompleted {
return fmt.Errorf("response ended with status %s", response.Status)
}
patchCalls := make([]responses.ResponseOutputItemUnion, 0)
for _, item := range response.Output {
if item.Type == "apply_patch_call" {
patchCalls = append(patchCalls, item)
}
}
if len(patchCalls) == 0 {
fmt.Println(response.OutputText())
return nil
}
if turn == 8 {
return fmt.Errorf("patch workflow exceeded eight tool turns")
}
results := make(responses.ResponseInputParam, 0, len(patchCalls))
for _, call := range patchCalls {
success, logOutput := applyOperation(files, call.Operation)
status := "completed"
if !success {
status = "failed"
}
result := responses.ResponseInputItemParamOfApplyPatchCallOutput(call.CallID, status)
result.OfApplyPatchCallOutput.Output = openai.String(logOutput)
results = append(results, result)
}
response, err = client.Responses.New(ctx, responses.ResponseNewParams{
Model: "gpt-6.2-astra",
PreviousResponseID: openai.String(response.ID),
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: results},
Tools: []responses.ToolUnionParam{{OfApplyPatch: &responses.ApplyPatchToolParam{}}},
})
if err != nil {
return err
}
}
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
27import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ApplyPatchTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofApplyPatchCallOutput(
ResponseInputItem.ApplyPatchCallOutput.builder()
.callId(System.getenv("OPENAI_EXAMPLE_APPLY_PATCH_CALL_ID"))
.status(ResponseInputItem.ApplyPatchCallOutput.Status.COMPLETED)
.output("Patch applied successfully.")
.build())))
.previousResponseId(System.getenv("OPENAI_EXAMPLE_PREVIOUS_RESPONSE_ID"))
.addTool(ApplyPatchTool.builder().build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
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
289.times do |turn|
raise "Response ended with status #{response.status}" unless response.status == OpenAI::Responses::ResponseStatus::COMPLETED
patch_calls = response.output.grep(OpenAI::Models::Responses::ResponseApplyPatchToolCall)
if patch_calls.empty?
puts(response.output_text)
break
end
raise "Patch workflow exceeded eight tool turns" if turn == 8
# apply_operation is application-owned; see "Implementing the patch harness" in the guide.
results = patch_calls.map do |call|
success, output = apply_operation(files, call.operation)
{
type: :apply_patch_call_output,
call_id: call.call_id,
status: success ? :completed : :failed,
output: output
}
end
response = client.responses.create(
model: "gpt-6.2-astra",
previous_response_id: response.id,
input: results,
tools: [{ type: :apply_patch }]
)
end
files.each { |path, content| print("===== #{path}\n#{content}") }
如果补丁应用失败(例如找不到文件),请设置 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"
}
| 操作类型 |
用途 |
载荷 |
create_file |
在 path 处创建新文件。 |
diff 是表示完整文件内容的 V4A 差异。 |
update_file |
修改 path 处的现有文件。 |
diff 是包含新增、删除或替换内容的 V4A 差异。 |
delete_file |
删除 path 处的文件。 |
不包含 diff,直接删除整个文件。 |
您的补丁执行框架负责解析 V4A 格式的差异并应用更改。参考实现请见 Python Agents SDK 或 TypeScript Agents SDK 的代码。
使用 apply_patch 工具时,您无需提供输入模式,模型知道如何构造 operation 对象。您需要完成以下工作:
- 从响应中解析操作
- 在响应中查找满足
type: "apply_patch_call" 的项。
- 对于每次调用,检查
operation.type、operation.path 以及可能存在的 diff。
- 执行文件操作
- 对于
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 使用补丁工具。您仍需实现执行框架来处理实际的文件操作,但可以使用 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99import {
mkdirSync,
realpathSync,
lstatSync,
readFileSync,
writeFileSync,
unlinkSync,
} from "node:fs";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import {
applyDiff,
Agent,
run,
applyPatchTool,
type Editor,
type ApplyPatchResult,
} from "@openai/agents";
class WorkspaceEditor implements Editor {
root: string;
constructor(root = "workspace") {
mkdirSync(root, { recursive: true });
this.root = realpathSync(root);
}
path(name: string) {
const target = resolve(this.root, name);
const relativePath = relative(this.root, target);
if (
!relativePath ||
isAbsolute(relativePath) ||
relativePath === ".." ||
relativePath.startsWith(`..${sep}`)
) {
throw new Error("Patch paths must stay inside the workspace");
}
let current = this.root;
for (const part of relativePath.split(sep)) {
current = join(current, part);
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) {
throw new Error("Patch paths must not traverse symbolic links");
}
}
return target;
}
async createFile(
operation: Parameters<Editor["createFile"]>[0]
): Promise<ApplyPatchResult> {
const path = this.path(operation.path);
const content = applyDiff("", operation.diff, "create");
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content, { encoding: "utf8", flag: "wx" });
return { status: "completed", output: `Created ${operation.path}` };
}
async updateFile(
operation: Parameters<Editor["updateFile"]>[0]
): Promise<ApplyPatchResult> {
const path = this.path(operation.path);
const content = applyDiff(readFileSync(path, "utf8"), operation.diff);
writeFileSync(path, content, "utf8");
return { status: "completed", output: `Updated ${operation.path}` };
}
async deleteFile(
operation: Parameters<Editor["deleteFile"]>[0]
): Promise<ApplyPatchResult> {
unlinkSync(this.path(operation.path));
return { status: "completed", output: `Deleted ${operation.path}` };
}
}
const editor = new WorkspaceEditor();
const agent = new Agent({
name: "Patch Assistant",
model: "gpt-6.2-astra",
instructions:
"Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",
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}`);
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67from pathlib import Path
from agents import Agent, ApplyPatchTool, Runner, apply_diff
class WorkspaceEditor:
def __init__(self, root="workspace"):
self.root = Path(root).resolve()
self.root.mkdir(parents=True, exist_ok=True)
def _path(self, name):
path = self.root / name
resolved = path.resolve()
if resolved == self.root or not resolved.is_relative_to(self.root):
raise ValueError("Patch paths must stay inside the workspace")
return path
async def create_file(self, operation):
content = apply_diff("", operation.diff, mode="create")
path = self._path(operation.path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("x", encoding="utf-8") as file:
file.write(content)
return {"status": "completed", "output": f"Created {operation.path}"}
async def update_file(self, operation):
path = self._path(operation.path)
content = apply_diff(path.read_text(encoding="utf-8"), operation.diff)
path.write_text(content, encoding="utf-8")
return {"status": "completed", "output": f"Updated {operation.path}"}
async def delete_file(self, operation):
self._path(operation.path).unlink()
return {"status": "completed", "output": f"Deleted {operation.path}"}
editor = WorkspaceEditor()
agent = Agent(
name="Patch Assistant",
model="gpt-6.2-astra",
instructions="Use apply_patch to edit files in the workspace. Supply paths relative to that workspace.",
tools=[
ApplyPatchTool(
editor=editor,
# could also be a function for you to determine if approval is needed
needs_approval=True,
# Implement your own approval logic
on_approval=lambda _ctx, _approval_item: {"approve": True},
),
],
)
async def main():
result = await Runner.run(
agent,
input="Create tasks.md with a shopping checklist of 5 entries.",
)
print(f"\nFinal response:\n{result.final_output}")
if __name__ == "__main__":
import asyncio
asyncio.run(main())
您可以在 GitHub 上找到完整的可运行示例。
在 TypeScript 中通过 Agents SDK 使用补丁工具的示例
在 Python 中通过 Agents SDK 使用补丁工具的示例
使用 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 工具。
- 考虑配合
shell 工具使用
- 配合
shell 工具,模型可以浏览文件系统目录、读取文件并使用 grep 搜索关键词,从而自主查找和编辑文件。
- 让模型生成范围小、目标明确的差异
- 在系统指令中引导模型针对具体目标做尽可能少的修改,避免大规模重写。
- 确认补丁已正确应用
- 应用一系列补丁后,运行测试或代码检查工具,并在下一次
input 中反馈失败信息,以便模型修复问题。