-
Notifications
You must be signed in to change notification settings - Fork 1
/
repository_context.txt
546 lines (447 loc) · 17 KB
/
repository_context.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<repository_structure>
<directory name="llm_prompt_manager">
<file>
<name>.gitignore</name>
<path>.gitignore</path>
<content>Full content not provided</content>
</file>
<file>
<name>README.md</name>
<path>README.md</path>
<content>
# Prompt Manager
Prompt Manager is a flexible system for managing and processing prompt templates for use with language models. It simplifies the process of loading, managing, and formatting prompts, allowing you to focus on developing your AI applications.
## Features
- Load prompts from text files or direct text input
- Insert variables into prompts using double braces `{{variable}}`
- Handle various file types and encoding issues with a universal file opener
- Flexible API for ease of use
## Installation
Install the package using pip:
```sh
pip install prompt_manager
```
## Usage
### Basic Usage
To load and process a template named `example_template` with no dependencies:
```python
from prompt_manager import PromptManager
# Initialize the PromptManager with the path to the prompts folder
pm = PromptManager("path/to/prompts/folder")
# Load a prompt template and insert variables
prompt = pm.get_prompt("example_template.txt", name="John Doe", age=30)
print(prompt)
```
### Using Direct Text Prompts
To use a direct text prompt and replace placeholders with direct values:
```python
from prompt_manager import PromptManager
pm = PromptManager()
# Use a direct text prompt
prompt = pm.get_prompt("Hello, {{name}}!", name="Alice")
print(prompt)
```
### Loading File Content as Variables
To load and process a template and replace placeholders with the content of other files:
```python
from prompt_manager import PromptManager
pm = PromptManager("path/to/prompts/folder")
# Load a prompt template and insert file content as variables
prompt = pm.get_prompt("example_template.txt", variable1=pm.load_file("sub_template1.txt"), variable2=pm.load_file("sub_template2.txt"))
print(prompt)
```
## Exception Handling
- Raises `FileNotFoundError` if the template file does not exist.
- Raises `ValueError` if required placeholders are not provided or if there are issues with file dependencies.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Contributing
If you have suggestions for improvements, feel free to submit a pull request or open an issue.
## Contact
Author: Bryan Anye
Email: [email protected]
GitHub: [BryanNsoh](https://github.com/BryanNsoh)
</content>
</file>
<file>
<name>repo_context_extractor.py</name>
<path>repo_context_extractor.py</path>
<content>
import os
EXCLUDED_DIRS = {".git", "__pycache__", "node_modules", ".venv"}
FULL_CONTENT_EXTENSIONS = {".py", ".txt", ".dbml", ".yaml", ".toml", ".md",".sh",".ps1", }
def create_file_element(file_path, root_folder):
relative_path = os.path.relpath(file_path, root_folder)
file_name = os.path.basename(file_path)
file_extension = os.path.splitext(file_name)[1]
file_element = [
f" <file>\n <name>{file_name}</name>\n <path>{relative_path}</path>\n"
]
if file_extension in FULL_CONTENT_EXTENSIONS:
file_element.append(" <content>\n")
try:
with open(file_path, "r", encoding="utf-8") as file:
file_element.append(file.read())
except UnicodeDecodeError:
file_element.append("Binary or non-UTF-8 content not displayed")
file_element.append("\n </content>\n")
else:
file_element.append(" <content>Full content not provided</content>\n")
file_element.append(" </file>\n")
return "".join(file_element)
def get_repo_structure(root_folder):
structure = ["<repository_structure>\n"]
for subdir, dirs, files in os.walk(root_folder):
dirs[:] = [d for d in dirs if d not in EXCLUDED_DIRS]
level = subdir.replace(root_folder, "").count(os.sep)
indent = " " * 4 * level
relative_subdir = os.path.relpath(subdir, root_folder)
structure.append(f'{indent}<directory name="{os.path.basename(subdir)}">\n')
for file in files:
file_path = os.path.join(subdir, file)
file_element = create_file_element(file_path, root_folder)
structure.append(file_element)
structure.append(f"{indent}</directory>\n")
structure.append("</repository_structure>\n")
return "".join(structure)
def main():
root_folder = r"C:\Users\bnsoh2\OneDrive - University of Nebraska-Lincoln\Documents\Projects\llm_prompt_manager"
output_file = os.path.join(root_folder, "repository_context.txt")
# Delete the previous output file if it exists
if os.path.exists(output_file):
os.remove(output_file)
print(f"Deleted previous {output_file}")
repo_structure = get_repo_structure(root_folder)
with open(output_file, "w", encoding="utf-8") as f:
f.write(repo_structure)
print(f"Fresh repository context has been extracted to {output_file}")
if __name__ == "__main__":
main()
</content>
</file>
<file>
<name>setup.py</name>
<path>setup.py</path>
<content>
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="llm_prompt_manager",
version="0.1.2",
author="Bryan Anye",
author_email="[email protected]",
description="A flexible system for managing and processing prompt templates",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/BryanNsoh/prompt_manager",
packages=find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
install_requires=[
"chardet",
],
)
</content>
</file>
</directory>
<directory name="build">
</directory>
<directory name="bdist.win-amd64">
</directory>
<directory name="lib">
</directory>
<directory name="llm_prompt_manager">
<file>
<name>core.py</name>
<path>build\lib\llm_prompt_manager\core.py</path>
<content>
"""
Prompt Manager: A flexible system for managing and processing prompt templates.
This module provides a PromptManager class that simplifies the process of loading,
managing, and formatting prompt templates for use with language models. It supports
loading prompts from files or direct text input, and allows for flexible variable
insertion.
Classes:
--------
PromptManager
Main class for managing prompts and their variables.
Functions:
----------
universal_file_opener(file_path: str) -> str
A utility function to open and read text from various file types.
Example Usage:
--------------
from prompt_manager import PromptManager
# Initialize the PromptManager
pm = PromptManager("path/to/prompts/folder")
# Load a prompt from a file and insert variables
prompt = pm.get_prompt("example_prompt",
variable1="value1",
variable2=pm.load_file("path/to/file.txt"))
# Use a direct text prompt
prompt = pm.get_prompt("This is a {{variable}} prompt", variable="test")
# The resulting prompt is ready to be sent to an LLM
"""
import os
import json
import chardet
def universal_file_opener(file_path):
"""Open and read text from various file types, handling encoding issues."""
try:
with open(file_path, 'rb') as file:
raw_data = file.read()
detected = chardet.detect(raw_data)
encoding = detected['encoding'] or 'utf-8'
return raw_data.decode(encoding)
except Exception as e:
raise ValueError(f"Error reading file {file_path}: {str(e)}")
class PromptManager:
def __init__(self, prompts_dir=None):
self.prompts_dir = prompts_dir
def load_file(self, file_path):
"""Load the content of a file given its path."""
if self.prompts_dir:
file_path = os.path.join(self.prompts_dir, file_path)
return universal_file_opener(file_path)
def _process_variable(self, value):
"""Process a variable, converting to string or loading file content if needed."""
if isinstance(value, str) and os.path.isfile(value):
return self.load_file(value)
return str(value)
def get_prompt(self, main_prompt, **kwargs):
"""
Generate the final prompt by replacing placeholders in the template with variable values.
:param main_prompt: Can be a filename, direct text, or a variable containing text
:param kwargs: Variables to be inserted into the prompt
:return: Formatted prompt string
"""
if self.prompts_dir and os.path.isfile(os.path.join(self.prompts_dir, main_prompt)):
template = self.load_file(main_prompt)
elif os.path.isfile(main_prompt):
template = self.load_file(main_prompt)
else:
template = main_prompt
processed_kwargs = {k: self._process_variable(v) for k, v in kwargs.items()}
try:
return template.format(**{k: f"{{{{{k}}}}}" for k in processed_kwargs.keys()}).format(**processed_kwargs)
except KeyError as e:
missing_key = str(e).strip("'")
raise ValueError(f"Missing argument for prompt: {missing_key}")
except Exception as e:
raise ValueError(f"Error formatting prompt: {str(e)}")
# Example usage
if __name__ == "__main__":
pm = PromptManager("prompts")
prompt = pm.get_prompt("example_template.txt", name="John", age=30)
print(prompt)
direct_prompt = pm.get_prompt("Hello, {{name}}!", name="Alice")
print(direct_prompt)
</content>
</file>
<file>
<name>__init__.py</name>
<path>build\lib\llm_prompt_manager\__init__.py</path>
<content>
from .core import PromptManager
</content>
</file>
</directory>
<directory name="dist">
<file>
<name>llm_prompt_manager-0.1.2-py3-none-any.whl</name>
<path>dist\llm_prompt_manager-0.1.2-py3-none-any.whl</path>
<content>Full content not provided</content>
</file>
<file>
<name>llm_prompt_manager-0.1.2.tar.gz</name>
<path>dist\llm_prompt_manager-0.1.2.tar.gz</path>
<content>Full content not provided</content>
</file>
</directory>
<directory name="llm_prompt_manager">
<file>
<name>core.py</name>
<path>llm_prompt_manager\core.py</path>
<content>
"""
Prompt Manager: A flexible system for managing and processing prompt templates.
This module provides a PromptManager class that simplifies the process of loading,
managing, and formatting prompt templates for use with language models. It supports
loading prompts from files or direct text input, and allows for flexible variable
insertion.
Classes:
--------
PromptManager
Main class for managing prompts and their variables.
Functions:
----------
universal_file_opener(file_path: str) -> str
A utility function to open and read text from various file types.
Example Usage:
--------------
from prompt_manager import PromptManager
# Initialize the PromptManager
pm = PromptManager("path/to/prompts/folder")
# Load a prompt from a file and insert variables
prompt = pm.get_prompt("example_prompt",
variable1="value1",
variable2=pm.load_file("path/to/file.txt"))
# Use a direct text prompt
prompt = pm.get_prompt("This is a {{variable}} prompt", variable="test")
# The resulting prompt is ready to be sent to an LLM
"""
import os
import json
import chardet
def universal_file_opener(file_path):
"""Open and read text from various file types, handling encoding issues."""
try:
with open(file_path, 'rb') as file:
raw_data = file.read()
detected = chardet.detect(raw_data)
encoding = detected['encoding'] or 'utf-8'
return raw_data.decode(encoding)
except Exception as e:
raise ValueError(f"Error reading file {file_path}: {str(e)}")
class PromptManager:
def __init__(self, prompts_dir=None):
self.prompts_dir = prompts_dir
def load_file(self, file_path):
"""Load the content of a file given its path."""
if self.prompts_dir:
file_path = os.path.join(self.prompts_dir, file_path)
return universal_file_opener(file_path)
def _process_variable(self, value):
"""Process a variable, converting to string or loading file content if needed."""
if isinstance(value, str) and os.path.isfile(value):
return self.load_file(value)
return str(value)
def get_prompt(self, main_prompt, **kwargs):
"""
Generate the final prompt by replacing placeholders in the template with variable values.
:param main_prompt: Can be a filename, direct text, or a variable containing text
:param kwargs: Variables to be inserted into the prompt
:return: Formatted prompt string
"""
if self.prompts_dir and os.path.isfile(os.path.join(self.prompts_dir, main_prompt)):
template = self.load_file(main_prompt)
elif os.path.isfile(main_prompt):
template = self.load_file(main_prompt)
else:
template = main_prompt
processed_kwargs = {k: self._process_variable(v) for k, v in kwargs.items()}
try:
return template.format(**{k: f"{{{{{k}}}}}" for k in processed_kwargs.keys()}).format(**processed_kwargs)
except KeyError as e:
missing_key = str(e).strip("'")
raise ValueError(f"Missing argument for prompt: {missing_key}")
except Exception as e:
raise ValueError(f"Error formatting prompt: {str(e)}")
# Example usage
if __name__ == "__main__":
pm = PromptManager("prompts")
prompt = pm.get_prompt("example_template.txt", name="John", age=30)
print(prompt)
direct_prompt = pm.get_prompt("Hello, {{name}}!", name="Alice")
print(direct_prompt)
</content>
</file>
<file>
<name>__init__.py</name>
<path>llm_prompt_manager\__init__.py</path>
<content>
from .core import PromptManager
</content>
</file>
</directory>
<directory name="llm_prompt_manager.egg-info">
<file>
<name>dependency_links.txt</name>
<path>llm_prompt_manager.egg-info\dependency_links.txt</path>
<content>
</content>
</file>
<file>
<name>PKG-INFO</name>
<path>llm_prompt_manager.egg-info\PKG-INFO</path>
<content>Full content not provided</content>
</file>
<file>
<name>requires.txt</name>
<path>llm_prompt_manager.egg-info\requires.txt</path>
<content>
chardet
</content>
</file>
<file>
<name>SOURCES.txt</name>
<path>llm_prompt_manager.egg-info\SOURCES.txt</path>
<content>
README.md
setup.py
llm_prompt_manager/__init__.py
llm_prompt_manager/core.py
llm_prompt_manager.egg-info/PKG-INFO
llm_prompt_manager.egg-info/SOURCES.txt
llm_prompt_manager.egg-info/dependency_links.txt
llm_prompt_manager.egg-info/requires.txt
llm_prompt_manager.egg-info/top_level.txt
</content>
</file>
<file>
<name>top_level.txt</name>
<path>llm_prompt_manager.egg-info\top_level.txt</path>
<content>
llm_prompt_manager
</content>
</file>
</directory>
<directory name="tests">
<file>
<name>test_prompt_manager.py</name>
<path>tests\test_prompt_manager.py</path>
<content>
import unittest
from llm_prompt_manager.core import PromptManager
class TestPromptManager(unittest.TestCase):
def setUp(self):
self.pm = PromptManager("tests/prompts")
def test_load_file(self):
content = self.pm.load_file("test_template.txt")
self.assertIn("Hello, {{name}}!", content)
def test_get_prompt_with_file_template(self):
prompt = self.pm.get_prompt("test_template.txt", name="John")
self.assertIn("Hello, John!", prompt)
def test_get_prompt_with_direct_text(self):
prompt = self.pm.get_prompt("Hello, {{name}}!", name="Alice")
self.assertEqual(prompt, "Hello, Alice!")
def test_get_prompt_with_file_variable(self):
prompt = self.pm.get_prompt("Main template with {{sub_template}}", sub_template=self.pm.load_file("sub_template.txt"))
self.assertIn("Main template with This is a sub template.", prompt)
if __name__ == '__main__':
unittest.main()
</content>
</file>
</directory>
<directory name="prompts">
<file>
<name>sub_template.txt</name>
<path>tests\prompts\sub_template.txt</path>
<content>
This is a sub template.
</content>
</file>
<file>
<name>test_template.txt</name>
<path>tests\prompts\test_template.txt</path>
<content>
Hello, {{name}}!
</content>
</file>
</directory>
</repository_structure>