Concepts of Prompting and its Techniques

Hey there! I'm Shivam, a beginner web developer who's passionate about coding and creating beautiful websites. I'm currently in the process of learning everything I can about web development, and I'm always excited to discover new tools and techniques that can help me grow as a developer.
This blog is where I'll be sharing my journey and what I'm learning along the way. From tips and tricks to code snippets, I hope to help other beginners like me as we navigate the world of web development together.
Thanks for stopping by, and I hope you'll join me on this journey as we learn and grow together!
Prompting’s just the way you give a generative AI its marching orders think of it as writing a note to a very eager but somewhat literal-minded assistant. Your prompt can be a question “Write me a poem about spring”, a command “Summarize this article in bullet points”, or even an example-filled template “Translate these three sentences into French, then tackle yours”. The trick is that the AI doesn’t know your true intent unless you spell it out, so the clearer, more detailed, or more creatively framed your prompt is, the more on-target its response will be. Good prompts guide the model’s style, tone, and focus like choosing the right words when you’re texting a friend versus sending an email to your boss.
Zero-shot Prompting
Zero-shot prompting is like walking up to a new assistant and giving them a fresh task without showing them any examples first and trusting they’ll figure it out just from your instructions. In generative AI, you simply describe what you want, and the model uses its broad training to perform the task on the fly.
Here’s how it looks in practice with Python and the OpenAI SDK:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You’re a helpful assistant."},
{"role": "user", "content": "Translate the following sentence into French: 'Generative AI is amazing.'"}
]
)
print(response.choices[0].message.content)
Notice there’s no example of a prior translation, just your instruction. The model digests that single prompt and goes for it.
Few-shot Prompting
Few‐shot prompting is like teaching your AI assistant with a couple of quick demos before you hand over the real task. Instead of just saying “Do this,” you show it a few examples of the kind of input‐output pairs you want, then let it generalize from there.
Imagine you need the model to convert temperatures from Fahrenheit to Celsius. With few‐shot prompting, you might send a prompt like this:
Translate Fahrenheit to Celsius.
F: 32 → C: 0
F: 212 → C: 100
F: 68 → C:
By giving those two examples (32→0 and 212→100), you’re implicitly teaching the AI the formula, so when it sees 68, it can fill in 20 on its own.
Here’s how that plays out in Python with OpenAI’s SDK:
import openai
openai.api_key = "YOUR_API_KEY"
prompt = """
Translate Fahrenheit to Celsius.
F: 32 → C: 0
F: 212 → C: 100
F: 68 → C:
"""
response = openai.Completion.create(
model="gpt-4o",
prompt=prompt,
max_tokens=10,
temperature=0
)
print(response.choices[0].text.strip())
# Should print "20"
Chain-of-Thought (CoT) Prompting
Chain-of-Thought prompting is basically asking your AI to “show its work” before giving you the answer, kind of like when your math teacher has you write out each algebra step so you don’t just blurt out the final number. Instead of just saying:
“What’s 23 × 47?”
and getting “1,081,” you nudge the model:
“Let’s think step by step: 23 × 47 = ?”
and it might reply:
“First, 23 × 40 = 920.
Next, 23 × 7 = 161.
Finally, 920 + 161 = 1,081.”
By coaxing out each intermediate thought, you usually get more accurate answers on tricky problems, whether it’s logic puzzles, math, or even multi-stage reasoning in text.
Here’s how you’d hook that up in Python with the OpenAI SDK:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You’re a helpful assistant."},
{"role": "user", "content": (
"Solve this step by step:\n"
"If a train travels at 60 mph for 2 hours, then 80 mph for 1.5 hours, "
"what’s the average speed over the whole trip?"
)}
],
temperature=0.2
)
print(response.choices[0].message.content)
When you run that, the model should walk through each segment calculating distances, summing them, dividing by total time and then give you the final average. That extra “thinking aloud” often catches mistakes that a straight-to-the-answer approach might miss.
Self-Consistency Prompting
Think of self-consistency prompting like polling a classroom of bright students: instead of asking just one of them to solve a tricky problem (and trusting that single answer), you have every student show their work, then pick whichever answer the majority landed on. In generative AI, you do this by sampling multiple “think-aloud” (chain-of-thought) answers from the model, extracting each final solution, and taking the most frequent one. This usually irons out random mistakes and gives you the answer the model “agrees” on most.
Quick Python sketch
import openai
from collections import Counter
import re
openai.api_key = "YOUR_API_KEY"
def solve_with_self_consistency(prompt, model="gpt-4o", tries=5, temp=0.7):
answers = []
for _ in range(tries):
resp = openai.ChatCompletion.create(
model=model,
messages=[
{"role": "system", "content": "You’re a helpful assistant."},
{"role": "user", "content": "Think step by step:\n" + prompt}
],
temperature=temp
)
text = resp.choices[0].message.content
# Naively grab the last number or word as the “final answer”
match = re.search(r"Ans(?:wer)?:?\s*([^\n]+)$", text, re.IGNORECASE)
answers.append(match.group(1).strip() if match else text.splitlines()[-1])
# Pick the most common answer
most_common, count = Counter(answers).most_common(1)[0]
print(f"All tries: {answers}")
return most_common
# Example use:
question = "If 5 machines take 5 minutes to make 5 widgets, how long for 100 machines to make 100 widgets?"
print("Consensus answer:", solve_with_self_consistency(question))
Loop over
tries: each pass gets a fresh chain of thought.Tally up the final answers you extract (here we grab the last line or a labeled “Answer:”).
Return the majority vote as your final result.
That simple “ask many, vote once” trick often nudges your AI from “maybe” to “definitely.”
Instruction Prompting
Instruction prompting is basically you telling the model exactly what you want it to do step one, two, three rather than leaving it to guess your intent. It’s like handing your AI a simple recipe card:
“Please summarize this article in three bullet points, then suggest two follow-up questions.”
By framing your prompt as a clear instruction, you cut down on misunderstandings and get more consistent, on-target outputs.
How you’d do it in code
Here’s a quick Python example using OpenAI’s ChatCompletion endpoint:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": (
"You’re an expert science communicator. "
"Always use simple language and bullet points where asked."
)
},
{
"role": "user",
"content": (
"Instruction:\n"
"1. Read the following paragraph.\n"
"2. Summarize it in exactly three bullet points.\n"
"3. Propose two follow-up questions a curious student might ask.\n\n"
"Paragraph:\n"
"\"Climate change refers to long-term shifts in temperatures "
"and weather patterns, mainly due to human activities like burning fossil fuels...\""
)
}
],
temperature=0.3,
max_tokens=200
)
print(response.choices[0].message.content)
When you run that, you’ll get something like:
Three neat bullets capturing the gist of climate change.
Two thoughtful questions (e.g., “How do greenhouse gases trap heat?”).
That is instruction prompting in a nutshell, feed the model a numbered to-do list and watch it follow each step.
Direct Answer Prompting
Direct Answer Prompting is basically asking your AI to cut straight to the chase, no preamble, no “thinking out loud,” just the nugget you want. It’s like ordering your coffee with “black, no sugar, please” instead of “I’m pondering what kind of coffee I might enjoy…” You frame your prompt so the model knows you only want the final fact or response.
Example in Python
Here’s how you’d do it with the OpenAI SDK, telling the model “just give me the answer in one line” and using a low temperature so it sticks to the most likely output:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "You’re a concise assistant. Only reply with the direct answer, one sentence max."
},
{
"role": "user",
"content": "What’s the tallest mountain in the world?"
}
],
temperature=0, # keep it factual
max_tokens=20 # limit verbosity
)
answer = response.choices[0].message.content.strip()
print(answer) # → "Mount Everest, at 8,848 meters above sea level."
In that snippet:
System message sets the rule, no extra chatter.
Temperature=0 makes the model pick the single most probable answer.
Max tokens=20 caps how much it can say.
That’s Direct Answer Prompting in action, your shortcut to the exact line you need.
Persona-based Prompting
Think of persona-based prompting as giving your AI a costume and a script before it speaks, it’s you saying, “Hey, talk like you’re this character,” so every answer oozes that personality. You’re not just asking it to deliver facts, you’re asking it to be someone.
Why persona prompts matter
Consistent voice: Whether you want Shakespeare, a pirate, or Deadpool, the AI stays in character.
Audience fit: A playful tone for kids, a formal tone for business, or a gruff tone for comic relief.
Engagement: Personas can make dry info more fun and memorable.
How you set it up
Usually you prime the model with a system or assistant message that defines the persona:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": (
"You’re Deadpool: witty, sarcastic, and a little irreverent. "
"You break the fourth wall, crack jokes, and always sign off with a quip."
)
},
{
"role": "user",
"content": "Explain how photosynthesis works."
}
],
temperature=0.8
)
print(response.choices[0].message.content)
What you’d see:
“Ah, photosynthesis—nature’s very own solar panel buffet! 🌞🍽️ Green leaf chlorophyll munches on sunlight and CO₂, turning them into sweet, sweet glucose snacks and oxygen gas for us to breathe. It’s like plants are throwing an all-you-can-eat light feast every day—no reservation needed! 🥳”
Tips for killer persona prompts
Be specific: “You’re a pirate with an eye patch,” not “be funny.”
Give quirks: “Use at least one emoji per reply,” or “address me as ‘Captain.’”
Control the mix: Combine persona with task instructions (“Explain algebra like you’re a pirate schoolmaster”).
That’s it—persona prompting turns your AI from a bland encyclopedia into someone entertaining (or authoritative, or wise…) for whatever flavor you need.
Role-Playing Prompting
Think of role-playing prompting as kicking your AI into a little improv scene, you set up the situation and cast it as a character in that world, then let it interact “in character” with you or other users. It’s like saying, “You’re not just Deadpool, you’re Deadpool negotiating peace between two warring kingdoms,” or “You’re a friendly barista taking customers’ orders.”
Why it’s handy
Immersive interactions: The model reacts to changing inputs as if it really is that character in that scenario.
Dynamic storytelling or training: Great for simulations (e.g., interviewing practice, customer-service role-play, language conversations).
Context continuity: Because you’ve defined the scene up front, the AI keeps track of its goals, relationships, and “stage directions.”
How you’d do it in code
Here’s a quick Python example where we have the AI play a helpful barista:
import openai
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": (
"You’re a friendly coffee shop barista named Jamie. "
"You greet customers, take orders, and make small talk about the weather."
)
},
{
"role": "user",
"content": "Hey Jamie, I’d like a latte with oat milk, please."
}
],
temperature=0.7
)
print(response.choices[0].message.content)
When you run that, Jamie might reply:
“Sure thing, one oat milk latte coming right up! It’s a bit drizzly today, isn’t it? Perfect latte weather—want a dash of cinnamon on top?”
Contextual Prompting
Think of contextual prompting like briefing your AI assistant before you start, you give it the relevant background, an article excerpt, product specs, past chat logs, so when you ask your question, it’s already “in the know.” Instead of just saying “Write a summary,” you tack on the bit of text you want summarized or remind it what you’ve already talked about.
Here’s a quick Python example using OpenAI’s SDK:
import openai
openai.api_key = "YOUR_API_KEY"
# Imagine we’ve already discussed a user’s profile above
conversation_history = [
{"role": "system", "content": "You’re a customer-support specialist."},
{"role": "user", "content": "I just upgraded to the Pro plan but still see the old limits."},
{"role": "assistant", "content": "Sorry to hear that—let me check your account."}
]
# Now we prime in extra context: the user’s actual plan details
product_info = """
User: Shivam Kumar
Current Plan: Pro (unlimited projects, 100 GB storage)
Previous Plan: Basic (3 projects, 5 GB storage)
Upgrade Date: April 27, 2025
"""
# And then ask our question
conversation_history.append({"role": "system", "content": f"Context:\n{product_info}"})
conversation_history.append({"role": "user", "content": "Why am I still limited to 5 GB?"})
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=conversation_history,
temperature=0.2
)
print(response.choices[0].message.content)
Multimodal Prompting
Imagine you’re talking to a friend who can see your sketches, photos, or diagrams as well as read your text and then answer questions or tell you stories about what they see. That’s the essence of multimodal prompting, you give the model more than one kind of input (say, an image plus a caption) and it weaves them together into a single response.
Why it’s cool:
Richer context. A picture of your garden plus “What should I plant here?” beats text alone.
Visual reasoning. The model can spot details (“That lamp looks dusty”) or describe scenes.
Cross-modal creativity. You could show a sketch and ask for a poem about it, or feed in an audio clip and ask for a summary.
Sketch of how you’d do it in code (using a hypothetical GPT-4o endpoint that accepts images):
import openai
openai.api_key = "YOUR_API_KEY"
# 1. Read your image file
with open("garden.jpg", "rb") as img_file:
image_bytes = img_file.read()
# 2. Build the multimodal prompt
messages = [
{"role": "system", "content": "You’re a creative gardening assistant."},
# Send the image as raw bytes (the API handles multipart behind the scenes)
{"role": "user", "content": image_bytes},
{"role": "user", "content": "Here’s a photo of my backyard—what flowers would you plant here for spring?"}
]
# 3. Call the chat endpoint
response = openai.ChatCompletion.create(
model="gpt-4o", # supports text + images
messages=messages,
temperature=0.7
)
print(response.choices[0].message.content)
In practice, the library uploads the image and signals to the model, “Hey, look at this too.” The AI then combines its visual “impression” with your text question to give you tailored advice or descriptions. That’s multimodal prompting in a nutshell, using all your senses not just sight!
