Skip to content

ParisNeo/flexipatch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FlexiPatch: The Forgiving Patch Tool for AI-Powered Coding

PyPI version Python versions License Build Status Code style: black Downloads

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:

  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.

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.

About

a tool to apply patches to code. very useful for optimizing LLM code editing

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages