AutoPyFunc: AI-Powered Python Function Generator
Hey guys so today I wanna share a different small script with you called - AutoPyFunc. It’s an AI-powered tool that generates Python functions from plain English descriptions. Pretty cool, right?
So what is AutoPyFunc?
AutoPyFunc is a Python script that uses AI models like GitHub Copilot’s GPT or OpenAI’s GPT to automatically create Python functions based on what you tell it to do. You just give it a description of what you want the function to do, and it spits out the Python code for you.
I built this to help and ease me to quickly write code for simple tasks without having to start from scratch every time. It’s not perfect, but it’s a fun way to experiment with AI and programming.
How does it work?
Okay, so here’s how AutoPyFunc does its thing:
It starts by reading your Python script and looking for any calls to a special function called
sid.When it finds a
sidfunction call, it looks at the arguments you passed to figure out what you want the function to do. You can give it a name for the function and a description of what it should do.AutoPyFunc then checks if it has already generated a function with the same name and description before. If it has, it just reuses that code. If not, it sends the description to an AI model (like GitHub Copilot) and asks it to generate the function code.
Let’s dive into the code a bit to see how this works:
async def generate_function(self, function_name: str, description: str) -> str:
try:
if time.time() - self.token_time > 600:
self.token = get_token()
self.token_time = time.time()
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.githubcopilot.com/chat/completions",
headers={
"Editor-Version":"vscode/1.83.0",
"Authorization": f"Bearer {self.token}",
},
json={
"messages":[{"role": "system", "content": f"Below is a python function with the name {function_name} that does the following: {description}. No code blocks/formatting are allowed. Assume any uncertainties."}],
"model":"gpt-4",
"temperature":0.4,
"role":"system",
},
timeout=130.0
)
if response.status_code != 200:
return "Response 404"
code = response.json()["choices"]["message"]["content"]
code_blocks = re.search(r'```.*?\n(.*?)```', code, re.DOTALL)
code = code_blocks.group(1) if code_blocks else code
compile(code, '<string>', 'exec')
return code
except Exception as e:
logging.error(f"Failed to generate function: {e}")
return ""
This generate_function method is where the magic happens. It takes the function name and description, and sends a POST request to the GitHub Copilot API at https://api.githubcopilot.com/chat/completions (you could refer this api from my Vulnyzer project). The request includes the function name and description in the prompt, along with some other parameters like the AI model to use (gpt-4) and the temperature (which controls the randomness of the output).
The request includes the function name and description in the prompt, along with some other parameters like the AI model to use (gpt-4) and the temperature (which controls the randomness of the output). The API sends back the generated code in the response. The method then extracts the code, checks it for syntax errors by compiling it, and returns the code as a string.
4 The AI model sends back the generated code, and AutoPyFunc checks it for any syntax errors. If it looks good, it adds the new function to your script.
5 Finally, AutoPyFunc replaces the sid function call in your script with the name of the newly generated function.
So, when you run AutoPyFunc on your script, it will add all the new functions it generated to the top of your file, and your original sid function calls will now call those new functions instead. Here’s a quick example of how you might use AutoPyFunc in your code:
Here’s a quick example of how you might use AutoPyFunc in your code:
First, we’ll write a Python script that uses the sid function to describe what we want our function to do:
def main():
numbers = [1, 2, 3, 5, 6, 7, 8, 10, 11, 12]
consecutive_numbers = sid("Find all consecutive numbers in a list")
print(f"The consecutive numbers in {numbers} are: {consecutive_numbers(numbers)}")
Now, let’s run this script through AutoPyFunc. Based on our project code, AutoPyFunc will:
- Parse the script and find the sid function call.
- Extract the description “Find all consecutive numbers in a list” from the sid call.
- Check if it has already generated a function for this description (it hasn’t in this case).
- Send the description to the GitHub Copilot API to generate the function code.
The API will return something like this:
def find_all_consecutive_numbers_in_a_list(numbers):
consecutive = []
for i in range(len(numbers) - 1):
if numbers[i+1] - numbers[i] == 1:
if not consecutive or numbers[i] - consecutive[-1][-1] == 1:
if not consecutive:
consecutive.append([numbers[i]])
consecutive[-1].append(numbers[i+1])
else:
consecutive.append([numbers[i], numbers[i+1]])
return consecutive
def main():
numbers = [1, 2, 3, 5, 6, 7, 8, 10, 11, 12]
consecutive_numbers = find_all_consecutive_numbers_in_a_list
print(f"The consecutive numbers in {numbers} are: {consecutive_numbers(numbers)}")
Now, when we run this script, it will output:
The consecutive numbers in [1, 2, 3, 5, 6, 7, 8, 10, 11, 12] are: [[1, 2, 3], [5, 6, 7, 8], [10, 11, 12]]
Pretty neat, huh?
The generated function find_all_consecutive_numbers_in_a_list works by iterating through the list, checking if each number is exactly one more than the previous number. If it is, it adds it to the current consecutive sequence. If not, it starts a new sequence.
well that was it, just a small tool to generate python function using llms :)
See you in next Project!