Patch

Patch#

Gives the LLM agent the ability to patch text files, by using a adapted version git conflict markers.

Environment Variables:
GPTME_PATCH_RECOVERY: If set to “true” or “1”, returns the file content in error messages

when patches don’t match. This helps the assistant recover faster by seeing the actual file contents.

Instructions

To patch/modify files, we use an adapted version of git conflict markers.

Multiple ORIGINAL/UPDATED blocks can make several changes in one patch.
Keep patches small. Scope each change to a function/class. Avoid placeholders
in ORIGINAL blocks; they must match the file exactly or the patch will fail.

### When to use patch vs save

Use `patch` for targeted edits to existing files.
Use `save` for new files, full rewrites, or changes too large for patch markers.

Note: When patching markdown, avoid replacing partial codeblocks (just the opening
or closing backticks). The parser needs complete codeblocks. For simple
codeblock-boundary changes (like a language tag), use `sed` or `perl` instead.

Examples

User
patch `src/hello.py` to ask for the name of the user
src/hello.py
def hello():
    print("Hello world")

if __name__ == "__main__":
    hello()
Assistant
patch src/hello.py
<<<<<<< ORIGINAL
    print("Hello world")
=======
    name = input("What is your name? ")
    print(f"Hello {name}")
>>>>>>> UPDATED
System
Patch applied
class gptme.tools.patch.Patch

Patch(original: str, updated: str)

__init__(original: str, updated: str) None
diff_minimal(strip_context=False) str

Show a minimal diff of the patch. Note that a minimal diff isn’t necessarily a unique diff.

gptme.tools.patch.apply(codeblock: str, content: str) str

Applies multiple patches in codeblock to content. Provides detailed error messages when patches fail.

gptme.tools.patch.execute_patch(code: str | None, args: list[str] | None, kwargs: dict[str, str] | None) Generator[Message, None, None]

Applies the patch.

gptme.tools.patch.execute_patch_impl(content: str, path: Path | None) Generator[Message, None, None]

Actual patch implementation.

gptme.tools.patch.preview_patch(content: str, path: Path | None) str | None

Prepare preview content for patch operation.