How to use GPT-4o for code generation
Quick answer
Use the
gpt-4o model via the OpenAI Python SDK to generate code by sending a chat completion request with a coding prompt. Set your API key in os.environ["OPENAI_API_KEY"] and call client.chat.completions.create() with model="gpt-4o" and appropriate messages.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable for secure authentication.
pip install openai>=1.0 Step by step
This example shows how to generate Python code using gpt-4o. It sends a prompt asking for a function to reverse a string and prints the AI-generated code.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Write a Python function to reverse a string."}
]
)
print(response.choices[0].message.content) output
def reverse_string(s):
return s[::-1] Common variations
- Streaming output: Use
stream=Trueto receive tokens as they are generated for faster feedback. - Async usage: Use async clients or frameworks to integrate code generation in asynchronous workflows.
- Different models: Use
gpt-4o-minifor faster, cheaper code generation with slightly reduced quality.
import os
import asyncio
from openai import OpenAI
async def async_code_generation():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
stream = await client.chat.completions.acreate(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a Python function to check if a number is prime."}],
stream=True
)
async for chunk in stream:
print(chunk.choices[0].delta.content or '', end='', flush=True)
asyncio.run(async_code_generation()) output
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True Troubleshooting
- If you get
401 Unauthorized, verify yourOPENAI_API_KEYenvironment variable is set correctly. - If the model returns irrelevant text, try refining your prompt with explicit instructions.
- For rate limits, consider exponential backoff or upgrading your OpenAI plan.
Key Takeaways
- Use the OpenAI Python SDK with
gpt-4ofor high-quality code generation. - Set
OPENAI_API_KEYin your environment to authenticate securely. - Streaming and async calls improve responsiveness in interactive applications.
- Prompt clarity directly impacts the quality of generated code.
- Check API key and usage limits if you encounter authentication or rate errors.