AI Accelerated Software Development example
This example uses the OpenAI API to perform two common tasks: generating code from a description and creating documentation for an existing function.
# Requires: pip install openai python-dotenv
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# TASK 1: Generate a function from a description
def generate_function(description):
prompt = f"""
Write a Python function based on the following description.
Provide only the code, no explanation.
Description: {description}
"""
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.1 # Low temperature for more deterministic code
)
return response.choices[0].message.content
# TASK 2: Document an existing function
def document_function(code_snippet):
prompt = f"""
Write a professional docstring for the following Python function.
Use the Google style format, including Args and Returns sections.
Code:
{code_snippet}
"""
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# --- Example Usage ---
# 1. Generate Code
description = "A function that connects to a PostgreSQL database using psycopg2 and fetches the top 10 users from a 'users' table."
new_code = generate_function(description)
print("*** Generated Function ***")
print(new_code)
# 2. Document Code
existing_code = """
def calculate_metrics(data):
if not data:
return None
total = sum(data)
count = len(data)
average = total / count
variance = sum((x - average) ** 2 for x in data) / count
return {'mean': average, 'std_dev': variance ** 0.5}
"""
new_docstring = document_function(existing_code)
print("n*** Generated Documentation ***")
print(new_docstring)
No Comments have been Posted.