codecamp

OpenAI 应用补丁

apply_patch 工具让GPT-5.1通过结构化差异创建、更新和删除代码库文件。模型发出补丁操作,由应用执行并报告结果,从而形成可迭代、多步骤的代码编辑工作流。

适用场景

  • 跨文件重构:重命名符号、提取辅助函数、同时整理多个模块。
  • 修复错误:让模型诊断问题并给出精确补丁。
  • 生成测试与文档:伴随代码变更创建测试文件、夹具和文档。
  • 迁移与机械修改:执行重复、结构化的API迁移、类型注释和格式修正。

只要能用文本说明仓库和期望变更,通常便可用 apply_patch 生成相应差异。

在Responses API中使用应用补丁工具

流程如下:

  1. 请求Responses API并启用 tools=[{"type": "apply_patch"}]。在 input 中提供可用文件的上下文或摘要,也可提供探索文件系统的工具。
  2. 接收一个或多个 apply_patch_call 输出项,每项描述一次创建、更新或删除操作。
  3. 应用中的补丁执行器解释 operation 差异,在工作目录或仓库中应用,并记录成功与否、日志和错误。
  4. 再次请求Responses API,使用 previous_response_id 或完整会话项续接。每个 call_id 都要有对应的 apply_patch_call_output,包括 status 及可选 output。继续携带工具定义,让模型能进一步编辑。
  5. 模型继续发出补丁,或向用户说明改动及原因。

示例:用应用补丁重命名函数

步骤1:请模型规划并发出补丁。

来源示例1(javascript)

// [中文] 把两份文件及重命名任务交给模型,启用apply_patch并查看补丁调用。
const response = await client.responses.create({
  model: "gpt-6-astra",
  input: fileContext,
  tools: [{ type: "apply_patch" }],
});

const patchCalls = response.output.filter(
  (item) => item.type === "apply_patch_call"
);

来源示例2(python)

程序中的自然语言译释33:

用户拥有示例中列出的lib/fib.py和run.py文件。你是编程助手,应帮助用户完成所提请求。
用户请求:将fib()函数重命名为fibonacci()。
文件正文中的递归实现、导入关系及fib(42)调用均保留在原代码中;重命名时需处理这两份文件的相关位置。

## [中文] 把两份文件及重命名任务交给模型,启用apply_patch并查看补丁调用。
from openai import OpenAI

client = OpenAI()

## [中文] 为缩短示例,直接在输入中提供文件上下文。
## 为简化示例,将文件上下文直接放入输入。
## [中文] 多数智能体场景应向模型提供文件探索工具,
## 在多数智能体场景中,应为模型提供工具,
## [中文] 让模型自行查看文件系统状态。
## 以便它自行检查文件系统状态。
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可能含多个apply_patch_call,例如:
## response.output 可能包含多个 apply_patch_call 项,例如:
## [中文] 更新lib/fib.py。
## - update lib/fib.py
## [中文] 更新run.py。
## - update run.py
patch_calls = [
    item.model_dump() for item in response.output if item.type == "apply_patch_call"
]

来源示例3(go)

// [中文] 把两份文件及重命名任务交给模型,启用apply_patch并查看补丁调用。
response, 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
}

来源示例4(java)

程序中的自然语言译释126:

将lib/fib.py中的fib()改名为fibonacci(),并更新run.py以使用新名称。

// [中文] 把两份文件及重命名任务交给模型,启用apply_patch并查看补丁调用。
import 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);

来源示例5(ruby)

本段复用的中文释义:译释126。

## [中文] 把两份文件及重命名任务交给模型,启用apply_patch并查看补丁调用。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Rename fib() to fibonacci() in lib/fib.py and update run.py to use the new name.",
  tools: [{ type: :apply_patch }]
)

patch_calls = response.output.select { |item| item.type == :apply_patch_call }
puts(patch_calls)

apply_patch_call 对象示例:

来源示例6(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
    "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:应用补丁并返回执行结果。

来源示例7(javascript)

// [中文] 将应用实际执行的补丁结果关联原call_id返回,继续允许模型提出补丁。
const results = patchCalls.map((call) => {
  const { success, output } = applyOperation(call.operation);

  return {
    type: "apply_patch_call_output",
    call_id: call.call_id,
    status: success ? "completed" : "failed",
    output,
  };
});

const followup = await client.responses.create({
  model: "gpt-6-astra",
  previous_response_id: response.id,
  input: results,
  tools: [{ type: "apply_patch" }],
});

console.log(followup.output_text);

来源示例8(python)

## [中文] 将应用实际执行的补丁结果关联原call_id返回,继续允许模型提出补丁。
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-6-astra",
    previous_response_id=response.id,
    input=results,
    tools=[{"type": "apply_patch"}],
)

来源示例9(go)

// [中文] 将应用实际执行的补丁结果关联原call_id返回,继续允许模型提出补丁。
for 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
    }
}

来源示例10(java)

// [中文] 将应用实际执行的补丁结果关联原call_id返回,继续允许模型提出补丁。
import 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()));

来源示例11(ruby)

## [中文] 将应用实际执行的补丁结果关联原call_id返回,继续允许模型提出补丁。
require "openai"

client = OpenAI::Client.new
response_id = ENV.fetch("OPENAI_RESPONSE_ID")
patch_call_id = ENV.fetch("OPENAI_APPLY_PATCH_CALL_ID")
response = client.responses.create(
  model: "gpt-6-astra",
  previous_response_id: response_id,
  input: [
    {
      type: :apply_patch_call_output,
      call_id: patch_call_id,
      status: :completed,
      output: "Patch applied successfully."
    }
  ],
  tools: [{ type: :apply_patch }]
)

puts(response.output_text)

补丁失败,例如文件不存在时,设置 status: "failed" 并提供有帮助的输出,让模型修正后续操作。

来源示例12(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "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 修改已有文件 diff 包含增加、删除、替换内容
delete_file 删除文件 不包含 diff,删除整个文件

执行器负责解释V4A格式。可参考Python Agents SDK实现和TypeScript Agents SDK实现。

实现补丁执行器

启用工具时不需要提交输入模式,模型知道如何构造 operation。应用的职责包括:

  1. 扫描响应中的 apply_patch_call,检查每项的 operation.type、operation.path 和可选 operation.diff。
  2. 对创建和更新操作,将差异应用到文件系统或内存工作区;对删除操作移除文件。记录每项操作是否成功和相关日志。
  3. 对每个 call_id 恰好返回一个 apply_patch_call_output:成功为 status: "completed",失败为 status: "failed",失败时提供有助于恢复的 output。

安全性与健壮性

  • 路径验证:防止目录穿越,限制到允许的目录。
  • 备份:应用补丁前备份文件,或在临时工作副本中操作。
  • 错误处理:无法应用时明确返回失败及有效错误信息。
  • 原子性:自行决定整批全部成功或回滚,还是允许逐文件部分成功。

在Agents SDK中使用应用补丁工具

也可通过Agents SDK调用。应用仍需实现执行器,但可用SDK的 applyDiff 辅助函数处理差异。

来源示例13(javascript)

程序中的自然语言译释34:

可以使用apply_patch工具编辑/tmp目录内的文件。

程序中的自然语言译释35:

创建tasks.md,包含五项购物检查清单。

// [中文] 提供创建、读取、更新和删除文件的补丁执行器;批准逻辑由应用定义。
import { applyDiff, Agent, run, applyPatchTool } from "@openai/agents";

class WorkspaceEditor {
  async createFile(operation) {
    // [中文] 把差异转换成文件内容。
    // 把差异转换成文件内容。
    const content = applyDiff("", operation.diff, "create");
    // [中文] 将文件内容写入文件系统。
    // 将文件内容写入文件系统。
    return { status: "completed", output: `Created ${operation.path}` };
  }

  async updateFile(operation) {
    // [中文] 从文件系统读取现有内容。
    // 从文件系统读取文件内容。
    const current = "";
    // [中文] 将差异应用为新内容。
    // 根据差异生成更新后的文件内容。
    const newContent = applyDiff(current, operation.diff);
    // [中文] 将更新后的内容写回文件系统。
    // 将更新后的内容写入文件系统。
    return { status: "completed", output: `Updated ${operation.path}` };
  }

  async deleteFile(operation) {
    // [中文] 从文件系统删除文件。
    // 从文件系统删除文件。
    return { status: "completed", output: `Deleted ${operation.path}` };
  }
}

const editor = new WorkspaceEditor();

const agent = new Agent({
  name: "Patch Assistant",
  model: "gpt-6-astra",
  instructions:
    "You can edit files inside the /tmp directory using the apply_patch tool.",
  tools: [
    applyPatchTool({
      editor,
      // [中文] 这里也可以由函数动态判断是否需要批准。
      // 也可以用函数判断是否需要审批。
      needsApproval: true,
      onApproval: async (_ctx, _approvalItem) => {
        // [中文] 在此实现应用自己的批准逻辑。
        // 实现应用自己的审批逻辑。
        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}`);

来源示例14(python)

本段复用的中文释义:译释34、译释35。

## [中文] 提供创建、读取、更新和删除文件的补丁执行器;批准逻辑由应用定义。
from agents import Agent, ApplyPatchTool, Runner, apply_diff


class WorkspaceEditor:
    async def create_file(self, operation):
        # [中文] 把差异转换成文件内容。
        # 把差异转换成文件内容。
        content = apply_diff("", operation.diff, mode="create")
        # [中文] 将文件内容写入文件系统。
        # 将文件内容写入文件系统。
        return {"status": "completed", "output": f"Created {operation.path}"}

    async def update_file(self, operation):
        # [中文] 从文件系统读取现有内容。
        # 从文件系统读取文件内容。
        current = ""
        # [中文] 将差异应用为新内容。
        # 根据差异生成更新后的文件内容。
        new_content = apply_diff(current, operation.diff)
        # [中文] 将更新后的内容写回文件系统。
        # 将更新后的内容写入文件系统。
        return {"status": "completed", "output": f"Updated {operation.path}"}

    async def delete_file(self, operation):
        # [中文] 从文件系统删除文件。
        # 从文件系统删除文件。
        return {"status": "completed", "output": f"Deleted {operation.path}"}


editor = WorkspaceEditor()

agent = Agent(
    name="Patch Assistant",
    model="gpt-6-astra",
    instructions="You can edit files inside the /tmp directory using the apply_patch tool.",
    tools=[
        ApplyPatchTool(
            editor=editor,
            # [中文] 这里也可以由函数动态判断是否需要批准。
            # 也可以用函数判断是否需要审批。
            needs_approval=True,
            # [中文] 在此实现应用自己的批准逻辑。
            # 实现应用自己的审批逻辑。
            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())

完整示例:TypeScript、Python。

处理常见错误

使用 status: "failed" 和清晰输出,帮助模型恢复。

文件不存在

来源示例15(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "type": "apply_patch_call_output",
  "call_id": "call_abc",
  "status": "failed",
  "output": "Error: File not found at path 'lib/baz.py'"
}

补丁冲突

来源示例16(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "type": "apply_patch_call_output",
  "call_id": "call_abc",
  "status": "failed",
  "output": "Error: Invalid Context:\n@@ def fib(n):"
}

模型可据此重新读取文件或简化变更,再调整后续差异。

最佳实践

  • 提供清晰的文件上下文:在请求中放文件快照,或提供Shell等文件探索工具。
  • 结合Shell:让模型查看目录、读取文件、搜索关键字,完成文件发现与编辑。
  • 鼓励小而集中的差异:在系统指令中要求最小且有针对性的变更,避免巨大重写。
  • 确认应用成功:一系列补丁之后运行测试或检查器,把失败结果放进后续 input。

使用说明

来源的可用性表列出Responses、Chat Completions、Assistants入口,以及GPT-5.5、GPT-5.4、GPT-5.2、GPT-5.1模型。此表保留来源列举范围;具体接口的请求结构须按各自参考核对,不能把Responses的 apply_patch_call 直接套用于其他协议。

OpenAI 使用工具
OpenAI 代码解释器
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

其他能力与进阶指南

Embeddings 接口参考

审计日志接口参考

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }