Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon GPT-4o API complex code generation Python
    GPT-4o API


GPT-4o API complex code generation Python


Here is an example of how to use the GPT-4o API in Python to generate more complex code:

python
import openai

openai.api_key = "YOUR_API_KEY"

# Define the system prompt
system_prompt = """
You are an expert Python developer who can take instructions and generate code. You will be provided with a description of the task at hand. 

Your output must be a JSON string. The keys in the JSON document must be paths to files. The values must contain Python code that can be executed. Do not include markdown code fences.

You must include a main.py file, which should be the entry point for the application. For example, the app should execute when running `python main.py`.

You must also include a README.md file containing sample commands to use the app; for example, building a REST API should consist of sample curl commands.
"""

# Define the user prompt
user_prompt = """
Create a Flask app with CRUD endpoints for a Book model. The book model has the following fields: 
- title (string)
- author (string) 
- year_published (integer)

The app should have the following routes:
- GET /books - returns a list of all books
- GET /books/<id> - returns a single book by id
- POST /books - creates a new book
- PUT /books/<id> - updates an existing book by id
- DELETE /books/<id> - deletes a book by id

The app should use a SQLite database to store the books.
"""

# Generate the code
response = openai.Completion.create(
    engine="gpt-4o",
    prompt=f"System: {system_prompt}\nUser: {user_prompt}",
    max_tokens=2048,
    n=1,
    stop=None,
    temperature=0.7,
)

# Extract the generated code from the JSON response
generated_code = response.choices[0].text.strip()

# Parse the JSON and write the files
import json
code_files = json.loads(generated_code)

for filename, code in code_files.items():
    with open(filename, "w") as f:
        f.write(code)

print("Code generated successfully!")

Key points:

- Define a system prompt that provides instructions for the code generation
- Define a user prompt that describes the desired application functionality
- Use `openai.Completion.create()` to generate the code based on the prompts
- Extract the JSON string containing the generated code files
- Parse the JSON and write the code to the corresponding files

This example demonstrates how to leverage the GPT-4o API to generate a Flask application with a Book model and CRUD endpoints. The generated code includes the necessary files like `main.py` and `README.md`.

By carefully crafting the system and user prompts, you can guide the model to generate more complex and specific code. The JSON format allows the model to output multiple files at once, making it easier to generate complete applications.

Keep in mind that while GPT-4o can generate working code, it's important to review the output for correctness, security, and best practices before deploying it in production.

Citations:
[1] https://www.datacamp.com/tutorial/gpt4o-api-openai-tutorial
[2] https://github.com/topics/gpt-4o?o=desc&s=updated
[3] https://tilburg.ai/2024/05/tutorial-gpt-4o-api/
[4] https://github.com/TheStoneMX/conversation_with_GPT4o
[5] https://ploomber.io/blog/gpt-4o-flask/