Skip to content

Lesson 3 of 40How AI works

Prompting That Works

Write prompts that get useful answers the first time, using context, examples, structure, formats and iteration, with before and after examples.

16 min read0/4 questions

Most disappointing AI answers come from prompts that left the model guessing. The model is not lazy or stupid; it simply cannot see your project, your goal or your standards unless you put them in the prompt. "Prompt engineering" sounds like a bag of magic phrases, but the techniques that actually work are the same ones that work on a smart new colleague: say what you want, explain why, show an example, and say what "done" looks like. This lesson turns those into habits, with real before and after prompts you can reuse.

The new colleague test

Imagine handing your prompt to a sharp developer who joined the team this morning. They have never seen your codebase, do not know your users, and cannot ask follow-up questions. Would they produce what you want? If not, the model will not either.

Here is a typical first attempt:

Write a function to validate emails.

The model has to guess the language, how strict to be, what to return, and whether you want tests. It will pick the most common answer from its training data, which is probably a Python regex that is either too strict or too loose for you. Now the same request after the new colleague test:

Write a TypeScript function `isValidEmail(input: string): boolean` for our
signup form.
 
Context: this is a quick client-side check to catch typos before we send a
verification email, so it should be permissive. The server does the real
check. Rejecting a real address is worse than accepting a fake one.
 
Rules:
- Exactly one @, with something on both sides
- The domain part contains at least one dot
- Trim surrounding whitespace first
- No external libraries
 
Return only the function and 6 example calls with expected results.

Every added line removes a guess. The model knows the language, the signature, the purpose, the trade-off, the rules and the output shape.

Clear, specific, and with the why

Being specific means naming the things you care about: the language and version, the inputs and outputs, the constraints, the length, the audience. "Make this better" is a guess; "make this function easier to read for a junior developer, without changing its behaviour" is a task.

Giving the why matters as much as the what. Compare "Never use ellipses" with "This text will be read aloud by a text-to-speech engine, so never use ellipses, because it cannot pronounce them". The second version lets the model generalise: it will also avoid other things a speech engine cannot read. Rules without reasons get followed literally; rules with reasons get followed intelligently.

Context is anything the model cannot know on its own: the error message, the relevant file, the library version, what you already tried. "My React component re-renders too much" invites generic advice. Pasting the component, the parent that renders it, and "this happens when I type in the search box" invites a diagnosis.

Quick check
You ask a model to 'fix the bug in my login code' and get a generic list of common login mistakes. What is the BEST next prompt?
Need a nudge? A hint rules out a wrong answer.

Show, do not just tell: examples

Describing a format in words is hard. Showing it is easy. Giving a few examples of input and the output you want is called few-shot prompting (one example is "one-shot", none is "zero-shot"). Models copy the patterns in examples very closely, which is a superpower and a trap.

Turn each commit message into a one-line changelog entry for users.
 
<examples>
<example>
Commit: fix(auth): handle null session in middleware
Changelog: Fixed a bug that could log you out unexpectedly.
</example>
<example>
Commit: feat(export): add CSV export to reports page
Changelog: You can now export reports as CSV files.
</example>
</examples>
 
Commit: perf(search): debounce input and cache results
Changelog:

The trap: if all your examples are short, every answer will be short. If they all start with "You can now", the model will start bug fixes that way too. Make examples varied (different lengths, cases and edge cases) and relevant to the real inputs you expect.

Structure: headings and tags

A prompt with instructions, a document, some examples and a question all jumbled together is hard for anyone to read. Separate the parts. Markdown headings work, and XML-style tags work especially well with Claude: wrap each part in a descriptive tag such as <document>, <instructions> or <examples>. There is nothing special about the tag names; they just mark clear boundaries, so the model does not confuse the text you want summarised with the instructions about how to summarise it.

Anatomy of a strong prompt
  1. Role (optional)only when it changes the answer
  2. Context and goalwho it is for, why, what done looks like
  3. Input materialcode, docs, data in tags
  4. Instructionsthe task, rules, and their reasons
  5. Examplesvaried input and output pairs
  6. Output formatshape, length, what to leave out

Context and goal do the most work. Skip everything else before you skip this.

1/5

Roles: useful, not magic

Setting a role, like "You are an experienced accessibility auditor", focuses the model on a perspective and vocabulary. It helps when the role changes what gets noticed: a security reviewer looks for injection, a technical editor looks for unclear sentences. In the API, the role usually goes in the system prompt, the instructions that sit above the conversation:

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    system="You are a security reviewer. Report only exploitable issues, with the line and a fix.",
    messages=[{"role": "user", "content": "Review this function: ..."}],
)

What a role cannot do is add knowledge. "You are a world-class Rust expert" does not make the model know more Rust. A paragraph of real context about your project beats any amount of flattery.

Ask for a format

If you are going to paste the answer somewhere, say what shape it must have. "Return a Markdown table with columns Endpoint, Method, Auth required." "Respond with JSON only, matching this shape." "Give me the diff, no explanation." "Answer in under 100 words." Say what to include and what to leave out.

Tell the model what to do rather than what not to do. "Write in flowing paragraphs" works better than "Do not use bullet points". For programs that read the output, ask for JSON with an exact shape; when you build features on the API, structured outputs can enforce a schema for you, which the AI Features in Production lesson covers.

Match the pairs0/5 matched

Match each problem to the technique that fixes it.

Choose an item, then its match on the other side.

Let it think, and let it say "I don't know"

For hard problems (debugging, tricky logic, design trade-offs), ask the model to reason before answering: "Think through the possible causes step by step before you suggest a fix." As the How LLMs Work lesson showed, written-out reasoning becomes part of the model's context and makes the final answer more likely to be right. Models with extended thinking do this on their own, but asking for the steps still helps you check the reasoning. For simple lookups it just adds length.

Models are trained to be helpful, which can tip into answering when they should not. Give explicit permission to admit uncertainty:

Answer only from the documentation in <docs>. If the answer is not there,
say "Not in the docs" instead of guessing. For each claim, quote the line
it comes from.

Asking for quotes or sources makes answers easy to verify, and "you may say you don't know" measurably reduces invented answers. It does not eliminate them, so still check anything important.

Quick checkPick all that apply
You want a model to answer questions about your internal API docs without inventing endpoints. Which TWO changes help most?

None picked yet

Need a nudge? A hint rules out a wrong answer.

Iterate on prompts like code

Good prompts are rarely written in one go. Treat them like code: write a version, run it on several realistic inputs (not just the one you had in mind), look at what went wrong, change one thing, run again. Keep prompts you reuse in files under version control, so you can see what changed when results got worse.

Python
# A reusable prompt is just a template with clear slots.TEMPLATE = """<context>{context}</context> <code>{code}</code> <instructions>Review the code for {focus}. List at most {limit} issues, most seriousfirst. For each: the line, the problem, and a one-line fix. If there areno real issues, say "No issues found" instead of inventing some.</instructions>""" prompt = TEMPLATE.format( context="Flask API used by our mobile app. Python 3.12.", code="def get_user(id):\n return db.execute(f'SELECT * FROM users WHERE id={id}')", focus="security problems", limit=3,)print(prompt)print(f"\n{len(prompt.split())} words, {prompt.count('<') // 2} tagged sections")
Output
Press Run (⌘ Enter) to see what happens.
Prompts are tested like code
Prompt v3: kept in gitPrompt v3kept in gitTest inputs: real and edge casesTest inputsreal and edge casesModel: runs each inputModelruns each inputReview: what failed, and whyReviewwhat failed, and whyPrompt v4: one changePrompt v4one changewithfeedoutputsfix the causere-run all

Run the current prompt on several inputs, including awkward ones: empty input, very long input, a different language.

1/4

When an answer is wrong, resist "please try again". Ask why it went wrong: was context missing, was the instruction ambiguous, did an example mislead? Fix that cause in the prompt. Once a conversation has gone off the rails twice, starting fresh with an improved prompt usually beats a third correction, because the bad attempts are now part of the context.

Put it in order5 steps

Put the prompt iteration loop in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
prompt
The full input you give a model: instructions, context, examples and the question.
system prompt
Instructions set above the conversation, often holding the role and the rules.
few-shot prompting
Including a few input and output examples so the model copies the pattern.
XML-style tags
Labels like <docs>...</docs> that separate parts of a prompt clearly.
role prompting
Telling the model what perspective to take. A nudge, not extra knowledge.
prompt iteration
Improving a prompt by testing on varied inputs and fixing causes of failure one at a time.