For LLMs to reliably provide patches for editing a file within a tool call, the most robust and reliable format is a JSON-based structured patch with contextual cues.
This format balances the LLM's ability to generate structured output with the need for the patch application tool to precisely and safely modify the file, even if the file's content has subtly changed since the LLM last saw it.
Let's break down why and provide an example:
The Recommended Format: JSON-Based Structured Patch with Context
This approach involves the LLM generating a JSON object containing a list of distinct operations, each specifying the change, the file path, and crucial contextual information to locate the change precisely.
Why this is best:
- LLM Generation Ease: LLMs excel at generating structured JSON. It's a well-defined format with clear key-value pairs, which is easier for an LLM to adhere to than the more complex, line-number-sensitive, or special-character-heavy
diff format.
- Robustness via Context: Instead of relying on fragile line numbers, the patch uses "context lines" (snippets of the original surrounding code/text). This allows the patching tool to find the correct location even if lines have been added or removed elsewhere in the file.
- Parsability & Validation: JSON is universally parsable. The tool can easily validate the structure and content of the patch using a JSON Schema.
- Specific Operations: It allows for explicit
insert, replace, and delete operations, making the LLM's intent clear.
- Auditability & Review: While not as concise as a
diff, the JSON structure is human-readable and can be easily converted into a diff for review.
Example JSON Schema & Explanation
{
"type": "array",
"description": "An array of file modification operations.",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path to the file to be modified."
},
"operation_type": {
"type": "string",
"enum": ["replace", "insert_after", "insert_before", "delete"],
"description": "The type of modification operation."
},
"original_content_context": {
"type": "string",
"description": "REQUIRED for 'replace', 'insert_after', 'insert_before', 'delete'. A unique snippet of the *original* content immediately surrounding or defining the target location. This helps the tool locate the exact position to apply the patch. It should be as unique as possible to avoid ambiguity. Can be multiple lines."
},
"new_content": {
"type": "string",
"description": "REQUIRED for 'replace', 'insert_after', 'insert_before'. The new content to insert or replace with. Can be multiple lines."
}
},
"required": ["file_path", "operation_type", "original_content_context"],
"oneOf": [
{
"properties": {
"operation_type": { "const": "replace" },
"new_content": { "type": "string" }
},
"required": ["new_content"]
},
{
"properties": {
"operation_type": { "const": "insert_after" },
"new_content": { "type": "string" }
},
"required": ["new_content"]
},
{
"properties": {
"operation_type": { "const": "insert_before" },
"new_content": { "type": "string" }
},
"required": ["new_content"]
},
{
"properties": {
"operation_type": { "const": "delete" }
}
}
]
}
}
Example LLM Output (Tool Call Payload)
[
{
"file_path": "src/utils.py",
"operation_type": "replace",
"original_content_context": "def calculate_sum(a, b):\n return a + b",
"new_content": "def calculate_sum(a: int, b: int) -> int:\n \"\"\"Calculates the sum of two integers.\"\"\"\n return a + b"
},
{
"file_path": "src/main.py",
"operation_type": "insert_after",
"original_content_context": "import os",
"new_content": "import logging\nlogging.basicConfig(level=logging.INFO)"
},
{
"file_path": "src/temp_files.txt",
"operation_type": "delete",
"original_content_context": "temporary_data.log"
}
]
How the Patch Application Tool Works (Crucial for Reliability)
The reliability of this format heavily depends on the tool that applies the patch:
- Read File: The tool reads the
file_path content.
- Locate Context: It searches for
original_content_context within the file.
- Crucial: If
original_content_context is not found, or found multiple times, the tool should fail gracefully (e.g., report an error to the LLM or user, suggesting the file might have changed or the context is ambiguous). It should not guess.
- Apply Operation:
replace: Replaces the original_content_context with new_content.
insert_after: Inserts new_content immediately after original_content_context.
insert_before: Inserts new_content immediately before original_content_context.
delete: Removes original_content_context from the file.
- Write File: The modified content is written back to the
file_path.
- Error Handling: Implement robust error handling for file I/O, context not found, and ambiguous contexts. Provide clear feedback to the LLM if an operation fails.
Less Reliable Alternatives (and why)
-
Unified Diff Format (.diff files):
- Pros: Standard, very expressive, tool-friendly for applying (e.g.,
git apply).
- Cons (for LLM generation): Extremely complex syntax (
---, +++, @@, +, -, leading spaces). LLMs are highly prone to generating subtle syntax errors (e.g., wrong number of leading spaces, malformed hunk headers) that make the entire patch invalid. It's a high cognitive load for the LLM to consistently produce perfectly.
-
Full File Replacement:
- Pros: Simplest for LLM to generate (just output the entire new file content).
- Cons: Highly inefficient (large token cost), no diffing capabilities, and extremely dangerous. If the LLM has an outdated view of the file, or makes a single mistake, it overwrites the entire file, losing all other concurrent changes. It lacks granularity and safety.
-
Line Number-Based Instructions (e.g., "Delete line 5", "Insert at line 10"):
- Pros: Simple for LLM to understand.
- Cons: Extremely fragile. Line numbers are absolute and shift with any preceding modification. If the LLM's internal line count is off by even one, the entire patch can apply incorrectly, leading to silent corruption.
Best Practices for LLM-Tool Interaction with Patches
- Provide Full Context: Always provide the LLM with the current content of the file it needs to modify.
- Clear Tool Description: Document the
file_patch tool clearly, including its JSON schema and the meaning of original_content_context. Emphasize its importance for precise targeting.
- Iterative Refinement: If the patch application tool reports an error (e.g., "context not found"), feed that error back to the LLM, giving it another chance to provide a corrected patch, possibly by requesting more context or a different approach.
- Version Control: For any system handling code or critical text, always apply patches within a version-controlled environment (e.g., Git) to allow for easy rollback and review.
- Pre-computation/Validation: The tool should internally "diff" the proposed
original_content_context with the actual file content to confirm it matches before applying. This adds a layer of safety.
By using a JSON-based structured patch with robust contextual anchoring, you maximize both the LLM's ability to generate accurate changes and the tool's ability to apply them safely and reliably.