├── requirements.txt ├── .gitignore ├── bitefix ├── __init__.py ├── BiteFixAICrew.py ├── BiteFixAIRunner.py ├── BiteFixAITasks.py ├── bitefix_utils.py └── BiteFixAIAgents.py ├── assets └── max_profit_bitefix_demo.png ├── setup.cfg ├── LICENSE ├── .github └── workflows │ └── publish.yml ├── setup.py └── README.md /requirements.txt: -------------------------------------------------------------------------------- 1 | crewai==0.14.4 2 | langchain==0.1.9 3 | crewai-tools==0.0.12 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .talismanrc 2 | .DS_Store 3 | venv/ 4 | .talismanrc 5 | build/ 6 | dist/ 7 | bitefix.egg-info/ -------------------------------------------------------------------------------- /bitefix/__init__.py: -------------------------------------------------------------------------------- 1 | from .bitefix_utils import resolve 2 | from .bitefix_utils import resolve_with_openai 3 | -------------------------------------------------------------------------------- /assets/max_profit_bitefix_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pallavi-Sinha-12/bitefix/HEAD/assets/max_profit_bitefix_demo.png -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = bitefix 3 | version = 1.0.2 4 | author = Pallavi Sinha 5 | author_email = dataaienthusiast128@gmail.com 6 | description = Bitefix is an efficient library designed to streamline Python Runtime error debugging with Multi agent AI-powered decorators. 7 | license = MIT 8 | home-page = https://github.com/Pallavi-Sinha-12/bitefix -------------------------------------------------------------------------------- /bitefix/BiteFixAICrew.py: -------------------------------------------------------------------------------- 1 | from crewai import Crew, Process, Agent, Task 2 | 3 | 4 | class BiteFixAICrew: 5 | 6 | """ 7 | This class represents a crew of Bite Fix AI agents involved in the decorated function code error fixing process. 8 | 9 | Attributes: 10 | agent (list[Agent]): List of AI Agents involved in the error fixing process. 11 | tasks (list[Task]): List of Tasks involved in the error fixing process. 12 | 13 | Methods: 14 | kickoff: Kicks off the crew. Returns the result of the agents. 15 | """ 16 | 17 | def __init__(self, agent: list[Agent], tasks: list[Task]): 18 | self.agent = agent 19 | self.tasks = tasks 20 | 21 | def kickoff(self) -> dict: 22 | crew = Crew( 23 | agents=self.agent, 24 | tasks=self.tasks, 25 | verbose=False, 26 | process=Process.sequential, 27 | full_output=True, 28 | ) 29 | result = crew.kickoff() 30 | return result 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Pallavi Sinha 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distributions 📦 to PyPI 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | build-n-publish: 9 | name: Build and publish Python 🐍 distributions 📦 to PyPI 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | 14 | - name: Set up Python 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: 3.11 18 | 19 | - name: Install pip 20 | run: python -m pip install --upgrade pip 21 | 22 | - name: Install dependencies 23 | run: pip install -r requirements.txt 24 | 25 | - name : Install black 26 | run: pip install black 27 | 28 | - name: Run black 29 | run: black . 30 | 31 | - name: Install build 32 | run: python -m pip install build 33 | 34 | - name: Build a binary wheel and a source tarball 35 | run: python -m build --sdist --wheel --outdir dist/ 36 | 37 | - name: Publish distribution 📦 to PyPI 38 | uses: pypa/gh-action-pypi-publish@release/v1 39 | with: 40 | user: __token__ 41 | password: ${{ secrets.PYPI_API_TOKEN }} -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | with open("requirements.txt") as f: 7 | required = f.read().splitlines() 8 | 9 | setup( 10 | name="bitefix", 11 | version="1.0.2", 12 | description="""Bitefix is an efficient library designed to streamline Python Runtime error debugging with AI-powered decorators. 13 | It initializes a crew of AI agents which work together to diagnose the error, generate ideas to fix the error, 14 | evaluate the ideas to choose the best and develop the code to fix the error that occurred.""", 15 | long_description=long_description, 16 | long_description_content_type="text/markdown", 17 | author="Pallavi Sinha", 18 | packages=find_packages(include=["bitefix"]), 19 | classifiers=[ 20 | "Programming Language :: Python :: 3", 21 | "License :: OSI Approved :: MIT License", 22 | "Operating System :: OS Independent", 23 | ], 24 | install_requires=required, 25 | license="MIT", 26 | url="https://github.com/Pallavi-Sinha-12/bitefix", 27 | python_requires=">=3.10", 28 | ) 29 | -------------------------------------------------------------------------------- /bitefix/BiteFixAIRunner.py: -------------------------------------------------------------------------------- 1 | from bitefix.BiteFixAIAgents import BiteFixAIAgents 2 | from bitefix.BiteFixAITasks import BiteFixAITasks 3 | from bitefix.BiteFixAICrew import BiteFixAICrew 4 | from typing import Any, Tuple 5 | 6 | 7 | class BiteFixAIRunner: 8 | 9 | """ 10 | This class is responsible for running the BiteFixAICrew. 11 | 12 | Attributes: 13 | function_code (str): The function code. 14 | arguments (Tuple[Any, ...]): The arguments passed to the function. 15 | error_message (str): The error message. 16 | llm (object): The LLM object. 17 | 18 | Methods: 19 | run: Initializes the Bite Fix AI Agents and Tasks involved in the error fixing process and passes them to the Bite Fix AI Crew to kickoff. 20 | """ 21 | 22 | def __init__( 23 | self, 24 | function_code: str, 25 | function_description: str, 26 | arguments: Tuple[Any, ...], 27 | error_message: str, 28 | llm: object, 29 | ): 30 | self.function_code = function_code 31 | self.function_description = function_description 32 | self.arguments = arguments 33 | self.error_message = error_message 34 | self.llm = llm 35 | 36 | def run(self) -> dict: 37 | biteFixAIAgents = BiteFixAIAgents( 38 | llm=self.llm, 39 | ) 40 | 41 | biteFixAITasks = BiteFixAITasks( 42 | function_code=self.function_code, 43 | function_description=self.function_description, 44 | arguments=self.arguments, 45 | error_message=self.error_message, 46 | ) 47 | 48 | diagnosisAgent = biteFixAIAgents.DiagnosisAgent() 49 | ideaGeneratorAgent = biteFixAIAgents.IdeaGeneratorAgent() 50 | ideasEvaluatorAgent = biteFixAIAgents.IdeasEvaluatorAgent() 51 | codeDeveloperAgent = biteFixAIAgents.CodeDeveloperAgent() 52 | 53 | diagnosisTask = biteFixAITasks.DiagnosisTask(agent=diagnosisAgent) 54 | ideaGenerationTask = biteFixAITasks.IdeaGenerationTask(agent=ideaGeneratorAgent) 55 | ideasEvaluationTask = biteFixAITasks.IdeasEvaluationTask( 56 | agent=ideasEvaluatorAgent 57 | ) 58 | codeDevelopmentTask = biteFixAITasks.CodeDevelopmentTask( 59 | agent=codeDeveloperAgent 60 | ) 61 | 62 | biteFixAICrew = BiteFixAICrew( 63 | agent=[ 64 | diagnosisAgent, 65 | ideaGeneratorAgent, 66 | ideasEvaluatorAgent, 67 | codeDeveloperAgent, 68 | ], 69 | tasks=[ 70 | diagnosisTask, 71 | ideaGenerationTask, 72 | ideasEvaluationTask, 73 | codeDevelopmentTask, 74 | ], 75 | ) 76 | 77 | result = biteFixAICrew.kickoff() 78 | return result 79 | -------------------------------------------------------------------------------- /bitefix/BiteFixAITasks.py: -------------------------------------------------------------------------------- 1 | from crewai import Agent, Task 2 | from typing import Any, Tuple 3 | 4 | 5 | class BiteFixAITasks: 6 | 7 | """ 8 | This class is responsible for creating the tasks for the BiteFixAI task. 9 | The tasks are the steps involved in the process of fixing the error in the decorated python function. 10 | 11 | Attributes: 12 | function_code (str): The function code. 13 | arguments (Tuple[Any, ...]): The arguments passed to the function. 14 | error_message (str): The error message. 15 | 16 | Methods: 17 | DiagnosisTask: Returns a task responsible for diagnosing the error. 18 | IdeaGenerationTask: Returns a task responsible for generating ideas to fix the error. 19 | IdeasEvaluationTask: Returns a task responsible for evaluating and choosing the best idea to fix the error. 20 | CodeDevelopmentTask: Returns a task responsible for writing the code to fix the error. 21 | """ 22 | 23 | def __init__( 24 | self, 25 | function_code: str, 26 | function_description: str, 27 | arguments: Tuple[Any, ...], 28 | error_message: str, 29 | ): 30 | self.function_code = function_code 31 | self.function_description = function_description 32 | self.arguments = arguments 33 | self.error_message = error_message 34 | self.function_description_block = ( 35 | f"The function description is given to you here - {self.function_description}. " 36 | if self.function_description 37 | else "" 38 | ) 39 | 40 | def DiagnosisTask(self, agent: Agent) -> Task: 41 | return Task( 42 | description=f"""Go through the function code, arguments passed and the error message and explain why the error occured. 43 | Explain why the function failed for the arguments passed. Explain it in normal human language. 44 | The function code is given to you here - {self.function_code}. 45 | {self.function_description_block} 46 | The arguments passed are given to you here - {self.arguments}. 47 | The error message is given to you here - {self.error_message}.""", 48 | agent=agent, 49 | ) 50 | 51 | def IdeaGenerationTask(self, agent: Agent) -> Task: 52 | return Task( 53 | description=f"""Generate ideas on how to fix the error in normal human language. 54 | You also think of best practices and efficiency while suggesting the ideas. 55 | Consider the below given information while generating ideas: 56 | The function code is given to you here - {self.function_code}. 57 | {self.function_description_block} 58 | The arguments passed are given to you here - {self.arguments}. 59 | The error message is given to you here - {self.error_message}. """, 60 | agent=agent, 61 | ) 62 | 63 | def IdeasEvaluationTask(self, agent: Agent) -> Task: 64 | return Task( 65 | description=f"""Evaluate the error fix ideas and choose the best idea to fix the error. 66 | Also explain your decision to fix the error in normal human language. 67 | Also think of best practices and efficiency while evaluating the ideas. 68 | Take a look on below given information while evaluating the ideas as well if needed: 69 | The function code is given to you here - {self.function_code}. 70 | {self.function_description_block} 71 | The arguments passed are given to you here - {self.arguments}. 72 | The error message is given to you here - {self.error_message}.""", 73 | agent=agent, 74 | ) 75 | 76 | def CodeDevelopmentTask(self, agent: Agent) -> Task: 77 | return Task( 78 | description=f"""Rewrite the function code to fix the error based on the idea chosen. 79 | Also explain the implementation details in normal human language. 80 | The function code is given to you here - {self.function_code}. 81 | {self.function_description_block} 82 | The arguments passed are given to you here - {self.arguments}. 83 | The error message is given to you here - {self.error_message}. """, 84 | agent=agent, 85 | ) 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BiteFix 🛠️ 2 | 3 | ![Last commit](https://img.shields.io/github/last-commit/Pallavi-Sinha-12/bitefix?color=green&label=Last%20commit) 4 | ![Repo size](https://img.shields.io/github/repo-size/Pallavi-Sinha-12/bitefix?color=orange&label=Repo%20size) 5 | [![Stars](https://img.shields.io/github/stars/Pallavi-Sinha-12/bitefix?color=yellow&label=Stars)](https://github.com/Pallavi-Sinha-12/Expense-Tracker-Chatbot/stargazers) 6 | [![Forks](https://img.shields.io/github/forks/Pallavi-Sinha-12/bitefix?color=orange&label=Forks)](https://github.com/Pallavi-Sinha-12/bitefix/forks) 7 | 8 | 9 | BiteFix is an advanced and efficient Python library designed to revolutionize the error-fixing process which leverages multi agents framework concept to provide a seamless debugging experience. It offers decorators to help you debug your code when the function throws runtime errors. 10 | 11 | ## Table of Contents 📋 12 | 13 | - [Introduction](#Introduction) 14 | - [Technologies Used](#Technologies-Used) 15 | - [Getting Started](#Getting-Started) 16 | - [Examples](#Examples) 17 | - [Contributing](#Contributing) 18 | - [Feedback](#Feedback) 19 | - [Conclusion](#Conclusion) 20 | - [Contact](#Contact) 21 | - [License](#License) 22 | - [References](#References) 23 | 24 | ## Introduction 25 | 26 | By offering decorators, BiteFix empowers you to enhance the error-handling experience in your functions. When a decorated function encounters an error, the decorator orchestrates a team of AI Agents, each specializing in a unique aspect of error resolution. Here's a brief overview of the AI Agents: 27 | 28 | 🕵️ **Python code Diagnosis Expert**: Swiftly analyzes the code to pinpoint the root cause of the error. 29 | 30 | 👨‍💻 **Senior Python Developer**: Provides insightful ideas on how to rectify the issue within the decorated function's code. 31 | 32 | 👩‍💼 **Lead Python Developer**: Meticulously evaluates ideas, selecting the most effective one for implementation. 33 | 34 | 👨‍💻 **Python Code Developer**: Skillfully rewrites the code to bring the chosen idea to life, ultimately fixing the error. 35 | 36 | BiteFix simplifies the error-fixing journey by seamlessly combining the expertise of these AI Agents, ensuring a smoother and more efficient debugging process for your Python code. 37 | 38 | 39 | ## Technologies-Used 40 | 41 | - [![Python](https://img.shields.io/badge/Python-3.11-blue)](https://www.python.org/) 42 | - [![langchain](https://img.shields.io/badge/langchain-0.1.1-yellow)](https://api.python.langchain.com/en/latest/langchain_api_reference.html#) 43 | - [![crewai](https://img.shields.io/badge/crewai-0.1.2-green)](https://github.com/joaomdmoura/crewAI.git) 44 | - [![gpt-4](https://img.shields.io/badge/gpt-4-orange)](https://openai.com/) 45 | 46 | ## Getting-Started 47 | 48 | - Install BiteFix using `pip install bitefix` 49 | - Explore the powerful decorators to streamline your error-fixing process! 50 | - Check out the [examples](#examples) to understand how BiteFix works. 51 | 52 | Happy Coding! 🚀 53 | 54 | ## Examples 55 | 56 | Let's take a look at some examples to understand how BiteFix works. Bitefix offers two decorators: `@resolve` and `@resolve_with_openai`. 57 | 58 | ### Example 1 : Using Open AI Models 59 | 60 | Let's say you have a function that calculates the maximum profit that can be obtained from a given array of stock prices. 61 | We will use `@resolve_with_openai` decorator with our function to help us resolve the error if some runtime error occurs while executing the function. 62 | 63 | ```python 64 | 65 | from bitefix import resolve_with_openai 66 | 67 | function_description = """ 68 | This function calculates the maximum profit that can be obtained from a given array of stock prices, aiding in financial analysis. 69 | Stock prices represent daily closing prices of a stock over time, obtained from financial data sources. 70 | """ 71 | 72 | @resolve_with_openai(openai_api_key="YOUR_OPENAI_KEY", model_name="gpt-4", function_description= function_description, export_dir="logs", verbose=True) 73 | def max_profit(stock_prices): 74 | 75 | min_price = stock_prices[0] 76 | max_profit = 0 77 | 78 | for price in stock_prices[1:]: 79 | min_price = min(min_price, price) 80 | max_profit = max(max_profit, price - min_price) 81 | 82 | return max_profit 83 | 84 | ``` 85 | 86 | `openai_api_key` : The OpenAI API key to use the OpenAI's model. You can get the API key from [here](https://beta.openai.com/account/api-keys). 87 | `model_name` (optional) : The name of the model to be used. By default, it uses OpenAI's gpt-4 model. 88 | `function_description` (optional) : The description of the function to be used to understand the context of the function. By default, it is set to None. 89 | `temperature` (optional) : The temperature parameter for the model. By default, it is set to 0.7. 90 | `export_dir` (optional) : The directory path to export Error Resoltion Report by BiteFix AI Agents and fixed code python file. It will export the report if a directory is provided. By default, it is set to None. 91 | `verbose` (optional) : If set to True, it will print the debugging steps. By default, it is set to True. 92 | 93 | Now, let's call the function and see how it works. 94 | 95 | ```python 96 | 97 | stock_prices = [7, 1, 5, 3, 6, 4, None] 98 | max_profit = max_profit(stock_prices) 99 | print("Maximum profit from stock market analysis:", max_profit) 100 | 101 | ``` 102 | 103 | Below is the Error Resolution Report generated by the decorator. 104 | ![Error Resolution Report](assets/max_profit_bitefix_demo.png) 105 | 106 | Here is the full demo for the above example - [bitefix_decorator_example](https://drive.google.com/file/d/1_5lOo9HZIhYyenV-Y0WG_TuCVIgTg9hT/view?usp=sharing) 107 | 108 | 109 | We can see how this decorator provided us step by step debugging of the function in case of failure by using crew of Python AI coders. It also provided us with the solution to the error. 110 | 111 | ### Example 2 : Using Open Source Models 112 | 113 | If we want to use some other Large Language Model instead of OpenAI, we can use `@resolve` decorator with our function to help us resolve the error if the function fails while execution. This helps us to use any custom trained model as well for error resolution. 114 | 115 | For this example, let's use Openhermes model from Ollama. You can download Ollama from [here](https://ollama.ai/). Ollama allows you to run open-source large language models, such as Openhermes, Llama 2, locally. 116 | 117 | After downloading Ollama, install it. Then run the following command to pull the Openhermes model. 118 | 119 | ```bash 120 | ollama pull openhermes 121 | ``` 122 | 123 | Now, we can use the model with the decorator `@resolve` as follows. 124 | 125 | ```python 126 | 127 | from bitefix import resolve 128 | from langchain_community.llms.ollama import Ollama 129 | 130 | llm = Ollama(model = "openhermes") 131 | 132 | function_description = """ 133 | This function calculates the maximum profit that can be obtained from a given array of stock prices, aiding in financial analysis. 134 | Stock prices represent daily closing prices of a stock over time, obtained from financial data sources. 135 | """ 136 | 137 | @resolve(llm = llm, function_description= function_description, export_dir="logs", verbose=True) 138 | def max_profit(stock_prices): 139 | 140 | min_price = stock_prices[0] 141 | max_profit = 0 142 | 143 | for price in stock_prices[1:]: 144 | min_price = min(min_price, price) 145 | max_profit = max(max_profit, price - min_price) 146 | 147 | return max_profit 148 | 149 | stock_prices = [7, 1, 5, 3, 6, 4, None] 150 | max_profit = max_profit(stock_prices) 151 | print("Maximum profit from stock market analysis:", max_profit) 152 | 153 | 154 | ``` 155 | 156 | Note : Here `function_description`, `export_dir` and `verbose` are optional parameters. 157 | 158 | Similarly, we can use any other Large Language Model with the decorator. 159 | 160 | ## Contributing 161 | 162 | Contributions are always welcome! 163 | 164 | If you find any issue or have suggestions for improvements, please submit them as Github issues or pull requests. 165 | 166 | Here is the steps you can follow to contribute to this project: 167 | 168 | 1. Fork the project on Github. 169 | 2. Clone the forked project to your local machine. 170 | 3. Create a virtual environment using `python -m venv venv`. 171 | 4. Activate the virtual environment using `venv\Scripts\activate` on Windows or `source venv/bin/activate` on Mac/Linux 172 | 5. Install the dependencies using `pip install -r requirements.txt`. 173 | 6. Make the required changes. 174 | 7. Format the code using `black .`. 175 | 8. Create a pull request. 176 | 177 | 178 | ## Feedback 179 | 180 | 'bitefix' library is just a small step towards making the error-fixing process more efficient using the capabilities of Large Language Models. We have to go a long way to make this better. 181 | Feel free to send me feedback at dataaienthusiast128@gmail.com. Let me know if you have any suggestions on how to make this project better. 182 | 183 | If you liked the project support it by giving a star :star: to this repo. 184 | 185 | ## Conclusion 186 | 187 | - BiteFix is a powerful Python library that leverages the capabilities of Large Language Models to streamline the error-fixing process in Python. By offering decorators that orchestrate a team of AI Agents, BiteFix helps you resolve the runtime errors in your code efficiently. 188 | - ONE IMPORTANT OBSERVATION IS THAT CURRENTLY BITEFIX SHOWS GOOD RESULTS WITH INDEPENDENT FUNCTIONS. FOR FUNCTIONS WHICH CAN HAVE NESTED FUNCTIONS OR CLASSES, THE RESULTS MAY VARY. IN THOSE CASES, WE CAN CHOOSE TO GIVE THE FUNCTION DESCRIPTION TO THE DECORATOR TO GET BETTER RESULTS. 189 | 190 | ## Contact 191 | [![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/pallavi-sinha-09540917b/)[![GitHub](https://img.shields.io/badge/GitHub-555555?style=for-the-badge&logo=github&logoColor=white&)](https://github.com/Pallavi-Sinha-12) 192 | 193 | ## License 194 | 195 | This project is licensed under the terms of the [MIT license](https://choosealicense.com/licenses/mit/) 196 | 197 | ## References 198 | 199 | - crewAI: Cutting-edge framework for orchestrating role-playing, autonomous AI agents. https://github.com/joaomdmoura/crewAI 200 | 201 | - langchain: Python library for interacting with the Langchain API. https://api.python.langchain.com/en/latest/langchain_api_reference.html# 202 | 203 | - OpenAI: OpenAI is an artificial intelligence research laboratory consisting of the for-profit corporation OpenAI LP and its parent company, the non-profit OpenAI Inc. https://openai.com/ 204 | 205 | - Ollama: Ollama allows you to run open-source large language models, such as Openhermes, Llama 2, locally. https://ollama.ai/ -------------------------------------------------------------------------------- /bitefix/bitefix_utils.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import os 3 | from typing import Any, Callable 4 | from langchain_openai import ChatOpenAI 5 | from bitefix.BiteFixAIRunner import BiteFixAIRunner 6 | from crewai.tasks.task_output import TaskOutput 7 | from typing import List 8 | from datetime import datetime 9 | 10 | def resolve_with_openai( 11 | openai_api_key: str, 12 | function_description: str = None, 13 | model_name: str = "gpt-4", 14 | temperature: float = 0.7, 15 | export_dir: str = None, 16 | verbose: bool = True, 17 | ) -> Callable: 18 | """ 19 | Bite Fix AI Decorator that provides error resolution on Runtime Errors using BiteFix AI Agents and OpenAI's Large Language Model. 20 | 21 | Args: 22 | openai_api_key (str): The API key for OpenAI. 23 | function_description (str, optional): Recommended to provide a description of the function to be resolved. It should not be less than 20 words and more than 50 words. Defaults to None. 24 | model_name (str, optional): The name of the model to use. Defaults to "gpt4". 25 | temperature (float, optional): The temperature for generating responses. Defaults to 0.7. 26 | export_dir (str, optional): The path to the directory to export the error resolution report. Defaults to None. 27 | verbose (bool, optional): Whether to print the output of the BiteFix AI process. Defaults to True. 28 | 29 | Returns: 30 | function: Decorator function that provides error resolution using BiteFix AI Agents and OpenAI's Large Language Model. 31 | """ 32 | 33 | def resolve_with_openai_decorator(func) -> Callable: 34 | def function_causing_error(*args, **kwargs) -> Any: 35 | """ 36 | Function that executes the decorated function and handles errors. 37 | 38 | Args: 39 | *args: Positional arguments for the decorated function. 40 | **kwargs: Keyword arguments for the decorated function. 41 | 42 | Returns: 43 | Any: The result of the decorated function. 44 | """ 45 | try: 46 | result = func(*args, **kwargs) 47 | print("Successfully executed the function.") 48 | return result 49 | except Exception as e: 50 | print("Error occurred while executing the function. - ", e) 51 | print("Starting Bite Fix AI ...\n") 52 | code = inspect.getsource(func) 53 | 54 | os.environ["OPENAI_API_KEY"] = openai_api_key 55 | llm = ChatOpenAI(temperature=temperature, model_name=model_name) 56 | 57 | if function_description: 58 | if ( 59 | len(function_description.split()) < 20 60 | or len(function_description.split()) > 50 61 | ): 62 | raise ValueError( 63 | "The function description should be within the word limit of 20-50 words." 64 | ) 65 | print("Running BiteFix AI ...\n") 66 | try: 67 | biteFixAIRunner = BiteFixAIRunner( 68 | function_code=code, 69 | function_description=function_description, 70 | arguments=args, 71 | error_message=e, 72 | llm=llm, 73 | ) 74 | result = biteFixAIRunner.run() 75 | except Exception as ex: 76 | print("Error occurred while running BiteFix AI - ", ex) 77 | return None 78 | print("BiteFix AI completed.\n") 79 | if verbose: 80 | print("BiteFix AI Error Resoltion Report: \n\n") 81 | print( 82 | "[PYTHON CODE DIAGNOSIS EXPERT] Error Diagnosis :\n\n", 83 | result["tasks_outputs"][0].result().replace("```", ""), 84 | ) 85 | print( 86 | "\n\n[SENIOR PYTHON CODE EXPERT] Error resolution Ideas :\n\n", 87 | result["tasks_outputs"][1].result().replace("```", ""), 88 | ) 89 | print( 90 | "\n\n[LEAD PYTHON CODE EXPERT] Best Resolution Idea Evaluation :\n\n", 91 | result["tasks_outputs"][2].result().replace("```", ""), 92 | ) 93 | print( 94 | "\n\n[PYTHON CODE DEVELOPER] Resolution Idea Implemenation :\n\n", 95 | result["tasks_outputs"][3].result(), 96 | ) 97 | 98 | try: 99 | if export_dir: 100 | export_error_resolution_report( 101 | result["tasks_outputs"], export_dir 102 | ) 103 | except Exception as exc: 104 | print( 105 | "Error occurred while exporting the error resolution report - ", 106 | exc, 107 | ) 108 | 109 | return function_causing_error 110 | 111 | return resolve_with_openai_decorator 112 | 113 | 114 | def resolve( 115 | llm: object, 116 | function_description: str = None, 117 | export_dir: str = None, 118 | verbose: bool = True, 119 | ) -> Callable: 120 | """ 121 | Bite Fix AI Decorator that provides error resolution on Runtime Errors using BiteFiix AI Agents and the provided LLM. 122 | 123 | Args: 124 | llm (object): The language model object to use for error resolution. 125 | export_dir (str, optional): The directory to export Error Resoltion Report by BiteFix AI Agents and fixed code python file. Defaults to None. 126 | function_description (str, optional): Recommended to provide a description of the function to be resolved. Word limit: 20-50 words. Defaults to None. 127 | verbose (bool, optional): Whether to print the output of the BiteFix AI process. Defaults to True. 128 | 129 | Returns: 130 | function: Decorator function that provides error resolution using the BiteFix AI Agents and provided Large Language Model. 131 | """ 132 | 133 | def resolve_decorator(func) -> Callable: 134 | def function_causing_error(*args, **kwargs) -> Any: 135 | """ 136 | Function that executes the decorated function and handles errors. 137 | 138 | Args: 139 | *args: Positional arguments for the decorated function. 140 | **kwargs: Keyword arguments for the decorated function. 141 | 142 | Returns: 143 | Any: The result of the decorated function. 144 | 145 | Raises: 146 | Exception: If an error occurs while executing the decorated function. 147 | """ 148 | try: 149 | result = func(*args, **kwargs) 150 | print("Successfully executed the function.") 151 | return result 152 | except Exception as e: 153 | print("Error occurred while executing the function. - ", e) 154 | code = inspect.getsource(func) 155 | if function_description: 156 | if ( 157 | len(function_description.split()) < 20 158 | or len(function_description.split()) > 50 159 | ): 160 | raise ValueError( 161 | "The function description should be within the word limit of 30-50 words." 162 | ) 163 | 164 | print("Starting Bite Fix AI ...\n") 165 | 166 | try: 167 | biteFixAIRunner = BiteFixAIRunner( 168 | function_code=code, 169 | function_description=function_description, 170 | arguments=args, 171 | error_message=e, 172 | llm=llm, 173 | ) 174 | result = biteFixAIRunner.run() 175 | except Exception as ex: 176 | print("Error occurred while running BiteFix AI - ", ex) 177 | return None 178 | 179 | print("BiteFix AI completed.\n") 180 | if verbose: 181 | print("BiteFix AI Error Resoltion Report: \n\n") 182 | print( 183 | "[PYTHON CODE DIAGNOSIS EXPERT] Error Diagnosis :\n\n", 184 | result["tasks_outputs"][0].result().replace("```", ""), 185 | ) 186 | print( 187 | "\n\n[SENIOR PYTHON CODE EXPERT] Error resolution Ideas :\n\n", 188 | result["tasks_outputs"][1].result().replace("```", ""), 189 | ) 190 | print( 191 | "\n\n[LEAD PYTHON CODE EXPERT] Best Idea Evaluation :\n\n", 192 | result["tasks_outputs"][2].result().replace("```", ""), 193 | ) 194 | print( 195 | "\n\n[PYTHON CODE DEVELOPER] Resolution Idea Implemenation :\n\n", 196 | result["tasks_outputs"][3].result(), 197 | ) 198 | 199 | if export_dir: 200 | try: 201 | export_error_resolution_report( 202 | result["tasks_outputs"], export_dir 203 | ) 204 | except Exception as exc: 205 | print( 206 | "Error occurred while exporting the error resolution report - ", 207 | exc, 208 | ) 209 | 210 | return function_causing_error 211 | 212 | return resolve_decorator 213 | 214 | 215 | def export_error_resolution_report(output: List[TaskOutput], export_dir: str) -> None: 216 | """ 217 | Export the error resolution report to a file in the specified directory. 218 | 219 | Args: 220 | output (List[TaskOutput]): The list of task outputs from the BiteFix AI process. 221 | export_dir (str): The Path to the directory to export the error resolution report. 222 | 223 | Returns: 224 | None 225 | """ 226 | 227 | timestamp = datetime.now().strftime("%Y%m%d%H%M%S") 228 | report_file_name = f"BiteFixAIErrorResolutionReport_{timestamp}.md" 229 | report_file_path = os.path.join(export_dir, report_file_name) 230 | with open(report_file_path, "w") as file: 231 | file.write("# BiteFix AI Error Resolution Report\n\n") 232 | file.write("## Error Diagnosis Report by Python Code Diagnosis Expert\n\n") 233 | file.write(output[0].result().replace("```", "")) 234 | file.write("\n\n") 235 | file.write("## Error resolution ideas Report by Senior Python Code Expert\n\n") 236 | file.write(output[1].result().replace("```", "")) 237 | file.write("\n\n") 238 | file.write("## Best Idea Evaluation Report by Lead Python Code Expert\n\n") 239 | file.write(output[2].result().replace("```", "")) 240 | file.write("\n\n") 241 | file.write( 242 | "## Resolution Idea Implemenation Report by Python Code Developer\n\n" 243 | ) 244 | file.write(output[3].result()) 245 | file.write("\n\n") 246 | print(f"\nError Resolution Report has been saved to {report_file_path}") 247 | -------------------------------------------------------------------------------- /bitefix/BiteFixAIAgents.py: -------------------------------------------------------------------------------- 1 | from crewai import Agent 2 | from typing import Any, Tuple 3 | 4 | 5 | class BiteFixAIAgents: 6 | 7 | """ 8 | This class is responsible for creating the agents for the BiteFixAI task. 9 | Each agent is responsible for a specific task involved in the process of fixing the error in the decorated python function. 10 | 11 | Attributes: 12 | llm (object): The LLM object. 13 | 14 | Methods: 15 | DiagnosisAgent: Returns a Python code Diagnosis agent responsible for explaining why the error occurred. 16 | IdeaGeneratorAgent: Returns a senior Python code expert agent responsible for generating ideas to fix the error. 17 | IdeasEvaluatorAgent: Returns a lead Python code expert agent responsible for evaluating and choosing the best idea to fix the error. 18 | CodeDeveloperAgent: Returns a Python code Developer agent responsible for writing the final fixed code based on the chosen idea. 19 | """ 20 | 21 | def __init__( 22 | self, 23 | llm: object, 24 | ): 25 | self.llm = llm 26 | 27 | def DiagnosisAgent(self) -> Agent: 28 | return Agent( 29 | role="Python code Diagnosis Expert", 30 | goal="Go through the error message and code and explain why the error occurred", 31 | backstory=f""" 32 | Context: You are an AI expert in diagnosing Python code errors. 33 | Your skills in identifying and explaining these errors are unparalleled, often solving issues in less than a minute. 34 | The error at hand is critical and has a high impact on the overall functionality of the system. 35 | It's crucial to fix this error promptly to ensure the smooth operation of the system. 36 | Take it seriously otherwise it might lead to a wrong impression in front of clients and we can lose millions of dollars. 37 | 38 | Objective: You will provide a clear, concise explanation of why a Python error occurred. 39 | Your explanation should be in simple, easy-to-understand language. 40 | Your diagnosis will be used by the Senior Python code expert to generate ideas to fix the error. 41 | 42 | Given Information: You will be provided with a Python function code, arguments passed to the function, and an error message generated by the code. 43 | You might be provided with a function description as well. 44 | If yes, use it to understand the function better. 45 | Steps: 46 | 1. Review the Python function code. 47 | 2. Examine the arguments passed to the function. 48 | 3. Analyze the error message generated by the code. 49 | 4. Identify the root cause of the error. 50 | 51 | Rules: 52 | 1. Your explanation should be concise, clear, and in simple language. 53 | 2. It should accurately identify the cause of the error based on the function code, arguments passed, and error message. 54 | 3. Remember, your role is to diagnose and explain the error, not to write or fix the code.Stay in the role of a Python code diagnosis expert. 55 | 56 | Output Format: Your explanation should be in markdown format. 57 | """, 58 | allow_delegation=False, 59 | llm=self.llm, 60 | verbose=False, 61 | ) 62 | 63 | def IdeaGeneratorAgent(self) -> Agent: 64 | return Agent( 65 | role="Senior Python code expert", 66 | goal="Generate ideas on how to fix the error", 67 | backstory=f""" 68 | Context: You are a senior Python code expert with over 10 years of experience. 69 | Your expertise lies in generating ideas to resolve errors, considering best practices and efficiency. 70 | The error at hand is critical and has a high impact on the overall functionality of the system. 71 | It's crucial to fix this error promptly to ensure the smooth operation of the system. 72 | Take it seriously otherwise it might lead to a wrong impression in front of clients and we can lose millions of dollars. 73 | 74 | Objective: You will generate ideas to fix the error based on the diagnosis provided by the Python code diagnosis expert. 75 | 76 | Given Information: You will be provided with a diagnosis of the error, including the root cause of the error. 77 | You will also have access to the Python function code and the arguments passed to the function and the error message generated by the code. 78 | You might be provided with a function description as well. 79 | If yes, use it to understand what the user is trying to do with the function. 80 | Your ideas will be evaluated by the Lead Python code expert to choose the best idea to fix the error. 81 | 82 | Steps: 83 | 1. Carefully review the Python Code Diagnosis Expert's error diagnosis to understand the context, examining the function code, arguments passed, and the associated error message. 84 | 2. Prioritize solutions aligned with best practices in Python coding, ensuring they do not disrupt any existing functionality. 85 | 3. Generate a concise set of three ideas to fix the error, considering efficiency and diverse approaches. 86 | 87 | Rules: 88 | 1. Express each idea in clear and simple language, making it accessible to a broad audience. 89 | 2. Provide explanations that not only address the technical aspects but also enhance understanding. 90 | 3. Verify that each idea maintains compatibility with the current codebase, avoiding potential disruptions. 91 | 4. Your ideas should be based on the diagnosis provided and should align with best practices and efficiency. 92 | 5. Remember, your role is to generate ideas to fix the error, not to write the code. Stay in the role of a Senior Python code expert. 93 | 94 | Output Format: Your output should be in markdown format. 95 | 96 | """, 97 | allow_delegation=False, 98 | llm=self.llm, 99 | verbose=False, 100 | ) 101 | 102 | def IdeasEvaluatorAgent(self) -> Agent: 103 | return Agent( 104 | role="Lead Python code expert", 105 | goal="Evaluate the ideas generated by BugFixIdeaGeneratorAgent and choose the best idea to fix the error", 106 | backstory=f""" 107 | Context: You are a lead Python code expert with over 20 years of experience. 108 | You have successfully led the resolution of more than 2000 errors. 109 | Your expertise lies in evaluating error fix ideas and choosing the best one considering best practices and efficiency. 110 | The error at hand is critical and has a high impact on the overall functionality of the system. 111 | It's crucial to fix this error promptly to ensure the smooth operation of the system. 112 | Take it seriously otherwise it might lead to a wrong impression in front of clients and we can lose millions of dollars. 113 | 114 | Objective: You will evaluate the ideas generated by the Senior Python code expert and choose the best idea to fix the error. 115 | 116 | Given Information: You will be provided with a set of ideas to fix the error generated by the Senior Python code expert. 117 | You will also have access to the Python function code and the arguments passed to the function and the error message generated by the code. 118 | You might be provided with a function description as well. 119 | If yes, use it to understand what the user is trying to do with the function. 120 | Your chosen idea will be used by the Python code developer to write the code to fix the error. 121 | 122 | Steps: 123 | 1. Carefully analyze all the three ideas proposed by the Senior Python Code Expert. 124 | 2. Examine each idea in relation to the diagnosed error and the specifics of the function. 125 | 3. Evaluate each idea against established best practices and coding standards. 126 | 4. Select the idea that is most effective in addressing the diagnosed error. 127 | 5. Provide a comprehensive explanation, addressing why the selected idea is deemed the most effective. 128 | 129 | Rules: 130 | 1. Choose the solution that minimizes the likelihood of introducing new issues or complications. 131 | 2. Ensure that the chosen idea aligns with the broader context of the task. 132 | 3. Your evaluation should be based on best practices and efficiency. 133 | 4. Remember, your role is to select the best idea to fix the error and provide the rationale behind your decision. Don't try to implement your idea by writing the code itself. That's the job of the Python code developer. 134 | 135 | Output Format: Your output should be in markdown format. 136 | """, 137 | allow_delegation=False, 138 | llm=self.llm, 139 | verbose=False, 140 | ) 141 | 142 | def CodeDeveloperAgent(self) -> Agent: 143 | return Agent( 144 | role="Python code developer", 145 | goal="Write the code to fix the error", 146 | backstory=f""" 147 | Context : You are a seasoned Python developer with a proven track record of resolving complex errors. 148 | Your expertise lies in implementing solutions based on ideas provided by a Lead Python code expert. 149 | The error at hand is critical and has a high impact on the overall functionality of the system. 150 | It's crucial to fix this error promptly to ensure the smooth operation of the system. 151 | Take it seriously otherwise it might lead to a wrong impression in front of clients and we can lose millions of dollars. 152 | 153 | Objective: You will write the code to fix the error based on the idea chosen by the Lead Python code expert. 154 | 155 | Given Information: You will be provided with the idea chosen by the Lead Python code expert to fix the error. 156 | You will also have access to the Python function code and the arguments passed to the function and the error message generated by the code. 157 | You might also have access to the function description as well. 158 | Your rewritten function code will be presented to the user to fix the error. 159 | 160 | Steps: 161 | 1. Review the idea chosen by the Lead Python code expert. 162 | 2. Understand the context, examining the function code, arguments passed, and the associated error message. 163 | 3. Rewrite the function code to fix the error based on the chosen idea. 164 | 165 | Rules: 166 | 1. Your code should effectively address the diagnosed error and align with the chosen idea. 167 | 2. Double check the rewritten code to ensure it accurately implements the chosen idea and resolves the error. 168 | 3. Ensure that the code adheres to best practices and coding standards. 169 | 4. Remember, you should stick to the chosen idea and not deviate from it. You just have to write the code based on the chosen idea. 170 | 171 | Output Format: Your output should be in Python format. 172 | 173 | """, 174 | allow_delegation=False, 175 | llm=self.llm, 176 | verbose=False, 177 | ) 178 | --------------------------------------------------------------------------------