|
| 1 | +import { OpenAI as OpenAIClient } from "openai"; |
| 2 | +import { tool } from "@langchain/core/tools"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Re-export operation types from OpenAI SDK for convenience. |
| 6 | + */ |
| 7 | +export type ApplyPatchCreateFileOperation = |
| 8 | + OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile; |
| 9 | +export type ApplyPatchUpdateFileOperation = |
| 10 | + OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile; |
| 11 | +export type ApplyPatchDeleteFileOperation = |
| 12 | + OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile; |
| 13 | + |
| 14 | +/** |
| 15 | + * Union type of all apply patch operations from OpenAI SDK. |
| 16 | + */ |
| 17 | +export type ApplyPatchOperation = NonNullable< |
| 18 | + OpenAIClient.Responses.ResponseApplyPatchToolCall["operation"] |
| 19 | +>; |
| 20 | + |
| 21 | +/** |
| 22 | + * Options for the Apply Patch tool. |
| 23 | + */ |
| 24 | +export interface ApplyPatchOptions { |
| 25 | + /** |
| 26 | + * Execute function that handles patch operations. |
| 27 | + * This function receives the operation input and should return a string |
| 28 | + * describing the result (success or failure message). |
| 29 | + * |
| 30 | + * The operation types are: |
| 31 | + * - `create_file`: Create a new file at the specified path with the diff content |
| 32 | + * - `update_file`: Modify an existing file using V4A diff format |
| 33 | + * - `delete_file`: Remove a file at the specified path |
| 34 | + * |
| 35 | + * @example |
| 36 | + * ```typescript |
| 37 | + * execute: async (operation) => { |
| 38 | + * if (operation.type === "create_file") { |
| 39 | + * const content = applyDiff("", operation.diff, "create"); |
| 40 | + * await fs.writeFile(operation.path, content); |
| 41 | + * return `Created ${operation.path}`; |
| 42 | + * } |
| 43 | + * if (operation.type === "update_file") { |
| 44 | + * const current = await fs.readFile(operation.path, "utf-8"); |
| 45 | + * const newContent = applyDiff(current, operation.diff); |
| 46 | + * await fs.writeFile(operation.path, newContent); |
| 47 | + * return `Updated ${operation.path}`; |
| 48 | + * } |
| 49 | + * if (operation.type === "delete_file") { |
| 50 | + * await fs.unlink(operation.path); |
| 51 | + * return `Deleted ${operation.path}`; |
| 52 | + * } |
| 53 | + * return "Unknown operation type"; |
| 54 | + * } |
| 55 | + * ``` |
| 56 | + */ |
| 57 | + execute: (operation: ApplyPatchOperation) => string | Promise<string>; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * OpenAI Apply Patch tool type for the Responses API. |
| 62 | + */ |
| 63 | +export type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool; |
| 64 | + |
| 65 | +const TOOL_NAME = "apply_patch"; |
| 66 | + |
| 67 | +/** |
| 68 | + * Creates an Apply Patch tool that allows models to propose structured diffs |
| 69 | + * that your integration applies. This enables iterative, multi-step code |
| 70 | + * editing workflows. |
| 71 | + * |
| 72 | + * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase |
| 73 | + * using structured diffs. Instead of just suggesting edits, the model emits |
| 74 | + * patch operations that your application applies and then reports back on. |
| 75 | + * |
| 76 | + * **When to use**: |
| 77 | + * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules |
| 78 | + * - **Bug fixes** – Have the model both diagnose issues and emit precise patches |
| 79 | + * - **Tests & docs generation** – Create new test files, fixtures, and documentation |
| 80 | + * - **Migrations & mechanical edits** – Apply repetitive, structured updates |
| 81 | + * |
| 82 | + * **How it works**: |
| 83 | + * The tool operates in a continuous loop: |
| 84 | + * 1. Model sends patch operations (`apply_patch_call` with operation type) |
| 85 | + * 2. Your code applies the patch to your working directory or repo |
| 86 | + * 3. You return success/failure status and optional output |
| 87 | + * 4. Repeat until the task is complete |
| 88 | + * |
| 89 | + * **Security Warning**: Applying patches can modify files in your codebase. |
| 90 | + * Always validate paths, implement backups, and consider sandboxing. |
| 91 | + * |
| 92 | + * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation} |
| 93 | + * |
| 94 | + * @param options - Configuration options for the Apply Patch tool |
| 95 | + * @returns An Apply Patch tool that can be passed to `bindTools` |
| 96 | + * |
| 97 | + * @example |
| 98 | + * ```typescript |
| 99 | + * import { ChatOpenAI, tools } from "@langchain/openai"; |
| 100 | + * import { applyDiff } from "@openai/agents"; |
| 101 | + * import * as fs from "fs/promises"; |
| 102 | + * |
| 103 | + * const model = new ChatOpenAI({ model: "gpt-5.1" }); |
| 104 | + * |
| 105 | + * // With execute callback for automatic patch handling |
| 106 | + * const patchTool = tools.applyPatch({ |
| 107 | + * execute: async (operation) => { |
| 108 | + * if (operation.type === "create_file") { |
| 109 | + * const content = applyDiff("", operation.diff, "create"); |
| 110 | + * await fs.writeFile(operation.path, content); |
| 111 | + * return `Created ${operation.path}`; |
| 112 | + * } |
| 113 | + * if (operation.type === "update_file") { |
| 114 | + * const current = await fs.readFile(operation.path, "utf-8"); |
| 115 | + * const newContent = applyDiff(current, operation.diff); |
| 116 | + * await fs.writeFile(operation.path, newContent); |
| 117 | + * return `Updated ${operation.path}`; |
| 118 | + * } |
| 119 | + * if (operation.type === "delete_file") { |
| 120 | + * await fs.unlink(operation.path); |
| 121 | + * return `Deleted ${operation.path}`; |
| 122 | + * } |
| 123 | + * return "Unknown operation type"; |
| 124 | + * }, |
| 125 | + * }); |
| 126 | + * |
| 127 | + * const llmWithPatch = model.bindTools([patchTool]); |
| 128 | + * const response = await llmWithPatch.invoke( |
| 129 | + * "Rename the fib() function to fibonacci() in lib/fib.py" |
| 130 | + * ); |
| 131 | + * ``` |
| 132 | + * |
| 133 | + * @remarks |
| 134 | + * - Only available through the Responses API (not Chat Completions) |
| 135 | + * - Designed for use with `gpt-5.1` model |
| 136 | + * - Operations include: `create_file`, `update_file`, `delete_file` |
| 137 | + * - Patches use V4A diff format for updates |
| 138 | + * - Always validate paths to prevent directory traversal attacks |
| 139 | + * - Consider backing up files before applying patches |
| 140 | + * - Implement "all-or-nothing" semantics if atomicity is required |
| 141 | + */ |
| 142 | +export function applyPatch(options: ApplyPatchOptions) { |
| 143 | + const patchTool = tool(options.execute, { |
| 144 | + name: TOOL_NAME, |
| 145 | + description: |
| 146 | + "Apply structured diffs to create, update, or delete files in the codebase.", |
| 147 | + schema: { |
| 148 | + type: "object", |
| 149 | + properties: { |
| 150 | + operation: { |
| 151 | + type: "string", |
| 152 | + enum: ["create_file", "update_file", "delete_file"], |
| 153 | + }, |
| 154 | + }, |
| 155 | + required: ["operation"], |
| 156 | + }, |
| 157 | + }); |
| 158 | + |
| 159 | + patchTool.extras = { |
| 160 | + ...(patchTool.extras ?? {}), |
| 161 | + providerToolDefinition: { |
| 162 | + type: "apply_patch", |
| 163 | + } as ApplyPatchTool, |
| 164 | + }; |
| 165 | + |
| 166 | + return patchTool; |
| 167 | +} |
0 commit comments