搭配 Responses API 使用 apply_patch,讓模型以結構化差異描述要建立、更新或刪除的檔案。你的應用程式負責執行每項操作並傳回結果。以下範例使用 gpt-6-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-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-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-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-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-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-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-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-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-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-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-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-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 中回報失敗項目,讓模型修正問題。