如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

套用修補程式

讓模型提出結構化差異,再由你的應用程式套用。

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

使用須知