patchllm 0.1.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: patchllm
3
+ Version: 0.2.1
4
+ Summary: Lightweight tool to manage contexts and update code with LLMs
5
+ Author: nassimberrada
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 nassimberrada
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the “Software”), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Requires-Python: >=3.8
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: litellm
31
+ Requires-Dist: python-dotenv
32
+ Requires-Dist: rich
33
+ Provides-Extra: voice
34
+ Requires-Dist: SpeechRecognition; extra == "voice"
35
+ Requires-Dist: pyttsx3; extra == "voice"
36
+ Provides-Extra: url
37
+ Requires-Dist: html2text; extra == "url"
38
+ Dynamic: license-file
39
+
40
+ <p align="center">
41
+ <picture>
42
+ <source srcset="./assets/logo_dark.png" media="(prefers-color-scheme: dark)">
43
+ <source srcset="./assets/logo_light.png" media="(prefers-color-scheme: light)">
44
+ <img src="./assets/logo_light.png" alt="PatchLLM Logo" height="200">
45
+ </picture>
46
+ </p>
47
+
48
+ ## About
49
+ PatchLLM is a command-line tool that lets you flexibly build LLM context from your codebase using glob patterns, URLs, and keyword searches. It then automatically applies file edits directly from the LLM's response.
50
+
51
+ ## Usage
52
+ PatchLLM is designed to be used directly from your terminal.
53
+
54
+ ### 1. Initialize a Configuration
55
+ The easiest way to get started is to run the interactive initializer. This will create a `configs.py` file for you.
56
+
57
+ ```bash
58
+ patchllm --init
59
+ ```
60
+
61
+ This will guide you through creating your first context configuration, including setting a base path and file patterns. You can add multiple configurations to this file.
62
+
63
+ A generated `configs.py` might look like this:
64
+ ```python
65
+ # configs.py
66
+ configs = {
67
+ "default": {
68
+ "path": ".",
69
+ "include_patterns": ["**/*.py"],
70
+ "exclude_patterns": ["**/tests/*", "venv/*"],
71
+ "urls": ["https://docs.python.org/3/library/argparse.html"]
72
+ },
73
+ "docs": {
74
+ "path": "./docs",
75
+ "include_patterns": ["**/*.md"],
76
+ }
77
+ }
78
+ ```
79
+
80
+ ### 2. Run a Task
81
+ Use the `patchllm` command with a configuration name and a task instruction.
82
+
83
+ ```bash
84
+ # Apply a change using the 'default' configuration
85
+ patchllm --config default --task "Add type hints to the main function in main.py"
86
+ ```
87
+
88
+ The tool will then:
89
+ 1. Build a context from the files and URLs matching your configuration.
90
+ 2. Send the context and your task to the configured LLM.
91
+ 3. Parse the response and automatically write the changes to the relevant files.
92
+
93
+ ### All Commands & Options
94
+
95
+ #### Configuration Management
96
+ * `--init`: Create a new configuration interactively.
97
+ * `--list-configs`: List all available configurations from your `configs.py`.
98
+ * `--show-config <name>`: Display the settings for a specific configuration.
99
+
100
+ #### Core Task Execution
101
+ * `--config <name>`: The name of the configuration to use for building context.
102
+ * `--task "<instruction>"`: The task instruction for the LLM.
103
+ * `--model <model_name>`: Specify a different model (e.g., `claude-3-opus`). Defaults to `gemini/gemini-1.5-flash`.
104
+
105
+ #### Context Handling
106
+ * `--context-out [filename]`: Save the generated context to a file (defaults to `context.md`) instead of sending it to the LLM.
107
+ * `--context-in <filename>`: Use a previously saved context file directly, skipping context generation.
108
+ * `--update False`: A flag to prevent sending the prompt to the LLM. Useful when you only want to generate and save the context with `--context-out`.
109
+
110
+ #### Alternative Inputs
111
+ * `--from-file <filename>`: Apply file patches directly from a local file instead of from an LLM response.
112
+ * `--from-clipboard`: Apply file patches directly from your clipboard content.
113
+ * `--voice True`: Use voice recognition to provide the task instruction. Requires extra dependencies.
114
+
115
+ ### Setup
116
+
117
+ PatchLLM uses [LiteLLM](https://github.com/BerriAI/litellm) under the hood. Please refer to their documentation for setting up API keys (e.g., `OPENAI_API_KEY`, `GEMINI_API_KEY`) in a `.env` file and for a full list of available models.
118
+
119
+ To use the voice feature (`--voice True`), you will need to install extra dependencies:
120
+ ```bash
121
+ pip install "speechrecognition>=3.10" "pyttsx3>=2.90"
122
+ # Note: speechrecognition may require PyAudio, which might have system-level dependencies.
123
+ ```
124
+
125
+ ## License
126
+
127
+ This project is licensed under the MIT License. See the `LICENSE` file for details.
@@ -0,0 +1,88 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source srcset="./assets/logo_dark.png" media="(prefers-color-scheme: dark)">
4
+ <source srcset="./assets/logo_light.png" media="(prefers-color-scheme: light)">
5
+ <img src="./assets/logo_light.png" alt="PatchLLM Logo" height="200">
6
+ </picture>
7
+ </p>
8
+
9
+ ## About
10
+ PatchLLM is a command-line tool that lets you flexibly build LLM context from your codebase using glob patterns, URLs, and keyword searches. It then automatically applies file edits directly from the LLM's response.
11
+
12
+ ## Usage
13
+ PatchLLM is designed to be used directly from your terminal.
14
+
15
+ ### 1. Initialize a Configuration
16
+ The easiest way to get started is to run the interactive initializer. This will create a `configs.py` file for you.
17
+
18
+ ```bash
19
+ patchllm --init
20
+ ```
21
+
22
+ This will guide you through creating your first context configuration, including setting a base path and file patterns. You can add multiple configurations to this file.
23
+
24
+ A generated `configs.py` might look like this:
25
+ ```python
26
+ # configs.py
27
+ configs = {
28
+ "default": {
29
+ "path": ".",
30
+ "include_patterns": ["**/*.py"],
31
+ "exclude_patterns": ["**/tests/*", "venv/*"],
32
+ "urls": ["https://docs.python.org/3/library/argparse.html"]
33
+ },
34
+ "docs": {
35
+ "path": "./docs",
36
+ "include_patterns": ["**/*.md"],
37
+ }
38
+ }
39
+ ```
40
+
41
+ ### 2. Run a Task
42
+ Use the `patchllm` command with a configuration name and a task instruction.
43
+
44
+ ```bash
45
+ # Apply a change using the 'default' configuration
46
+ patchllm --config default --task "Add type hints to the main function in main.py"
47
+ ```
48
+
49
+ The tool will then:
50
+ 1. Build a context from the files and URLs matching your configuration.
51
+ 2. Send the context and your task to the configured LLM.
52
+ 3. Parse the response and automatically write the changes to the relevant files.
53
+
54
+ ### All Commands & Options
55
+
56
+ #### Configuration Management
57
+ * `--init`: Create a new configuration interactively.
58
+ * `--list-configs`: List all available configurations from your `configs.py`.
59
+ * `--show-config <name>`: Display the settings for a specific configuration.
60
+
61
+ #### Core Task Execution
62
+ * `--config <name>`: The name of the configuration to use for building context.
63
+ * `--task "<instruction>"`: The task instruction for the LLM.
64
+ * `--model <model_name>`: Specify a different model (e.g., `claude-3-opus`). Defaults to `gemini/gemini-1.5-flash`.
65
+
66
+ #### Context Handling
67
+ * `--context-out [filename]`: Save the generated context to a file (defaults to `context.md`) instead of sending it to the LLM.
68
+ * `--context-in <filename>`: Use a previously saved context file directly, skipping context generation.
69
+ * `--update False`: A flag to prevent sending the prompt to the LLM. Useful when you only want to generate and save the context with `--context-out`.
70
+
71
+ #### Alternative Inputs
72
+ * `--from-file <filename>`: Apply file patches directly from a local file instead of from an LLM response.
73
+ * `--from-clipboard`: Apply file patches directly from your clipboard content.
74
+ * `--voice True`: Use voice recognition to provide the task instruction. Requires extra dependencies.
75
+
76
+ ### Setup
77
+
78
+ PatchLLM uses [LiteLLM](https://github.com/BerriAI/litellm) under the hood. Please refer to their documentation for setting up API keys (e.g., `OPENAI_API_KEY`, `GEMINI_API_KEY`) in a `.env` file and for a full list of available models.
79
+
80
+ To use the voice feature (`--voice True`), you will need to install extra dependencies:
81
+ ```bash
82
+ pip install "speechrecognition>=3.10" "pyttsx3>=2.90"
83
+ # Note: speechrecognition may require PyAudio, which might have system-level dependencies.
84
+ ```
85
+
86
+ ## License
87
+
88
+ This project is licensed under the MIT License. See the `LICENSE` file for details.
@@ -1,8 +1,11 @@
1
- import os
2
1
  import glob
3
2
  import textwrap
4
- import sys
3
+ import subprocess
4
+ import shutil
5
5
  from pathlib import Path
6
+ from rich.console import Console
7
+
8
+ console = Console()
6
9
 
7
10
  # --- Default Settings & Templates ---
8
11
 
@@ -29,12 +32,19 @@ BASE_TEMPLATE = textwrap.dedent('''
29
32
  ```
30
33
  {{source_tree}}
31
34
  ```
32
-
35
+ {{url_contents}}
33
36
  Relevant Files:
34
37
  ---------------
35
38
  {{files_content}}
36
39
  ''')
37
40
 
41
+ URL_CONTENT_TEMPLATE = textwrap.dedent('''
42
+ URL Contents:
43
+ -------------
44
+ {{content}}
45
+ ''')
46
+
47
+
38
48
  # --- Helper Functions (File Discovery, Filtering, Tree Generation) ---
39
49
 
40
50
  def find_files(base_path: Path, include_patterns: list[str], exclude_patterns: list[str] | None = None) -> list[Path]:
@@ -70,11 +80,10 @@ def filter_files_by_keyword(file_paths: list[Path], search_words: list[str]) ->
70
80
  matching_files = []
71
81
  for file_path in file_paths:
72
82
  try:
73
- # Using pathlib's read_text for cleaner code
74
83
  if any(word in file_path.read_text(encoding='utf-8', errors='ignore') for word in search_words):
75
84
  matching_files.append(file_path)
76
85
  except Exception as e:
77
- print(f"Warning: Could not read {file_path} for keyword search: {e}", file=sys.stderr)
86
+ console.print(f"⚠️ Could not read {file_path} for keyword search: {e}", style="yellow")
78
87
  return matching_files
79
88
 
80
89
 
@@ -86,11 +95,8 @@ def generate_source_tree(base_path: Path, file_paths: list[Path]) -> str:
86
95
  tree = {}
87
96
  for path in file_paths:
88
97
  try:
89
- # Create a path relative to the intended base_path for the tree structure
90
98
  rel_path = path.relative_to(base_path)
91
99
  except ValueError:
92
- # This occurs if a file (from an absolute pattern) is outside the base_path.
93
- # In this case, we use the absolute path as a fallback.
94
100
  rel_path = path
95
101
 
96
102
  level = tree
@@ -112,6 +118,61 @@ def generate_source_tree(base_path: Path, file_paths: list[Path]) -> str:
112
118
  return f"{base_path.name}\n" + "\n".join(_format_tree(tree))
113
119
 
114
120
 
121
+ def fetch_and_process_urls(urls: list[str]) -> str:
122
+ """Downloads and converts a list of URLs to text, returning a formatted string."""
123
+ if not urls:
124
+ return ""
125
+
126
+ try:
127
+ import html2text
128
+ except ImportError:
129
+ console.print("⚠️ To use the URL feature, please install the required extras:", style="yellow")
130
+ console.print(" pip install patchllm[url]", style="cyan")
131
+ return ""
132
+
133
+ downloader = None
134
+ if shutil.which("curl"):
135
+ downloader = "curl"
136
+ elif shutil.which("wget"):
137
+ downloader = "wget"
138
+
139
+ if not downloader:
140
+ console.print("⚠️ Cannot fetch URL content: 'curl' or 'wget' not found in PATH.", style="yellow")
141
+ return ""
142
+
143
+ h = html2text.HTML2Text()
144
+ h.ignore_links = True
145
+ h.ignore_images = True
146
+
147
+ all_url_contents = []
148
+
149
+ console.print("\n--- Fetching URL Content... ---", style="bold")
150
+ for url in urls:
151
+ try:
152
+ console.print(f"Fetching [cyan]{url}[/cyan]...")
153
+ if downloader == "curl":
154
+ command = ["curl", "-s", "-L", url]
155
+ else: # wget
156
+ command = ["wget", "-q", "-O", "-", url]
157
+
158
+ result = subprocess.run(command, capture_output=True, text=True, check=True, timeout=15)
159
+ html_content = result.stdout
160
+ text_content = h.handle(html_content)
161
+ all_url_contents.append(f"<url_content:{url}>\n```\n{text_content}\n```")
162
+
163
+ except subprocess.CalledProcessError as e:
164
+ console.print(f"❌ Failed to fetch {url}: {e.stderr}", style="red")
165
+ except subprocess.TimeoutExpired:
166
+ console.print(f"❌ Failed to fetch {url}: Request timed out.", style="red")
167
+ except Exception as e:
168
+ console.print(f"❌ An unexpected error occurred while fetching {url}: {e}", style="red")
169
+
170
+ if not all_url_contents:
171
+ return ""
172
+
173
+ content_str = "\n\n".join(all_url_contents)
174
+ return URL_CONTENT_TEMPLATE.replace("{{content}}", content_str)
175
+
115
176
  # --- Main Context Building Function ---
116
177
 
117
178
  def build_context(config: dict) -> dict | None:
@@ -124,13 +185,13 @@ def build_context(config: dict) -> dict | None:
124
185
  Returns:
125
186
  dict: A dictionary with the source tree and formatted context, or None.
126
187
  """
127
- # Resolve the base path immediately to get a predictable absolute path.
128
188
  base_path = Path(config.get("path", ".")).resolve()
129
189
 
130
190
  include_patterns = config.get("include_patterns", [])
131
191
  exclude_patterns = config.get("exclude_patterns", [])
132
192
  exclude_extensions = config.get("exclude_extensions", DEFAULT_EXCLUDE_EXTENSIONS)
133
193
  search_words = config.get("search_words", [])
194
+ urls = config.get("urls", [])
134
195
 
135
196
  # Step 1: Find files
136
197
  relevant_files = find_files(base_path, include_patterns, exclude_patterns)
@@ -140,20 +201,18 @@ def build_context(config: dict) -> dict | None:
140
201
  norm_ext = {ext.lower() for ext in exclude_extensions}
141
202
  relevant_files = [p for p in relevant_files if p.suffix.lower() not in norm_ext]
142
203
  if count_before_ext > len(relevant_files):
143
- print(f"Filtered {count_before_ext - len(relevant_files)} files by extension.")
204
+ console.print(f"Filtered {count_before_ext - len(relevant_files)} files by extension.", style="cyan")
144
205
 
145
206
  # Step 3: Filter by keyword
146
207
  if search_words:
147
208
  count_before_kw = len(relevant_files)
148
209
  relevant_files = filter_files_by_keyword(relevant_files, search_words)
149
- print(f"Filtered {count_before_kw - len(relevant_files)} files by keyword search.")
210
+ console.print(f"Filtered {count_before_kw - len(relevant_files)} files by keyword search.", style="cyan")
150
211
 
151
- if not relevant_files:
152
- print("\nNo files matched the specified criteria.")
212
+ if not relevant_files and not urls:
213
+ console.print("\n⚠️ No files or URLs matched the specified criteria.", style="yellow")
153
214
  return None
154
215
 
155
- print(f"\nFinal count of relevant files: {len(relevant_files)}.")
156
-
157
216
  # Generate source tree and file content blocks
158
217
  source_tree_str = generate_source_tree(base_path, relevant_files)
159
218
 
@@ -164,12 +223,16 @@ def build_context(config: dict) -> dict | None:
164
223
  content = file_path.read_text(encoding='utf-8')
165
224
  file_contents.append(f"<file_path:{display_path}>\n```\n{content}\n```")
166
225
  except Exception as e:
167
- print(f"Warning: Could not read file {file_path}: {e}", file=sys.stderr)
226
+ console.print(f"⚠️ Could not read file {file_path}: {e}", style="yellow")
168
227
 
169
228
  files_content_str = "\n\n".join(file_contents)
170
229
 
230
+ # Fetch and process URL contents
231
+ url_contents_str = fetch_and_process_urls(urls)
232
+
171
233
  # Assemble the final context using the base template
172
234
  final_context = BASE_TEMPLATE.replace("{{source_tree}}", source_tree_str)
235
+ final_context = final_context.replace("{{url_contents}}", url_contents_str)
173
236
  final_context = final_context.replace("{{files_content}}", files_content_str)
174
237
 
175
238
  return {"tree": source_tree_str, "context": final_context}
@@ -1,11 +1,13 @@
1
1
  import speech_recognition as sr
2
2
  import pyttsx3
3
+ from rich.console import Console
3
4
 
5
+ console = Console()
4
6
  recognizer = sr.Recognizer()
5
7
  tts_engine = pyttsx3.init()
6
8
 
7
9
  def speak(text):
8
- print("🤖 Speaking:", text)
10
+ console.print(f"🤖 Speaking: {text}", style="magenta")
9
11
  tts_engine.say(text)
10
12
  tts_engine.runAndWait()
11
13
 
@@ -13,11 +15,11 @@ def listen(prompt=None, timeout=5):
13
15
  with sr.Microphone() as source:
14
16
  if prompt:
15
17
  speak(prompt)
16
- print("🎙 Listening...")
18
+ console.print("🎙 Listening...", style="cyan")
17
19
  try:
18
20
  audio = recognizer.listen(source, timeout=timeout)
19
21
  text = recognizer.recognize_google(audio)
20
- print(f"🗣 Recognized: {text}")
22
+ console.print(f"🗣 Recognized: {text}", style="cyan")
21
23
  return text
22
24
  except sr.WaitTimeoutError:
23
25
  speak("No speech detected.")
@@ -25,4 +27,4 @@ def listen(prompt=None, timeout=5):
25
27
  speak("Sorry, I didn’t catch that.")
26
28
  except sr.RequestError:
27
29
  speak("Speech recognition failed. Check your internet.")
28
- return None
30
+ return None