如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

应用补丁

让模型以结构化差异的形式提出更改,由您的应用程序执行。

在 Responses API 中使用 apply_patch,模型就可以通过结构化差异提出创建、更新和删除文件的建议。您的应用程序负责执行每项操作并返回结果。本文示例使用 gpt-6.2-astra。

适用场景

您可以使用 apply_patch 完成以下任务:

  • 多文件重构:一次性在多个文件中重命名符号、提取辅助函数或重新组织模块。
  • 修复错误:让模型诊断问题并生成精确的补丁。
  • 生成测试和文档:在修改代码的同时创建测试文件、测试夹具和文档。
  • 迁移和批量修改:按统一规则执行重复性更新,例如迁移 API、添加类型注解或修正格式。

如果您能用文字描述代码仓库和所需的更改,apply_patch 通常就能生成相应的差异。

在 Responses API 中使用补丁工具

在 Responses API 中使用 apply_patch 的基本流程如下:

  1. 调用 Responses API 并启用 apply_patch 工具
    • 在 input 中向模型提供可用文件的上下文或摘要,也可以向模型提供用于浏览文件系统的工具。
    • 使用 tools=[{"type": "apply_patch"}] 启用该工具。
  2. 让模型返回一个或多个补丁操作
    • 响应的输出包含一个或多个 apply_patch_call 对象。
    • 每次调用描述对一个文件执行的一项操作:创建、更新或删除。
  3. 在您的环境中应用补丁
    • 运行补丁执行框架或脚本,完成以下操作:
      • 解析 operation 中的差异,对每个 apply_patch_call 分别处理。
      • 将补丁应用到工作目录或代码仓库。
      • 记录每个补丁是否应用成功,以及相关日志或错误消息。
  4. 将补丁执行结果反馈给模型
    • 再次调用 Responses API,使用 previous_response_id,或将对话中的各项内容重新传入 input。
    • 返回 apply_patch_call_output 事件,每个 call_id 对应一个事件,其中包含 status 和可选的 output 字符串。
    • 保留 tools=[{"type": "apply_patch"}],以便模型在需要时继续编辑。
  5. 让模型继续编辑或解释更改
    • 模型可以继续发起 apply_patch_call 操作,
    • 也可以向用户说明修改了哪些内容以及修改的原因。

示例:使用补丁工具重命名函数

第 1 步:让模型制定修改计划并生成补丁

让模型制定修改计划并生成补丁
import 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"
);

apply_patch_call 对象示例

apply_patch_call 对象示例
{
    "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 步:应用补丁并返回结果

应用补丁并返回结果
for (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}`);
}

如果补丁应用失败(例如找不到文件),请设置 status: "failed",并在 output 字符串中说明原因,以便模型调整后继续操作:

报告 apply_patch 调用失败
{
  "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 对象。您需要完成以下工作:

  1. 从响应中解析操作
    • 在响应中查找满足 type: "apply_patch_call" 的项。
    • 对于每次调用,检查 operation.type、operation.path 以及可能存在的 diff。
  2. 执行文件操作
    • 对于 create_file 和 update_file,将 V4A 差异应用到文件系统或内存中的工作空间。
    • 对于 delete_file,删除 path 处的文件。
    • 记录每项操作是否成功,以及相关日志或错误消息。
  3. 返回 apply_patch_call_output 事件
    • 每个 call_id 都必须对应且仅对应一个 apply_patch_call_output 事件。通过该事件报告结果:
      • 如果操作执行成功,设置 status: "completed"。
      • 如果遇到错误,设置 status: "failed",并在 output 字符串中用简短易懂的文字说明错误。

安全性和健壮性

  • 路径验证:防止目录遍历,并将编辑范围限制在允许的目录内。
  • 备份:应用补丁前,可以先备份文件,也可以在临时副本中操作。
  • 错误处理:如果无法应用补丁,务必返回 failed 状态,并在 output 字符串中说明原因。
  • 原子性:您可以选择在任一补丁失败时回滚全部更改,也可以按文件分别处理成功或失败的结果。

在 Agents SDK 中使用补丁工具

您也可以通过 Agents SDK 使用补丁工具。您仍需实现执行框架来处理实际的文件操作,但可以使用 applyDiff 函数处理差异。

在 Agents SDK 中使用补丁工具
import {
  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}`);

您可以在 GitHub 上找到完整的可运行示例。

补丁工具示例(TypeScript)

在 TypeScript 中通过 Agents SDK 使用补丁工具的示例

补丁工具示例(Python)

在 Python 中通过 Agents SDK 使用补丁工具的示例

处理常见错误

使用 status: "failed" 并在 output 中清楚说明错误,以便模型调整后继续操作。

找不到文件错误
{
  "type": "apply_patch_call_output",
  "call_id": "call_abc",
  "status": "failed",
  "output": "Error: File not found at path 'lib/baz.py'"
}

模型随后可以根据这些错误消息调整后续生成的差异,例如重新读取您在提示词中提供的文件,或简化某项更改。

最佳实践

  • 提供清晰的文件上下文
    • 调用 Responses API 时,可以像示例中那样在输入中直接提供文件快照,也可以向模型提供用于浏览文件系统的工具,例如 shell 工具。
  • 考虑配合 shell 工具使用
    • 配合 shell 工具,模型可以浏览文件系统目录、读取文件并使用 grep 搜索关键词,从而自主查找和编辑文件。
  • 让模型生成范围小、目标明确的差异
    • 在系统指令中引导模型针对具体目标做尽可能少的修改,避免大规模重写。
  • 确认补丁已正确应用
    • 应用一系列补丁后,运行测试或代码检查工具,并在下一次 input 中反馈失败信息,以便模型修复问题。

使用说明