What makes a prompt effective
gpt-4o or claude-3-5-sonnet-20241022.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 clear, explicit instructions and provide context in your prompt to get precise AI responses. Below is a complete example using gpt-4o with the OpenAI Python SDK v1 pattern.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = (
"You are a helpful assistant."
" Please summarize the following text in 2 sentences, focusing on key points."
" Text: 'Artificial intelligence enables machines to learn from data and perform tasks.'"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
print(response.choices[0].message.content) Artificial intelligence allows machines to learn from data and perform various tasks efficiently. It is a transformative technology impacting many industries.
Common variations
You can enhance prompts by adding examples, specifying output format, or using different models like claude-3-5-sonnet-20241022. Async calls and streaming responses are also common variations.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant."
user_prompt = (
"Summarize the following text in bullet points:\n"
"Text: 'Artificial intelligence enables machines to learn from data and perform tasks.'"
)
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) - AI enables machines to learn from data. - Machines can perform various tasks. - AI impacts many industries.
Troubleshooting
If the AI output is vague or off-topic, refine your prompt by adding more context, examples, or explicit instructions. Avoid ambiguous language and test with smaller inputs first.
Key Takeaways
- Use clear, specific instructions to guide the AI effectively.
- Provide relevant context and examples to improve response accuracy.
- Specify output format and constraints to get usable results.
- Test and iterate prompts to refine AI behavior.
- Choose the right model and SDK pattern for your use case.