Implementation:Openai Openai agents python ApplyPatchTool Pattern
| Knowledge Sources | |
|---|---|
| Domains | Code Editing, File Operations, Sandboxed Execution |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Demonstrates ApplyPatchTool with a custom workspace editor implementation for file create, update, and delete operations, including workspace sandboxing, diff application via apply_diff, and operation approval tracking.
Description
The ApplyPatchTool pattern enables agents to perform file system modifications through a structured, sandboxed interface. Rather than giving agents direct file system access, the ApplyPatchTool accepts a custom editor object that implements create_file, update_file, and delete_file methods. Each method receives an ApplyPatchOperation containing the operation type, target path, and a diff string, and returns an ApplyPatchResult with an output message.
The example implements two key classes. WorkspaceEditor enforces workspace sandboxing by resolving all paths relative to a root directory and rejecting operations that would escape the workspace boundary. It uses the apply_diff utility to apply unified diffs to file contents -- apply_diff("", diff, mode="create") for new files and apply_diff(original, diff) for updates. ApprovalTracker provides operation deduplication by fingerprinting each operation (using SHA-256 of the operation type, path, and diff) and remembering approved operations, so identical operations are not re-prompted.
The agent is configured with ModelSettings(tool_choice="required") to force tool usage, and uses previous_response_id for multi-turn context. The example creates a tasks.md file and then updates it in a second turn, demonstrating the full create-then-update workflow within a temporary directory workspace.
Usage
Use this pattern when building agents that need to modify files in a controlled, auditable manner. It is ideal for code generation assistants, automated refactoring tools, configuration management agents, or any scenario where file modifications should be sandboxed, diffed, and optionally require human approval.
Code Reference
Source Location
- Repository: Openai_Openai_agents_python
- File: examples/tools/apply_patch.py
- Lines: 1-170
Signature
# Create the tool with a custom editor
tool = ApplyPatchTool(editor=editor)
# Editor must implement these methods:
class WorkspaceEditor:
def create_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult: ...
def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult: ...
def delete_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult: ...
Import
from agents import Agent, ApplyPatchTool, ModelSettings, Runner, apply_diff, trace
from agents.editor import ApplyPatchOperation, ApplyPatchResult
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| editor | object |
Yes | Custom editor implementing create_file, update_file, and delete_file methods
|
| operation.type | str |
N/A | The operation type: "create", "update", or "delete"
|
| operation.path | str |
N/A | The target file path (relative or absolute) |
| operation.diff | None | N/A | The unified diff to apply for create or update operations |
| model_settings.tool_choice | str |
No | Set to "required" to force the agent to use the tool
|
Outputs
| Name | Type | Description |
|---|---|---|
| ApplyPatchResult.output | str |
A message describing the operation result (e.g., "Created tasks.md") |
| result.final_output | str |
The agent's final text response summarizing the performed operations |
| result.last_response_id | str |
Response ID for multi-turn conversation continuation |
Usage Examples
Sandboxed File Editing Agent
import asyncio
import tempfile
from pathlib import Path
from agents import Agent, ApplyPatchTool, ModelSettings, Runner, apply_diff, trace
from agents.editor import ApplyPatchOperation, ApplyPatchResult
class SimpleEditor:
def __init__(self, root: Path):
self._root = root.resolve()
def create_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = (self._root / operation.path).resolve()
target.parent.mkdir(parents=True, exist_ok=True)
content = apply_diff("", operation.diff or "", mode="create")
target.write_text(content, encoding="utf-8")
return ApplyPatchResult(output=f"Created {operation.path}")
def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = (self._root / operation.path).resolve()
original = target.read_text(encoding="utf-8")
patched = apply_diff(original, operation.diff or "")
target.write_text(patched, encoding="utf-8")
return ApplyPatchResult(output=f"Updated {operation.path}")
def delete_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = (self._root / operation.path).resolve()
target.unlink(missing_ok=True)
return ApplyPatchResult(output=f"Deleted {operation.path}")
async def main():
with tempfile.TemporaryDirectory() as workspace:
workspace_path = Path(workspace).resolve()
editor = SimpleEditor(workspace_path)
tool = ApplyPatchTool(editor=editor)
agent = Agent(
name="Patch Assistant",
instructions=f"Edit files inside {workspace_path} using the apply_patch tool.",
tools=[tool],
model_settings=ModelSettings(tool_choice="required"),
)
with trace("apply_patch_example"):
result = await Runner.run(agent, "Create hello.txt with 'Hello, World!' content.")
print(result.final_output)
asyncio.run(main())