Allow models to propose structured diffs that your integration applies.
Use apply_patch with the Responses API to propose file creations, updates, and deletions as structured diffs. Your application applies each operation and returns its result. The examples use gpt-6.2-astra.
When to use
You can use apply_patch for the following tasks.
Multi-file refactors. Rename symbols, extract helpers, or reorganize modules across many files at once.
Bug fixes. Have the model both diagnose issues and emit precise patches.
Tests & docs generation. Create new test files, fixtures, and documentation alongside code changes.
If you can describe your repo and desired change in text, apply_patch can usually generate the corresponding diffs.
Use apply patch tool with Responses API
At a high level, using apply_patch with the Responses API looks like this:
Call the Responses API with the apply_patch tool
Provide the model with context about available files (or a summary) in your input, or give the model tools for exploring your file system.
Enable the tool with tools=[{"type": "apply_patch"}].
Let the model return one or more patch operations
The Response output includes one or more apply_patch_call objects.
Each call describes a single file operation: create, update, or delete.
Apply patches in your environment
Run a patch harness or script that:
Interprets the operation diff for each apply_patch_call.
Applies the patch to your working directory or repo.
Records whether each patch succeeded and any logs or error messages.
Report patch results back to the model
Call the Responses API again, either with previous_response_id or by passing back your conversation items into input.
Include an apply_patch_call_output event for each call_id, with a status and optional output string.
Keep tools=[{"type": "apply_patch"}] so the model can continue editing if needed.
Let the model continue or explain changes
The model may issue more apply_patch_call operations, or
Provide a human-facing explanation of what it changed and why.
Example: Renaming a function with Apply Patch Tool
Step 1: Ask the model to plan and emit patches
Ask the model to plan and emit patches
TypeScript
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";constclient=newOpenAI();constfiles= {"lib/fib.py": `def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)`,"run.py": `from lib.fib import fibprint(fib(42))`,};constfileContext=`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 OpenAIclient = 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.pydef fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)===== run.pyfrom lib.fib import fibdef main(): print(fib(42))<END_FILES>You are a helpful coding assistant that should assist the user with whatever theyask.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.pypatch_calls = [ item.model_dump() for item in response.output if 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
37import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.responses.ApplyPatchTool;import com.openai.models.responses.ResponseCreateParams;// Include the current files so the model can produce applicable updates.// An agent can instead use tools to inspect its workspace.String fileContext = """ 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 print(fib(42)) <END_FILES> Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name. """ .strip();ResponseCreateParams params = ResponseCreateParams.builder() .model("gpt-6.2-astra") .input(fileContext) .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
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
49using System.ClientModel.Primitives;using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Set OPENAI_API_KEY.");ResponsesClient client = new(key);// Include the current files so the model can produce applicable updates.// An agent can instead use tools to inspect its workspace.string fileContext = """The user has the following files:<BEGIN_FILES>===== lib/fib.pydef fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)===== run.pyfrom lib.fib import fibprint(fib(42))<END_FILES>Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.""";CreateResponseOptions options = new() { Model = "gpt-6.2-astra" };options.InputItems.Add(ResponseItem.CreateUserMessageItem(fileContext));options.Tools.Add(ResponseTool.CreateApplyPatchTool());ResponseResult response = await client.CreateResponseAsync(options);if (!response.OutputItems.Any(item => item is ApplyPatchCallItem)){ string text = response.GetOutputText(); if (!string.IsNullOrWhiteSpace(text)) Console.WriteLine(text);}foreach (ResponseItem item in response.OutputItems){ if (item is ApplyPatchCallItem patch) { // Preserve the SDK's wire representation, including call_id and operation. Console.WriteLine(ModelReaderWriter.Write(patch).ToString()); }}#pragma warning restore OPENAI001
1
2
3
4
5
6
7
8
9
10
11
12
13require "openai"client = OpenAI::Client.newfiles = { "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}" }.joinresponse = 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 }])
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
99
100
101
102
103
104
105
106
107
108
109using System.Text.Json;using System.Text.Json.Serialization;using OpenAI.Responses;#pragma warning disable OPENAI001// Replace these illustrative values with the authenticated application's context.await ReturnAppliedPatchAsync("user_123", "resp_123", "apc_123");static CreateResponseOptions CreateOwnedResultOptions( AppliedPatchResult result, string authenticatedUserId, string requestedResponseId, string requestedCallId){ // The caller obtains identity from authentication, never from the receipt or request body. if (string.IsNullOrWhiteSpace(authenticatedUserId) || string.IsNullOrWhiteSpace(result.OwnerId) || !string.Equals(result.OwnerId, authenticatedUserId, StringComparison.Ordinal) || string.IsNullOrWhiteSpace(result.PreviousResponseId) || !string.Equals(result.PreviousResponseId, requestedResponseId, StringComparison.Ordinal) || string.IsNullOrWhiteSpace(result.CallId) || !string.Equals(result.CallId, requestedCallId, StringComparison.Ordinal) || result.Status != "completed" || string.IsNullOrWhiteSpace(result.Output)) { throw new InvalidDataException("An owned, completed patch result with matching IDs is required."); } CreateResponseOptions options = new() { Model = "gpt-6.2-astra", PreviousResponseId = result.PreviousResponseId, }; options.Tools.Add(ResponseTool.CreateApplyPatchTool()); ApplyPatchCallOutputItem output = ResponseItem.CreateApplyPatchCallOutputItem( result.CallId, ApplyPatchCallOutputStatus.Completed); output.Output = result.Output; options.InputItems.Add(output); return options;}static async Task ReturnAppliedPatchAsync( string authenticatedUserId, string requestedResponseId, string requestedCallId){ // A trusted application executor creates this private result after applying the patch. // Do not load a client-uploaded receipt or derive the authenticated identity from it. AppliedPatchResult result = JsonSerializer.Deserialize<AppliedPatchResult>( await File.ReadAllTextAsync("applied-patch.json")) ?? throw new InvalidDataException("Missing application-owned patch result."); CreateResponseOptions options = CreateOwnedResultOptions( result, authenticatedUserId, requestedResponseId, requestedCallId); string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Set OPENAI_API_KEY."); ResponsesClient client = new(key); ResponseResult response = await client.CreateResponseAsync(options); for (int turn = 0; ; turn++) { ApplyPatchCallItem[] calls = response.OutputItems.OfType<ApplyPatchCallItem>().ToArray(); if (calls.Length == 0) { break; } if (turn == 8) { throw new InvalidOperationException("Patch workflow exceeded eight tool turns."); } // A completed receipt authorizes only its original call. New calls need // separate application approval and execution; never invent success. options = new() { Model = "gpt-6.2-astra", PreviousResponseId = response.Id }; options.Tools.Add(ResponseTool.CreateApplyPatchTool()); foreach (ApplyPatchCallItem call in calls) { ApplyPatchCallOutputItem rejected = ResponseItem.CreateApplyPatchCallOutputItem( call.CallId, ApplyPatchCallOutputStatus.Failed); rejected.Output = "This additional patch has not been approved or executed."; options.InputItems.Add(rejected); } response = await client.CreateResponseAsync(options); } foreach (ResponseItem item in response.OutputItems) { if (item is MessageResponseItem message) { foreach (ResponseContentPart content in message.Content) { if (content.Kind == ResponseContentPartKind.OutputText) { Console.WriteLine(content.Text); } } } }}internal sealed record AppliedPatchResult( [property: JsonPropertyName("owner_id")] string OwnerId, [property: JsonPropertyName("previous_response_id")] string PreviousResponseId, [property: JsonPropertyName("call_id")] string CallId, [property: JsonPropertyName("status")] string Status, [property: JsonPropertyName("output")] string Output);#pragma warning restore OPENAI001
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 }] )endfiles.each { |path, content| print("===== #{path}\n#{content}") }
If a patch fails (for example, file not found), set status: "failed" and include a helpful output string so the model can recover:
Report a failed apply_patch call
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"}
Apply patch operations
Operation Type
Purpose
Payload
create_file
Create a new file at path.
diff is a V4A diff representing the full file contents.
update_file
Modify an existing file at path.
diff is a V4A diff with additions, deletions, or replacements.
delete_file
Remove a file at path.
No diff; delete the file entirely.
Your patch harness is responsible for interpreting the V4A diff format and applying changes. For reference implementations, see the Python Agents SDK or TypeScript Agents SDK code.
Implementing the patch harness
When using the apply_patch tool, you don’t provide an input schema; the model knows how to construct operation objects. Your job is to:
Parse operations from the Response
Scan the Response for items with type: "apply_patch_call".
For each call, inspect operation.type, operation.path, and any potential diff.
Apply file operations
For create_file and update_file, apply the V4A diff to the file system or in-memory workspace.
For delete_file, remove the file at path.
Record whether each operation succeeded and any logs or error messages.
Return apply_patch_call_output events
For each call_id, emit exactly one apply_patch_call_output event with:
status: "completed" if the operation was applied successfully.
status: "failed" if you encountered an error (include a short human-readable output string).
Safety and robustness
Path validation: Prevent directory traversal and restrict edits to allowed directories.
Backups: Consider backing up files (or working in a scratch copy) before applying patches.
Error handling: Always return a failed status with an informative output string when patches cannot be applied.
Atomicity: Decide whether you want “all-or-nothing” semantics (rollback if any patch fails) or per-file success/failure.
Use the apply patch tool with the Agents SDK
Alternatively, you can use the Agents SDK to use the apply patch tool. You’ll still have to implement the harness that handles the actual file operations but you can use the applyDiff function to handle the diff processing.
The model can then adjust future diffs (for example, by re-reading a file in your prompt or simplifying a change) based on these error messages.
Best practices
Give clear file context
When you call the Responses API, include either an inline snapshot of your files (as in the example), or give the model tools for exploring your filesystem (like the shell tool).
Consider using with the shell tool
When used in conjunction with the shell tool, the model can explore file system directories, read files, and grep for keywords, enabling agentic file discovery and editing.
Encourage small, focused diffs
In your system instructions, nudge the model toward minimal, targeted edits rather than huge rewrites.
Make sure changes apply cleanly
After a series of patches, run your tests or linters and share failures back in the next input so the model can fix them.