scriptmonkey 0.1.0__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,83 @@
1
+ Metadata-Version: 2.1
2
+ Name: scriptmonkey
3
+ Version: 0.1.0
4
+ Summary: A Python package that automatically fixes errors in your code using OpenAI's GPT API
5
+ Home-page: https://github.com/lukerbs/CodeMonkey
6
+ Author: Luke Kerbs
7
+ Author-email: LDK.kerbs@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: openai
15
+ Requires-Dist: pydantic
16
+ Requires-Dist: tqdm
17
+
18
+
19
+ # ScriptMonkey 🐒
20
+
21
+ ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
22
+
23
+ ## Features
24
+ - **Automatic error detection**: Captures errors during runtime.
25
+ - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
26
+ - **Code auto-correction**: Automatically updates your Python files with the fixes.
27
+ - **Cross-IDE compatibility**: Works with any IDE or code editor.
28
+
29
+ ## Installation
30
+
31
+ To install ScriptMonkey, simply run:
32
+
33
+ ```bash
34
+ pip install scriptmonkey
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ 1. Import `scriptmonkey` in your Python script.
40
+ 2. Call `scriptmonkey.run()` to activate the error handler.
41
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
42
+
43
+ ### Example
44
+
45
+ ```python
46
+ import scriptmonkey
47
+
48
+ # Enable Codemonkey's error handler
49
+ scriptmonkey.run()
50
+
51
+ # Intentional error for testing
52
+ def add(a, b):
53
+ return a + b # This will fail if b is a string
54
+
55
+ print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
56
+ ```
57
+
58
+ Once an error occurs, ScriptMonkey will:
59
+ 1. Detect the error.
60
+ 2. Send the error and code to OpenAI for analysis.
61
+ 3. Provide a solution and automatically update the file with the correct code.
62
+
63
+ ## How It Works
64
+
65
+ ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
66
+ - Collects the traceback and the Python file that caused the error.
67
+ - Sends the error message and code to OpenAI.
68
+ - Receives the solution as structured JSON.
69
+ - Applies the fix directly to the source file.
70
+
71
+ ## Requirements
72
+ - Python 3.6 or later
73
+ - OpenAI API key
74
+
75
+ ## Setup
76
+
77
+ To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
78
+
79
+ ```bash
80
+ export OPENAI_API_KEY='your-api-key'
81
+ ```
82
+
83
+ Let ScriptMonkey take care of your Python errors so you can focus on building!
@@ -0,0 +1,66 @@
1
+
2
+ # ScriptMonkey 🐒
3
+
4
+ ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
5
+
6
+ ## Features
7
+ - **Automatic error detection**: Captures errors during runtime.
8
+ - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
9
+ - **Code auto-correction**: Automatically updates your Python files with the fixes.
10
+ - **Cross-IDE compatibility**: Works with any IDE or code editor.
11
+
12
+ ## Installation
13
+
14
+ To install ScriptMonkey, simply run:
15
+
16
+ ```bash
17
+ pip install scriptmonkey
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ 1. Import `scriptmonkey` in your Python script.
23
+ 2. Call `scriptmonkey.run()` to activate the error handler.
24
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
25
+
26
+ ### Example
27
+
28
+ ```python
29
+ import scriptmonkey
30
+
31
+ # Enable Codemonkey's error handler
32
+ scriptmonkey.run()
33
+
34
+ # Intentional error for testing
35
+ def add(a, b):
36
+ return a + b # This will fail if b is a string
37
+
38
+ print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
39
+ ```
40
+
41
+ Once an error occurs, ScriptMonkey will:
42
+ 1. Detect the error.
43
+ 2. Send the error and code to OpenAI for analysis.
44
+ 3. Provide a solution and automatically update the file with the correct code.
45
+
46
+ ## How It Works
47
+
48
+ ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
49
+ - Collects the traceback and the Python file that caused the error.
50
+ - Sends the error message and code to OpenAI.
51
+ - Receives the solution as structured JSON.
52
+ - Applies the fix directly to the source file.
53
+
54
+ ## Requirements
55
+ - Python 3.6 or later
56
+ - OpenAI API key
57
+
58
+ ## Setup
59
+
60
+ To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
61
+
62
+ ```bash
63
+ export OPENAI_API_KEY='your-api-key'
64
+ ```
65
+
66
+ Let ScriptMonkey take care of your Python errors so you can focus on building!
@@ -0,0 +1 @@
1
+ from .core import run
@@ -0,0 +1,72 @@
1
+ import sys
2
+ import traceback
3
+ from .openai_client import chatgpt_json, ScriptMonkeyResponse, default_prompts
4
+ from .file_handler import read_file, write_file
5
+ import platform
6
+ import threading
7
+ import itertools
8
+ import time
9
+
10
+
11
+ def get_platform():
12
+ os_name = platform.system()
13
+ os_version = platform.release()
14
+ return f"# Operating System: {os_name}, Version: {os_version}\n\n"
15
+
16
+
17
+ class Spinner:
18
+ def __init__(self, message="Processing"):
19
+ self.spinner = itertools.cycle(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])
20
+ self.stop_running = threading.Event()
21
+ self.spin_thread = None
22
+ self.message = message
23
+
24
+ def spin(self):
25
+ while not self.stop_running.is_set():
26
+ sys.stdout.write(f"\r{self.message} {next(self.spinner)}")
27
+ sys.stdout.flush()
28
+ time.sleep(0.1)
29
+ sys.stdout.write("\r" + " " * (len(self.message) + 2) + "\r")
30
+ sys.stdout.flush()
31
+
32
+ def __enter__(self):
33
+ self.spin_thread = threading.Thread(target=self.spin)
34
+ self.spin_thread.start()
35
+
36
+ def __exit__(self, exc_type, exc_val, exc_tb):
37
+ self.stop_running.set()
38
+ self.spin_thread.join()
39
+
40
+
41
+ def codemonkey_exception_handler(exc_type, exc_value, exc_traceback):
42
+ if issubclass(exc_type, KeyboardInterrupt):
43
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
44
+ return
45
+
46
+ error_message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
47
+
48
+ print(f"\n🐒 ScriptMonkey Detected an Error:")
49
+ print(error_message, "\n")
50
+
51
+ frame = traceback.extract_tb(exc_traceback)[-1]
52
+ file_path = frame.filename
53
+
54
+ original_code = read_file(file_path)
55
+ content = f"{get_platform()}# Original Code:\n```\n{original_code}\n```\n\n# Error Message:\n{error_message}"
56
+
57
+ solution = None
58
+ with Spinner("🐒 ScriptMonkey is working on a solution"):
59
+ solution = chatgpt_json(
60
+ instructions=default_prompts.fix_error, content=content, response_format=ScriptMonkeyResponse
61
+ )
62
+
63
+ print(f"\n🐒 ScriptMonkey Fixed It:\nProblem:\n{solution['problem']}\n")
64
+ print(f"Suggested Solution:\n{solution['solution']}\n")
65
+
66
+ corrected_code = solution["corrected_code"].replace("```python", "").replace("```", "")
67
+ write_file(file_path, corrected_code)
68
+ print(f"🐒 ScriptMonkey automatically fixed your code at: '{file_path}'.")
69
+
70
+
71
+ def run():
72
+ sys.excepthook = codemonkey_exception_handler
@@ -0,0 +1,22 @@
1
+ def read_file(path: str) -> str:
2
+ """Loads a file and returns the content.
3
+
4
+ Args:
5
+ path (str): Path to the file
6
+
7
+ Returns:
8
+ str: The content of the file
9
+ """
10
+ with open(path, "r") as file:
11
+ return file.read()
12
+
13
+
14
+ def write_file(path: str, content: str) -> None:
15
+ """Writes string content to a file.
16
+
17
+ Args:
18
+ path (str): Path to the file.
19
+ content (str): Content to write to file.
20
+ """
21
+ with open(path, "w") as file:
22
+ file.write(content)
@@ -0,0 +1,12 @@
1
+ from .prompting import DefaultPrompts
2
+ from .client import chatgpt_json
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class ScriptMonkeyResponse(BaseModel):
7
+ problem: str # A description of the error/problem
8
+ solution: str # The solution to the problem
9
+ corrected_code: str # The corrected version of the Python code
10
+
11
+
12
+ default_prompts = DefaultPrompts()
@@ -0,0 +1,7 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class CodemonkeyResponse(BaseModel):
5
+ problem: str # A description of the error/problem
6
+ solution: str # The solution to the problem
7
+ corrected_code: str # The corrected version of the Python code
@@ -0,0 +1,59 @@
1
+ import os
2
+
3
+ from dotenv import load_dotenv
4
+ from pydantic import BaseModel
5
+ import openai
6
+
7
+ # Load the OpenAI API key from .env file
8
+ load_dotenv()
9
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
10
+ if OPENAI_API_KEY:
11
+ # Initialize openai API client
12
+ client = openai.OpenAI(api_key=OPENAI_API_KEY)
13
+ else:
14
+ raise ValueError("Missing OpenAI API Key. Please check your environment variables.")
15
+
16
+
17
+ def chatgpt_json(instructions: str, content: str, response_format: BaseModel) -> dict:
18
+ """This function is used to return content from OpenAI Chat Completions API as a structured dictionary response.
19
+
20
+ Args:
21
+ instructions (str): Instructions for the LLM (how the LLM should process the input content).
22
+ content (str): Information that the LLM is supposed to process.
23
+ response_format (BaseModel): The output format defined by a Pydantic Basemodel.
24
+
25
+ Returns:
26
+ dict: The structured output response from the LLM.
27
+ """
28
+ completion = client.beta.chat.completions.parse(
29
+ model="gpt-4o-2024-08-06",
30
+ messages=[
31
+ {"role": "system", "content": instructions},
32
+ {"role": "user", "content": content},
33
+ ],
34
+ response_format=response_format,
35
+ )
36
+
37
+ structured_response = completion.choices[0].message.parsed
38
+ return structured_response.model_dump()
39
+
40
+
41
+ def chatgpt(prompt: str, model="gpt-4o", max_tokens=None):
42
+ """Function for generating responses to text prompts with OpenAI's ChatGPT API
43
+
44
+ Args:
45
+ prompt (str): The instructions for ChatGPT to respond to
46
+ model (str, optional): ChatGPT model to use. Defaults to "gpt-4o".
47
+ - List of Available Models: https://platform.openai.com/docs/models/continuous-model-upgrades
48
+ max_tokens (int, optional): Optional, the max tokens to be returned by response. Defaults to no limit (i.e. None).
49
+
50
+ Returns:
51
+ str: Returns the response to the prompt as a string value
52
+ """
53
+ completion = client.chat.completions.create(
54
+ model=model,
55
+ max_tokens=max_tokens,
56
+ messages=[{"role": "user", "content": prompt}],
57
+ )
58
+ response = completion.choices[0].message.content
59
+ return response
@@ -0,0 +1,12 @@
1
+ import os
2
+
3
+
4
+ def load_prompt(path: str) -> str:
5
+ path = os.path.join(os.path.dirname(__file__), path)
6
+ with open(path, "r") as file:
7
+ return file.read()
8
+
9
+
10
+ class DefaultPrompts:
11
+ def __init__(self):
12
+ self.fix_error = load_prompt(path="./prompts/fix_error.txt")
@@ -0,0 +1,10 @@
1
+ You are a Python programming expert that helps solve Python code errors.
2
+ When you fix Python code, your improvements should be well designed and follow Python best practices.
3
+ While you are at it, also make improvements like:
4
+ - Improving the code structure, formatting, and readability.
5
+ - Adding type hints to functions and classes.
6
+ - Organizing import statements.
7
+ - Leave short comments in the code describing the fix, and always start your explanations of fixes with: "SCRIPTMONKEY: "
8
+ NEVER remove any code related to scriptmonkey imports or statements.
9
+ - scriptmonkey.run() should always be the first statement in the file after the imports
10
+ Return the solution in a structured JSON format.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.1
2
+ Name: scriptmonkey
3
+ Version: 0.1.0
4
+ Summary: A Python package that automatically fixes errors in your code using OpenAI's GPT API
5
+ Home-page: https://github.com/lukerbs/CodeMonkey
6
+ Author: Luke Kerbs
7
+ Author-email: LDK.kerbs@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: openai
15
+ Requires-Dist: pydantic
16
+ Requires-Dist: tqdm
17
+
18
+
19
+ # ScriptMonkey 🐒
20
+
21
+ ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
22
+
23
+ ## Features
24
+ - **Automatic error detection**: Captures errors during runtime.
25
+ - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
26
+ - **Code auto-correction**: Automatically updates your Python files with the fixes.
27
+ - **Cross-IDE compatibility**: Works with any IDE or code editor.
28
+
29
+ ## Installation
30
+
31
+ To install ScriptMonkey, simply run:
32
+
33
+ ```bash
34
+ pip install scriptmonkey
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ 1. Import `scriptmonkey` in your Python script.
40
+ 2. Call `scriptmonkey.run()` to activate the error handler.
41
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
42
+
43
+ ### Example
44
+
45
+ ```python
46
+ import scriptmonkey
47
+
48
+ # Enable Codemonkey's error handler
49
+ scriptmonkey.run()
50
+
51
+ # Intentional error for testing
52
+ def add(a, b):
53
+ return a + b # This will fail if b is a string
54
+
55
+ print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
56
+ ```
57
+
58
+ Once an error occurs, ScriptMonkey will:
59
+ 1. Detect the error.
60
+ 2. Send the error and code to OpenAI for analysis.
61
+ 3. Provide a solution and automatically update the file with the correct code.
62
+
63
+ ## How It Works
64
+
65
+ ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
66
+ - Collects the traceback and the Python file that caused the error.
67
+ - Sends the error message and code to OpenAI.
68
+ - Receives the solution as structured JSON.
69
+ - Applies the fix directly to the source file.
70
+
71
+ ## Requirements
72
+ - Python 3.6 or later
73
+ - OpenAI API key
74
+
75
+ ## Setup
76
+
77
+ To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
78
+
79
+ ```bash
80
+ export OPENAI_API_KEY='your-api-key'
81
+ ```
82
+
83
+ Let ScriptMonkey take care of your Python errors so you can focus on building!
@@ -0,0 +1,15 @@
1
+ README.md
2
+ setup.py
3
+ scriptmonkey/__init__.py
4
+ scriptmonkey/core.py
5
+ scriptmonkey/file_handler.py
6
+ scriptmonkey.egg-info/PKG-INFO
7
+ scriptmonkey.egg-info/SOURCES.txt
8
+ scriptmonkey.egg-info/dependency_links.txt
9
+ scriptmonkey.egg-info/requires.txt
10
+ scriptmonkey.egg-info/top_level.txt
11
+ scriptmonkey/openai_client/__init__.py
12
+ scriptmonkey/openai_client/basemodels.py
13
+ scriptmonkey/openai_client/client.py
14
+ scriptmonkey/openai_client/prompting.py
15
+ scriptmonkey/openai_client/prompts/fix_error.txt
@@ -0,0 +1,3 @@
1
+ openai
2
+ pydantic
3
+ tqdm
@@ -0,0 +1 @@
1
+ scriptmonkey
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,23 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="scriptmonkey",
5
+ version="0.1.0",
6
+ description="A Python package that automatically fixes errors in your code using OpenAI's GPT API",
7
+ long_description=open("README.md", "r").read(),
8
+ long_description_content_type="text/markdown",
9
+ url="https://github.com/lukerbs/CodeMonkey",
10
+ author="Luke Kerbs",
11
+ author_email="LDK.kerbs@gmail.com",
12
+ license="MIT",
13
+ packages=find_packages(),
14
+ install_requires=["openai", "pydantic", "tqdm"],
15
+ python_requires=">=3.6", # Minimum Python version
16
+ classifiers=[
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ ],
21
+ package_data={"scriptmonkey.openai_client": ["prompts/*.txt"]},
22
+ include_package_data=True,
23
+ )