Back to Learn

Prompt Engineering

Basics of crafting prompts for large language models.

Last updated: July 2026

ContextInstructionPromptLLMAnswer
Instruction

You start with a clear instruction - the task you want done, stated precisely.

Instruction
How Prompt Engineering worksletslearngenai.com
Listen: Prompt Engineering (student & teacher)StudentTeacher
0:000:00

Prompt engineering is the practice of designing, structuring, and refining the inputs you give to an AI language model. These inputs are called prompts, and they guide the model toward accurate, relevant, and useful responses. It sits at the intersection of communication and computation: the better you phrase your request, the better the AI performs.

The same AI model can produce brilliant or useless output based entirely on how it's asked. Prompt engineering is the skill that bridges the gap.

ComponentWhat it doesExample
Role
Sets the AI's persona or expertiseYou are a senior financial advisor specializing in retirement planning…
Instruction
The core taskSummarize the key risks in the following investment portfolio report
Context
Background infoThe client is 58 years old and plans to retire in 7 years
Input Data
The actual content to process[paste the portfolio report text here]
Output Format
How to structure the resultReturn a 5-bullet list, one risk per bullet, in plain English
Constraints
Scope or tone limitsAvoid technical jargon. Keep each bullet under 20 words.

Full assembled example

You are a senior financial advisor. Summarize the key risks in the investment portfolio below for a client who is 58 years old and retiring in 7 years. Return a 5-bullet list in plain English, avoiding jargon. Keep each bullet under 20 words. [portfolio text here]

Core Principles

  • 1Clarity over brevity - Be specific about what you need.
  • 2One task at a time - Avoid stacking multiple questions into a single prompt.
  • 3Provide context - The AI only knows what you tell it in the prompt.
  • 4Specify the output format - Tell the AI exactly how you want the answer structured.
  • 5Iterate and refine - Treat prompts like drafts. Your second version almost always outperforms the first.
  • 6Test for consistency - Run the same prompt multiple times to verify you get reliable output.

Before vs after iteration

Before

Help me write a job description.

After

Write a job description for a mid-level UX Designer at a fintech startup. Include responsibilities, required skills, and a culture blurb. Use a professional but approachable tone. Under 400 words.

Zero-Shot Prompting

Ask directly, with no examples given. Works best for clear, well-defined tasks where the model already has strong knowledge from training.

Prompt

Classify the following customer review as Positive, Negative, or Neutral:
'The product arrived on time but the packaging was damaged.'

Output

Negative
Use when:Quick classification, translation, basic summarization. Use it when the task is self-explanatory.

Few-Shot Prompting

Provide 2 to 5 examples before asking the model to complete a new one. This greatly improves structure, tone consistency, and accuracy.

Prompt

Classify the sentiment of each review:

Review: "Shipping was fast and the product works great!" → Positive
Review: "Item was broken when it arrived." → Negative
Review: "It's okay, nothing special." → Neutral

Review: "Didn't expect much but I was pleasantly surprised." → ?

Output

Positive
Use when:You need a specific output format, tone, or classification schema the model wouldn't infer from instructions alone.

Chain-of-Thought (CoT)

Ask the AI to reason step by step rather than jump straight to an answer. The trigger phrase "Let's think step by step" greatly improves accuracy on logic, math, and multi-step reasoning.

Prompt

A store sells 3 items at $12 each and offers a 15% discount on orders over $30. What does the customer pay? Let's think step by step.

Output

Step 1: 3 × $12 = $36
Step 2: $36 > $30, so discount applies
Step 3: 15% of $36 = $5.40
Step 4: $36 − $5.40 = $30.60 ✓
Use when:Math, logic puzzles, legal reasoning, multi-condition decisions.

Role Prompting

Assign the AI a persona or expertise domain before giving the task. This shapes the tone, depth, vocabulary, and framing of its response.

Prompt

You are a board-certified nutritionist with 15 years of clinical experience. A patient asks: 'I'm trying to reduce inflammation - what are the top 5 dietary changes I should make?' Respond in a warm but professional tone.

Output

Expert-level dietary recommendations with clinical framing and authoritative tone
Use when:You need expert-level framing, a specific writing voice, or professional accuracy in tone.

Self-Consistency

Run the same reasoning prompt multiple times and take the most consistent answer. This reduces randomness and error in high-stakes situations.

Prompt

A train travels 90 km in 1.5 hours. What is its average speed?
[Run 3 times, take majority answer]

Output

60 km/h (majority of 3 runs agree)
Use when:Medical diagnosis support, financial calculations, legal clause interpretation. Any context where a single wrong answer has real consequences.

Prompt Chaining

Break a complex task into a sequence of smaller prompts, where the output of one feeds into the next.

Prompt

Prompt 1: "List 5 compelling angles for a blog post about remote work burnout."
Prompt 2: "Using angle #3, write a detailed outline with 5 sections."
Prompt 3: "Write the introduction section based on this outline."
Prompt 4: "Now write section 2 in the same tone."

Output

A fully drafted blog post built step-by-step
Use when:Long-form content creation, multi-step code development, research synthesis, complex document generation.

Best Practices

  • 1State the output format explicitly - "Return your answer as a JSON object with keys: name, price, category" is much clearer than "give me the data".
  • 2Use delimiters to separate instruction from input - Wrap input in triple backticks: "Summarize the following: ```[article text]```"
  • 3Include an example of the ideal output - "Your response should look like: 'Company: Acme | Revenue: $5M | Sector: SaaS'"
  • 4Break long tasks into steps - Instead of asking the AI to "Research, summarize, and format a competitor analysis" all at once, use three separate prompts.
  • 5Say what you want, not what you don't want - ✅ "Use formal English" → ❌ "Don't use casual language"
  • 6Add a fail-safe clause for uncertainty - "If you are unsure, say 'I don't have reliable data on this' instead of guessing"
  • 7Test with edge cases - Run your prompt with: (1) a clean typical input, (2) a messy input, (3) an edge case the model might misinterpret

Common Mistakes

MistakeReal-world scenarioFix
Too vague"Help me with marketing" → AI writes generic advice"Write 3 Instagram caption options for a women's activewear brand targeting ages 25–35, using an energetic tone"
Too many instructions"Summarize, translate, reformat, and add bullet points" → jumbled outputSplit into 4 separate prompts in sequence
No context"Is this a good contract clause?" → AI has no idea what typeAdd: "This is a freelance design contract in the US. The clause is about IP ownership…"
No format specified"List the pros and cons" → sometimes paragraph, sometimes table"Return two bullet lists: one for pros, one for cons. Max 5 bullets each."
Contradictory constraints"Be thorough but keep it under 50 words" → AI can't satisfy bothPick one: "Be thorough" OR "Under 50 words"
No fail-safeAI confidently invents a statistic when it doesn't knowAdd: "If unsure, say 'I don't have reliable data on this'"
Never testing edge casesPrompt works on 1 clean example but fails on real messy dataTest with incomplete, ambiguous, and boundary inputs before deploying

Use Cases by Task

Use CasePrompt exampleBest technique
Summarization"Summarize this research paper into 5 key findings for a non-technical audience: [text]"Zero-shot or CoT
Code generation"Write a Python function that returns only dict items where 'status' equals 'active'"Zero-shot or Role
Q&A / Research"Based on this document only, answer: What are the payment terms? [paste doc]"Zero-shot with delimiter
Creative writing"Write the opening paragraph of a thriller set in 1940s Berlin. Short sentences, tense tone."Role + Few-shot
Data extraction"Extract all dates, amounts, and vendor names from this invoice and return as a table: [text]"Zero-shot with format spec
Classification"Label each support ticket as: Billing, Technical, Account, or Other. Ticket: [text]"Few-shot
Translation"Translate this product description to French, keeping the casual marketing tone: [text]"Zero-shot + Role
Reasoning"A startup has 18 months runway and $50K MRR growing 8% monthly. When will they reach break-even at $80K MRR? Show reasoning."Chain-of-Thought
1

Prompt Refinement: Summarization

Weak prompt

Summarize this article
Better prompt

Strong prompt

Summarize the following news article in 3 bullet points. Each bullet should be one sentence. Focus on facts, not opinion. [article text]

Output

• OpenAI released GPT-5 with significant benchmark improvements.
• The model excels at multimodal reasoning tasks.
• Early access is available to Plus subscribers.
2

Code with Role Prompting

Prompt

You are a senior Python developer. Write a function that validates an email address using a regex pattern. Include a docstring and 3 unit test examples.

Output

def validate_email(email: str) -> bool:
    """Returns True if email matches standard format."""
    import re
    return bool(re.match(r'^[\w.+-]+@[\w-]+\.[\w.]+
#x27;, email))
3

Chain-of-Thought vs Direct Answer

Weak prompt

A store sells 3 items at $12 each and offers a 15% discount on orders over $30. What does the customer pay?
Better prompt

Strong prompt

A store sells 3 items at $12 each and offers a 15% discount on orders over $30. What does the customer pay? Let's think step by step.

Output

Step 1: 3 × $12 = $36
Step 2: $36 > $30, so discount applies
Step 3: 15% of $36 = $5.40
Step 4: $36 − $5.40 = $30.60 ✓

Tools & Playgrounds

ToolBest forLink
OpenAI PlaygroundTesting GPT-5.5 with system + user prompts, comparing temperature/model settingshttps://platform.openai.com
Google AI StudioGemini models, multimodal prompting (text + image)https://aistudio.google.com
Anthropic ConsoleClaude models, long-context and document analysishttps://console.anthropic.com
PromptHubSaving, versioning, and sharing prompts across teamshttps://prompthub.us
LangChain / LangSmithBuilding and tracing prompt chains and agentshttps://langchain.com
OllamaRunning open-source models (Llama, Mistral) locally with no API costhttps://ollama.com

Frequently asked questions

What is prompt engineering?

Prompt engineering is the process of crafting and refining the inputs, known as prompts, given to AI language models to guide them in producing accurate and relevant responses. It involves designing prompts to effectively communicate the task to the AI, ensuring the output meets the desired expectations.

How do you create an effective AI prompt?

An effective AI prompt should clearly define the role, instructions, context, input data, output format, and any constraints. This structured approach helps the AI understand the task and produce a more precise and useful response.

What are the core principles of prompt engineering?

Core principles of prompt engineering include prioritizing clarity over brevity, focusing on one task at a time, providing context, specifying the output format, iterating and refining prompts, and testing for consistency to ensure reliable AI output.

What techniques can improve AI prompt results?

Techniques such as zero-shot prompting, few-shot prompting, chain-of-thought reasoning, role prompting, self-consistency, and prompt chaining can enhance the accuracy, consistency, and relevance of AI-generated responses by tailoring the prompt to the specific task and context.

What are common mistakes in prompt engineering?

Common mistakes in prompt engineering include being too vague, providing too many instructions at once, lacking context, not specifying the output format, setting contradictory constraints, omitting fail-safes for uncertainty, and failing to test prompts with edge cases.