How to prompt AI for code generation
Quick answer
To prompt AI for code generation, use clear, specific instructions including the programming language, desired functionality, and any constraints. Include example inputs and expected outputs in your
prompt to improve accuracy and relevance.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
Use the OpenAI SDK to send a detailed prompt specifying the programming language, task, and example inputs/outputs. This example generates a Python function to reverse a string.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt_text = (
"Write a Python function named <code>reverse_string</code> that takes a string and returns it reversed."
" Include example input: 'hello' and expected output: 'olleh'."
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt_text}]
)
print(response.choices[0].message.content) output
def reverse_string(s):
return s[::-1] Common variations
You can use other models like claude-3-5-sonnet-20241022 with Anthropic's SDK or enable streaming for real-time code generation. Adjust prompts to specify language or style.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant that writes Python code."
user_prompt = (
"Create a Python function <code>factorial</code> that returns the factorial of a number."
" Provide example input 5 and output 120."
)
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
print(message.content[0].text) output
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1) Troubleshooting
If the generated code is incomplete or incorrect, refine your prompt by adding more examples or clarifying requirements. Also, verify your API key and model name are correct to avoid authentication or model errors.
Key Takeaways
- Specify the programming language and function purpose clearly in your prompt.
- Include example inputs and expected outputs to guide the AI.
- Use the latest SDK patterns with environment variables for API keys.
- Experiment with different models and prompt styles for best results.