How to beginner · 3 min read

How to write a good AI prompt

Quick answer
A good AI prompt uses clear, specific instructions with relevant context and examples to guide the model effectively. Use explicit roles, desired output format, and constraints in your prompt to improve response quality from models like 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 SDK and set your API key as an environment variable to start sending prompts to the model.

bash
pip install openai>=1.0

Step by step

Write a clear prompt with context, instructions, and examples. Use the OpenAI SDK to send the prompt to gpt-4o and print the response.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

prompt = (
    "You are a helpful assistant."
    "\nTask: Summarize the following text in 2 sentences."
    "\nText: 'Artificial intelligence is transforming industries by automating tasks and providing insights.'"
    "\nSummary:"
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print(response.choices[0].message.content)
output
Artificial intelligence automates tasks and provides insights, transforming industries. It enables more efficient and informed decision-making.

Common variations

You can use different models like claude-3-5-sonnet-20241022 or enable streaming responses. Async calls improve throughput in applications.

python
from anthropic import Anthropic
import os

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

system_prompt = "You are a helpful assistant."
user_prompt = (
    "Summarize the following text in 2 sentences:\n"
    "Artificial intelligence is transforming industries by automating tasks and providing insights."
)

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=100,
    system=system_prompt,
    messages=[{"role": "user", "content": user_prompt}]
)

print(message.content[0].text)
output
Artificial intelligence automates tasks and provides valuable insights, revolutionizing various industries. It enhances efficiency and decision-making processes.

Troubleshooting

If the output is vague or off-topic, refine your prompt by adding more context or explicit instructions. Avoid ambiguous language and specify the desired format clearly.

Key Takeaways

  • Use clear, specific instructions and context in your prompt to guide the AI effectively.
  • Include examples or desired output formats to reduce ambiguity and improve response quality.
  • Test and iterate your prompt to handle edge cases and improve accuracy.
  • Use the latest SDK patterns and models like gpt-4o or claude-3-5-sonnet-20241022 for best results.
  • Avoid vague language; be explicit about constraints and roles in your prompt.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗