Prompt Engineering: Writing Instructions That Work

Learn how to write clear prompts: role, task, context, format, constraints and examples, few-shot prompting, delimiters, step-by-step reasoning, testing and iterating, and basic protection against prompt injection.

25 minBeginnerCode Examples

The Core Idea: A model only knows what is in your prompt. Prompt engineering means giving a clear brief: role, task, context, format, constraints and examples, then testing and improving it like code.

  1. Beginner: What Is Prompt Engineering?

A prompt is the text you send to a model. Prompt engineering is the skill of writing prompts so that the model gives the answer you actually want. The model cannot read your mind. It only sees the words you give it, so missing details are filled in with guesses.

Think of a prompt as instructions for a very capable new colleague who knows a lot in general but knows nothing about your situation. The clearer your brief, the better the result.

Vague promptGets a vague answer
Example: Tell me about this review.
Result: The model must guess what you want.
Clear promptGets a useful answer
Example: Classify this review as positive, neutral or negative. Reply with one word.
Result: Short, predictable, easy to use.

  1. Beginner: The Parts of a Good Prompt

PartQuestion it answersExample
RoleWho should the model act as?You are a customer-support analyst.
TaskWhat exactly should it do?Classify the review below.
ContextWhat material should it use?Review: "The battery died after two days."
FormatHow should the answer look?Reply with JSON only.
ConstraintsWhat must or must not happen?At most 12 words. Do not add other text.
ExamplesWhat does a good answer look like?Two or three sample inputs and outputs.

Remember: You do not need all six parts every time. Add the ones that remove guesswork for your task.

  1. Medium: Few-Shot Examples and Delimiters

Zero-shot means asking with no examples. Few-shot means showing the model a few input and output pairs first. Examples are often the strongest way to communicate a style or format, because the model copies the pattern.

Use delimiters, clear separators such as triple quotes or tags, to keep your instructions apart from the data. This also makes the prompt easier to read and safer against text in the data that looks like instructions.

TechniqueWhen to use it
Zero-shotSimple, common tasks
Few-shot (2 to 5 examples)You need a specific format, tone or label set
Delimiters around dataAlways, when you paste documents or user text
Ask for a formatWhenever another program will read the answer

Tip: Make examples diverse and correct. A wrong example teaches the wrong pattern.

  1. Medium: Reasoning, Step by Step

For multi-step problems such as math, logic or planning, asking the model to show its reasoning before the final answer often improves accuracy. This is called chain-of-thought prompting. A simple version is to add a line such as Think step by step, then give the final answer on its own line.

Newer reasoning models: Some models already reason internally before answering. For them, a simple clear question often works best and extra instructions to think step by step may not be needed. Test both ways on your task.

Breaking big tasks up
Instead of one huge prompt, split the work: first extract the facts, then write the summary, then check it. Each step is easier to get right and easier to debug.

  1. Advanced: Testing, Iterating and Staying Safe

Prompts are small programs, so treat them like code: test them on a set of real examples, change one thing at a time, and keep a record of what worked.

HabitWhy it matters
Keep a test set of 20+ real inputsA prompt that works on one example may fail on others
Change one thing at a timeSo you know what caused the improvement
Version your promptsYou can go back when a change makes things worse
Watch for prompt injectionText in user data may say ignore previous instructions. Keep untrusted text clearly separated and never give the model power you would not give a stranger
Ask for uncertaintyAllow answers like I do not know to reduce invented facts

Security note: Never put secrets, passwords or API keys inside a prompt. Assume anything in the prompt could be revealed.

  1. Visual Explanation: From Vague to Precise

The figure contrasts a weak prompt with a strong one and shows the loop used to improve prompts.

Part 1 · Weak vs. Strong PromptSame model, different brief
Weak promptVague
Tell me about this review.
↓
Unpredictable answer, hard to use
Strong promptStructured
Role + task + input
↓
Format + constraints
↓
One example
↓
Short, consistent, machine-readable answer
Part 2 · The Improvement LoopPrompts are tested like code
Step 1 · Write
First draft
Role, task, context, format.
Step 2 · Test
Real inputs
Run on 20 or more examples.
Step 3 · Improve
One change
Fix the biggest failure, then repeat.
Click to see the six-part checklistCompare ▼
Role, task, context, format, constraints, examples. The linter in the code below scores a prompt out of six by looking for each part.

Part 1 compares what each prompt contains and what you get back. Part 2 shows the write, test and improve cycle. Open the bar to see the checklist the code uses.

  1. Python Implementation: A Prompt Linter and a Few-Shot Builder

This script does two practical things. It scores a prompt on the six parts of a good prompt (a simple linter), and it builds a few-shot prompt from a list of examples so you never have to type it by hand.

prompt_tools.pyPython 3.10+ · standard library only
# A small "prompt linter": checks whether a prompt contains the parts of a good promptCHECKS = {    "role": ["you are", "act as"],    "task": ["summarize", "classify", "explain", "write", "extract", "translate"],    "context": ["context:", "text:", "document:", "input:"],    "format": ["format", "json", "bullet", "table", "words", "sentences"],    "constraints": ["do not", "only", "must", "at most", "never"],    "examples": ["example", "for instance"],} def lint(prompt):    text = prompt.lower()    found = [name for name, words in CHECKS.items() if any(w in text for w in words)]    return found, [name for name in CHECKS if name not in found] weak = "Tell me about this review."strong = (    "You are a customer-support analyst.\n"    "Task: classify the review below as positive, neutral or negative.\n"    "Input: 'The battery died after two days.'\n"    "Format: answer with JSON only, like {\"label\": \"...\", \"reason\": \"...\"}.\n"    "Constraints: the reason must be at most 12 words. Do not add any other text.\n"    "Example: Input: 'Great screen!' -> {\"label\": \"positive\", \"reason\": \"praises the screen\"}")for name, prompt in [("weak prompt", weak), ("strong prompt", strong)]:    found, missing = lint(prompt)    print(name, "-> score", len(found), "/", len(CHECKS), "| missing:", missing) # Build a few-shot prompt from data instead of typing it by handexamples = [("I love it", "positive"), ("It broke at once", "negative"), ("It is okay", "neutral")]def few_shot(examples, new_text):    lines = ["Classify the sentiment as positive, neutral or negative."]    for text, label in examples:        lines.append("Text: " + text + "\nSentiment: " + label)    lines.append("Text: " + new_text + "\nSentiment:")    return "\n\n".join(lines) prompt = few_shot(examples, "Delivery was slow but the product is great")print("Few-shot prompt has", len(prompt.split()), "words and ends with:", repr(prompt.split("\n")[-1]))
EXPECTED OUTPUT (your numbers may differ slightly)
weak prompt -> score 0 / 6 | missing: ['role', 'task', 'context', 'format', 'constraints', 'examples']
strong prompt -> score 6 / 6 | missing: []
Few-shot prompt has 37 words and ends with: 'Sentiment:'

The weak prompt scores 0 out of 6 and the strong one scores 6. The few-shot builder always ends with Sentiment: so the model knows exactly what to complete.

Interactive Knowledge Check

Question 1: What is few-shot prompting?
Question 2: Why use delimiters around pasted text?

Key Points

✓A prompt is a brief for a capable colleague who knows nothing about your situation.
✓Good prompts include role, task, context, format, constraints and examples, as needed.
✓Few-shot examples are one of the strongest ways to set format and style.
✓Use delimiters to separate instructions from data and to reduce injection risk.
✓Step-by-step reasoning helps on multi-step problems, but test it, especially on reasoning models.
✓Test on real examples, change one thing at a time, and never put secrets in a prompt.

The Big Picture

Prompting in One Line

Clear role + clear task + the right context + a format + an example → predictable answers

Better prompts are the cheapest improvement you can make. Before fine-tuning or switching models, improve the prompt.

Up Next: You now know how to write the prompt. In LLM APIs and Open-Source Models you will learn how to send it from your own code and how to choose between hosted and local models.