Prompting in OpenAI SDK
Prompting means giving instructions or inputs to the AI to get a desired output. Think of it like asking a question or giving a task to the AI.
1. Zero-shot Prompting
๐น Definition:
Zero-shot Prompting: The model is given a direct question or task without prior examples.
๐น Detailed Explanation:
In zero-shot prompting, you donโt show the model how to solve the problem โ you just tell it what you want. The model relies on its pre-trained knowledge to understand your intent and generate a response.
โ Best for:
Simple questions
Language translation
Summarization
Quick data extraction
๐น Real-Time Example:
Task: Summarize the paragraph in one sentence.
Prompt:
"Summarize this: OpenAI has developed advanced AI models that can understand and generate human-like language, helping developers create smarter applications."
๐น Ready-to-Run Code:
import openai
openai.api_key = "your-api-key"
def zero_shot_prompt():
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Summarize this: OpenAI has developed advanced AI models that can understand and generate human-like language, helping developers create smarter applications."}
]
)
print("Zero-shot Response:\n", response['choices'][0]['message']['content'])
zero_shot_prompt()
2. Few-shot Prompting
๐น Definition:
Few-shot Prompting: The model is provided with a few examples before asking it to generate a response.
๐น Detailed Explanation:
Here, you give 2โ5 examples in the prompt. This helps the model understand the format, style, or logic of what you expect. Itโs like teaching by example.
โ Best for:
Custom formatting
Conversions (currency, date formats)
Custom Q&A or grammar correction
๐น Real-Time Example:
Task: Convert temperatures from Celsius to Fahrenheit.
Prompt:
yamlCopyEditConvert Celsius to Fahrenheit:
C: 0 โ F: 32
C: 10 โ F: 50
C: 25 โ F:
๐น Code:
def few_shot_prompt():
prompt = """Convert Celsius to Fahrenheit:
C: 0 โ F: 32
C: 10 โ F: 50
C: 25 โ F:"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
print("Few-shot Response:\n", response['choices'][0]['message']['content'])
few_shot_prompt()
3. Chain-of-Thought (CoT) Prompting
๐น Definition:
Chain-of-Thought Prompting: The model is encouraged to break down reasoning step by step before arriving at an answer.
๐น Detailed Explanation:
Instead of just giving an answer, the model explains its thinking process step by step. This helps in logical or mathematical problems and improves accuracy.
โ Best for:
Math problems
Logical reasoning
Code analysis
๐น Real-Time Example:
Task: Solve a math word problem step-by-step.
Prompt:
"If a train travels 60 km in 1.5 hours, what is its speed? Think step by step."
๐น Code:
def cot_prompt():
prompt = "If a train travels 60 km in 1.5 hours, what is its speed? Think step by step."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
print("Chain-of-Thought Response:\n", response['choices'][0]['message']['content'])
cot_prompt()
4. Self-Consistency Prompting
๐น Definition:
Self-Consistency: The model generates multiple answers and selects the most consistent one (majority vote).
๐น Detailed Explanation:
Instead of taking the first answer, you sample multiple outputs (e.g., 5), and then choose the most common or logical one. This reduces randomness and improves reasoning reliability.
โ Best for:
Critical tasks
Logic-heavy answers
Higher confidence output
๐น Real-Time Example:
Same as CoT, but get 5 outputs and choose the best.
๐น Code:
def self_consistency_prompt():
prompt = "If a train travels 60 km in 1.5 hours, what is its speed? Think step by step."
results = []
for _ in range(5):
res = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
temperature=1.0,
messages=[{"role": "user", "content": prompt}]
)
results.append(res['choices'][0]['message']['content'])
print("Self-Consistency Responses:")
for i, ans in enumerate(results, 1):
print(f"\nAttempt {i}:\n{ans.strip()}")
self_consistency_prompt()
5. Instruction Prompting
๐น Definition:
Instruction Prompting: The model is explicitly instructed to follow a particular format or guideline.
๐น Detailed Explanation:
You give clear commands like โWrite a summary in bullet pointsโ or โReply only in JSONโ. The model will follow those instructions closely.
โ Best for:
Structured outputs
APIs or automation
Custom formats
๐น Real-Time Example:
Task: Describe Apple Inc. in bullet points.
Prompt:
"List key facts about Apple Inc. in bullet points."
๐น Code:
def instruction_prompt():
prompt = "List key facts about Apple Inc. in bullet points."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
print("Instruction Response:\n", response['choices'][0]['message']['content'])
instruction_prompt()
6. Direct Answer Prompting
๐น Definition:
Direct Answer Prompting: The model is asked to give a concise and direct response without explanation.
๐น Detailed Explanation:
Great for chatbots, APIs, or command-line tools where you just want the answer โ no fluff.
โ Best for:
Yes/No answers
API returns
Quick data
๐น Real-Time Example:
Prompt:
"What is the capital of Germany? Answer only."
๐น Code:
def direct_answer_prompt():
prompt = "What is the capital of Germany? Answer only."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
print("Direct Answer:\n", response['choices'][0]['message']['content'])
direct_answer_prompt()
7. Persona-based Prompting
๐น Definition:
Persona-based Prompting: The model is instructed to respond as if it were a particular character or professional.
๐น Detailed Explanation:
You can make the model act like a doctor, teacher, poet, or even a movie character. It adjusts tone, vocabulary, and attitude accordingly.
โ Best for:
Character simulations
Creative writing
Expert-style responses
๐น Real-Time Example:
Prompt:
"You are a nutritionist. Suggest a healthy breakfast for weight loss."
๐น Code:
def persona_prompt():
messages = [
{"role": "system", "content": "You are a certified nutritionist."},
{"role": "user", "content": "Suggest a healthy breakfast for weight loss."}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
print("Persona-based Response:\n", response['choices'][0]['message']['content'])
persona_prompt()
8. Role-Playing Prompting
๐น Definition:
Role-Playing Prompting: The model assumes a specific role and interacts accordingly.
๐น Detailed Explanation:
Itโs similar to persona-based but more interactive. You can create simulations like โYou are a job interviewerโ and conduct a mock interview.
โ Best for:
Training bots
Scenario simulation
Education & entertainment
๐น Real-Time Example:
Prompt:
"You are an interviewer. Ask me 3 questions for a software engineer position."
๐น Code:
def role_playing_prompt():
messages = [
{"role": "system", "content": "You are a job interviewer."},
{"role": "user", "content": "Ask me 3 questions for a software engineer position."}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
print("Role-Playing Response:\n", response['choices'][0]['message']['content'])
role_playing_prompt()
9. Contextual Prompting
๐น Definition:
Contextual Prompting: The prompt includes background information to improve response quality.
๐น Detailed Explanation:
You provide extra context (past conversation, company details, etc.) so the model gives relevant, coherent answers.
โ Best for:
Long conversations
Business apps
Chatbots
๐น Real-Time Example:
Prompt:
"Company: EcoTech. Product: Solar Chargers. Task: Write a one-line pitch for investors."
๐น Code:
def contextual_prompt():
prompt = "Company: EcoTech. Product: Solar Chargers. Task: Write a one-line pitch for investors."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
print("Contextual Response:\n", response['choices'][0]['message']['content'])
contextual_prompt()
10. Multimodal Prompting
๐น Definition:
Multimodal Prompting: The model is given a combination of text, images, or other modalities to generate a response.
๐น Detailed Explanation:
Works with GPT-4-Vision. You can upload an image + add a prompt like โDescribe this pictureโ or โWhatโs in this chart?โ
โ Best for:
Image captions
Visual understanding
Diagrams, screenshots
๐น Real-Time Example (text + image description):
โ ๏ธ This requires an image and GPT-4 Vision model.
import base64
def multimodal_prompt():
# Load image and encode it to base64
with open("solar_panel.jpg", "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
response = openai.ChatCompletion.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe the image in detail."},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
)
print("Multimodal Response:\n", response['choices'][0]['message']['content'])
# multimodal_prompt() # Uncomment after setting up GPT-4-Vision access and image
โ Summary Table
| Type | Use Case | Strength |
| Zero-shot | Direct question | Fast & simple |
| Few-shot | Format-specific answers | Learn by examples |
| CoT | Reasoning/maths | Step-by-step thinking |
| Self-Consistency | Complex logic | More accurate |
| Instruction | Format control | Precise output |
| Direct Answer | Short replies | Chatbots, APIs |
| Persona-based | Expert advice | Custom tone |
| Role-Playing | Simulations | Fun & realistic |
| Contextual | Business/chatbots | Deep understanding |
| Multimodal | Images + text | Visual tasks |