https://github.com/parisneo/flexipatch
a tool to apply patches to code. very useful for optimizing LLM code editing
https://github.com/parisneo/flexipatch
Last synced: 10 months ago
JSON representation
a tool to apply patches to code. very useful for optimizing LLM code editing
- Host: GitHub
- URL: https://github.com/parisneo/flexipatch
- Owner: ParisNeo
- License: apache-2.0
- Created: 2025-07-23T21:09:41.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-07-27T22:24:29.000Z (12 months ago)
- Last Synced: 2025-08-06T10:19:25.592Z (12 months ago)
- Language: Python
- Size: 16.6 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# FlexiPatch: The Forgiving Patch Tool for AI-Powered Coding
[](https://badge.fury.io/py/flexipatch)
[](https://pypi.org/project/flexipatch)
[](https://github.com/ParisNeo/flexipatch/blob/main/LICENSE)
[](https://github.com/ParisNeo/flexipatch/actions)
[](https://github.com/psf/black)
[](https://pepy.tech/project/flexipatch)
Have you ever asked an LLM to refactor your code, only to get a patch that *looks* right but fails to apply because of a tiny whitespace or line-ending difference? **FlexiPatch** is the bridge between your AI's suggestions and your actual codebase.
It's a robust, dependency-free patch utility designed to work with the slightly imperfect, yet brilliant, code modifications generated by Large Language Models.
---
## The Problem: LLMs Are Smart, Not Perfect
Large Language Models are incredible at understanding code and suggesting improvements. You can ask one to "add type hints," "optimize this function," or "refactor this class to be more efficient," and it will often respond with a perfect `diff` or `patch` file.
The problem is that LLMs don't always sweat the small stuff:
* Did the original file have Windows (`\r\n`) or Unix (`\n`) line endings?
* Was there a trailing newline at the end of the file?
* Is the indentation in the context lines *exactly* the same?
A traditional patch tool sees these tiny differences and gives up. **FlexiPatch just gets it done.**
## The Workflow: LLM Genius Meets FlexiPatch Resilience
This library shines when combined with an LLM interaction library like [**lollms-client**](https://github.com/ParisNeo/lollms-client). You can create powerful, automated code editing scripts.
Here’s the game plan:
1. **Backup your code** (we'll use `git` for safety).
2. **Send your code to an LLM** via `lollms-client` and ask for a patch.
3. **Receive the patch** from the LLM.
4. **Apply the patch seamlessly** using `FlexiPatch`.
5. **Review and commit** your newly AI-refactored code!
### Example: A Complete AI Refactoring Script
Let's see it in action. Imagine we have a file `my_script.py` that we want to improve.
**Step 1: Install the necessary libraries.**
```bash
pip install flexipatch lollms-client
```
**Step 2: Create the Python script to orchestrate the magic.**
```python
import subprocess
from pathlib import Path
from lollms_client import LollmsClient
from flexipatch import RobustPatcher
# --- Configuration ---
# You can get a service key from your Lollms server instance
LOLLMS_HOST = "http://localhost:9642"
LOLLMS_KEY = "YOUR_LOLLMS_SERVICE_KEY"
FILE_TO_EDIT = Path("my_script.py")
# --- Let's create a dummy file to work with ---
FILE_TO_EDIT.write_text("""
def calculate_sum(a, b):
# A simple function
result = a + b
return result
# Let's test it
print(calculate_sum(5, 10))
""")
print(f"Created dummy file: {FILE_TO_EDIT}")
# --- 1. Safety First: Backup with Git ---
# It's always a good idea to commit your work before an AI takes the wheel.
try:
subprocess.run(["git", "add", FILE_TO_EDIT], check=True)
subprocess.run(["git", "commit", "-m", f"Backup before AI edit of {FILE_TO_EDIT}"], check=True)
print(f"✅ Committed a backup of {FILE_TO_EDIT} to git.")
except subprocess.CalledProcessError:
print("⚠️ Git backup failed. Make sure the file is in a git repository.")
# In a real script, you might want to exit here if backup is critical.
# --- 2. Connect to the LLM ---
print("Connecting to Lollms...")
lc = LollmsClient(host_address=LOLLMS_HOST, service_key=LOLLMS_KEY)
# --- 3. Ask the LLM to Generate a Patch ---
original_code = FILE_TO_EDIT.read_text()
prompt = f"""
Here is a Python script. Your task is to refactor it by adding type hints and a proper docstring to the `calculate_sum` function.
Please provide your changes ONLY in the form of a standard unified diff (a patch file). Do not add any other text, explanations, or code blocks.
```python
{original_code}
```
"""
system_prompt = "You are an expert Python code refactoring assistant. You only respond with patch files in the unified diff format."
print("Asking the LLM to generate a patch...")
# We use generate_text here as a patch is not exactly code, but text.
patch_text = lc.generate_text(
prompt,
system_prompt=system_prompt,
temperature=0.1 # Lower temperature for more deterministic, clean output
)
print("✅ Patch received from LLM:\n---")
print(patch_text)
print("---")
# --- 4. Apply the Patch with FlexiPatch ---
print("Applying patch with FlexiPatch...")
patcher = RobustPatcher()
try:
patched_code = patcher.apply_patch(original_code, patch_text)
# Overwrite the original file with the new, improved code
FILE_TO_EDIT.write_text(patched_code)
print(f"✅ Successfully patched {FILE_TO_EDIT}!")
except ValueError as e:
print(f"❌ FlexiPatch failed: {e}")
print("The LLM may have generated a malformed or incorrect patch. No changes were made.")
# Now you can run `git diff my_script.py` to see the changes!
```
---
## Contributing
Got an idea to make FlexiPatch even more resilient? Found a weird edge case it didn't handle? We welcome contributions!
1. **Fork the repository** on GitHub.
2. **Create a new branch** for your feature or bugfix (`git checkout -b feature/my-cool-idea`).
3. **Add tests** to the `tests/` directory to prove your change works and doesn't break anything.
4. **Send a pull request** and describe your changes.
## License
This project is licensed under the **Apache License 2.0**. See the `LICENSE` file for details. You are free to use, modify, and distribute it in your own projects, including commercial ones.
## Thank You!
Thanks for trying out FlexiPatch. We hope it makes your journey into AI-assisted software development smoother and more productive.