The forgiving patch tool for AI-powered coding.
Project description
FlexiPatch: The Forgiving Patch Tool for AI-Powered Coding
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. You can create powerful, automated code editing scripts.
Here’s the game plan:
- Backup your code (we'll use
gitfor safety). - Send your code to an LLM via
lollms-clientand ask for a patch. - Receive the patch from the LLM.
- Apply the patch seamlessly using
FlexiPatch. - 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.
pip install flexipatch lollms-client
Step 2: Create the Python script to orchestrate the magic.
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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flexipatch-0.1.0.tar.gz.
File metadata
- Download URL: flexipatch-0.1.0.tar.gz
- Upload date:
- Size: 18.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ecc1413198e86c23d9ed8496d38ac259635401d77abcc27896dad63cd1f1415c
|
|
| MD5 |
81d24a2736101ba5f285c54cd22a558e
|
|
| BLAKE2b-256 |
cd1c2afa010b66409d01b83893e23e22dceaa6e2308d2f96f84669af259c1f80
|
File details
Details for the file flexipatch-0.1.0-py3-none-any.whl.
File metadata
- Download URL: flexipatch-0.1.0-py3-none-any.whl
- Upload date:
- Size: 14.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fd62ecdac311fb2b6944fb7fe64d94c8fa9734370499bf843f99ac86ab91b339
|
|
| MD5 |
29c31896721fa0ca657fd65c175879a8
|
|
| BLAKE2b-256 |
169891398bd14386a1b329fb5efa4721f31c65bce4f9741d6cafdd2c6a1cad92
|