MemberPress AI Academy memberpress.ai

Courses

Prompt Engineering 101

Nineteen lessons of structure, specificity, examples, and chained prompts.

beginner3h 45m19 lessonsTaught by Seth Shoultes

Overview

The complete Anthropic curriculum for writing effective prompts. Four modules of hands-on prompting practice — from basic structure to building complex chained prompts.

What You Will Learn

About This Course

Nineteen short lessons, each on one technique, with prompts to try as you go.

BeginnerFoundations of a Good Prompt

1. Welcome & how this works 4 min

Lesson notes

Most people write prompts the way they write search queries: a few words, a vague intent, and hope. That habit produces vague answers. This course replaces that habit with a set of techniques you can apply immediately.

What this course is

Nineteen lessons on prompt engineering. Each lesson covers one technique. The lessons are short by design — the goal is that you practice the technique during the lesson, not after it.

The structure is consistent across every lesson. You get a short explainer, one or more before/after prompt examples, prompts to try in Claude yourself, and a deliverable that tells you whether you actually understood the technique or just read about it. If the deliverable doesn't work, you haven't finished the lesson.

What you will be able to do when you finish

By the end of module one, you will know how to structure a prompt so Claude understands what you want, who it is writing for, and what format to produce. That alone eliminates roughly 80% of the frustrating answers most people get from Claude on the first try.

By the end of module two, you will be able to separate data from instructions, request structured output like JSON, and guide Claude's reasoning step by step. These are the techniques that separate a person who uses AI from a person who uses AI well.

By the end of module three, you will have built prompts for three real professional domains — legal, finance, and code — and you will understand how to prevent the specific failure mode that causes Claude to invent facts it doesn't know.

Module four covers the techniques that power production systems: chaining prompts, calling external tools, and connecting Claude to documents it has never seen.

How to practise

Keep Claude open in another tab (claude.ai or Claude Desktop) and work alongside each lesson. You can run the same prompt multiple times with different wording and compare the results side by side. This is the fastest way to develop an intuition for what the model responds to.

The prompts listed at the top of each lesson are starting points, not exercises with one right answer. Use them to get your first response, then modify them and observe what changes.

Prerequisites

None. If you can type a sentence, you can work through this course.

If you get stuck

If a lesson's deliverable doesn't click, the most common cause is that the concept hasn't been tried with your own material yet. The examples in each lesson are generic by necessity. Swap in a real task from your work — a real email, a real document, a real piece of code — and the technique usually lands.

Deliverable

Type a prompt into Claude. Any prompt. Observe the response. Then modify one element — audience, format, or length — and run it again. Notice what changed.

Try these prompts

  • Write a 3-paragraph welcome email to new team members.
  • Summarize the main idea of this course in one sentence.

Back to contents

2. Basic prompt structure 6 min

Lesson notes

"Tell me about dogs" is a grammatically complete sentence. It is also a prompt that will produce a generic answer about dogs — domestication history, breeds, care requirements — none of which is what you wanted. The problem is not the question. The problem is that the question contains no information about what useful would look like for you.

A good prompt has three parts: task, context, and output format.

Task

The task is what you want done. Not "tell me about" — that is a category of answer. The task should be a verb with a specific object: summarize, classify, rewrite, extract, compare, draft.

Wrong: "Tell me about machine learning." Right: "Explain the difference between supervised and unsupervised learning."

The right version has a specific verb (explain) and a specific object (the difference between two things). Claude now knows what kind of answer to produce.

Context

Context is the background Claude needs to produce a useful answer. Who is the audience? What constraints apply? What does the person already know? What should the answer avoid?

Without context, Claude makes assumptions. Those assumptions may not match yours. Give Claude the information it would need to write something specific rather than generic.

Wrong: "Explain machine learning." Right: "Explain the difference between supervised and unsupervised learning to a non-technical marketing manager who needs to understand why our recommendation system sometimes surfaces irrelevant products."

The right version tells Claude the audience (non-technical marketing manager), the frame (recommendation system), and the purpose (explaining a specific behavior). Claude can now write something that will actually be useful to that person.

Output format

Format is how the answer should look. Paragraph? Numbered list? JSON? A table? 50 words or 500? The format constraint is often the most neglected part of a prompt, and it is frequently the most important. A five-paragraph essay and a three-bullet summary of the same content serve completely different purposes.

Right: "Explain the difference between supervised and unsupervised learning to a non-technical marketing manager in three bullet points, each under 25 words."

Putting it together

When you write a prompt, run this quick check: Does the model know what verb to perform? Does it know who it is writing for and what constraints apply? Does it know what format to produce? If any of these is missing, the prompt will produce something that might be right, or might not, and you will not know why.

If you get stuck

If the output is still too generic after adding context, the context is likely still abstract. Replace adjectives with specifics. "Non-technical" is abstract; "a person who manages email campaigns and has never written code" is specific. "Brief" is abstract; "under 50 words" is specific.

If you are unsure what format to request, look at an example of a good answer in that domain and describe its structure back to Claude.

Cross-reference

L4 (Being clear and direct) goes deeper on specificity. L7 (Separating data from instructions) covers what to do when the context itself is a large block of text.

Deliverable

Take this prompt: "Write an email." Add task, context, and format until it produces the specific email you actually need. The prompt should be at least three sentences. The output should be something you could send.

Further reading

  • "Nouns and Verbs" — why a prompt that names the noun and the verb explicitly produces a different class of output than one that gestures at either.

Try these prompts

  • Rewrite this vague prompt with task, context, and format: "Tell me about dogs."
  • Write a prompt asking Claude to summarize a meeting transcript in 3 bullets.

Back to contents

3. Practice - rewrite this prompt 5 min

Lesson notes

The gap between a vague prompt and a useful one is usually a few sentences of specificity. This practice session is about closing that gap on three prompts that are vague by design.

The pattern you practiced in L2

Task + context + format. That is the structure. Apply it to each prompt below and compare the output to what you get from the vague version.

Before and after: worked example

Before: "Tell me about birds."

After: "Write a 100-word summary of how North American migratory birds navigate across thousands of miles. Write it for a curious ten-year-old. Include three specific species and end with one sentence about why migration matters for ecosystems."

Run both in Claude. The before version will produce a general encyclopedia entry. The after version will produce something that could actually be read to a child.

What changed: the verb became specific (write a summary, not tell me about), the audience was named, the length was bounded, the scope was narrowed (navigation, not birds in general), and a structural requirement was added (three species, one closing sentence).

Your turn: three prompts to rewrite

Prompt 1: "Write an email."

Before you rewrite it, answer these questions: Who is the email to? What does it need to accomplish? What tone is appropriate? How long should it be? Now put those answers into the prompt.

Prompt 2: "Explain machine learning."

Who is the explanation for? What analogy domain are they familiar with? How much do they already know? What decision does this explanation help them make?

Prompt 3: "Tell me about birds."

Pick a specific angle — migration, behavior, a particular species, ecological role. Name the audience. Set a length. Add one structural requirement (a specific example, a comparison, a closing takeaway).

If you get stuck

If the rewritten prompt still produces something generic, the format constraint is probably missing. Add a word count and a structural requirement. Those two additions alone usually break generic outputs.

If you are not sure what context to add, write down in plain language why you want the information. That sentence usually contains the context the prompt is missing.

Deliverable

Rewrite all three prompts. For each one, run the before and after versions side by side. Pick the one where the difference is most dramatic. Keep that rewritten prompt — you will use a similar structure in L5.

Try these prompts

  • Tell me about birds.
  • Write an email.
  • Explain machine learning.

Back to contents

4. Being clear and direct 6 min

Lesson notes

Most prompts are vaguer than their authors think. The author knows what they meant. Claude does not. Claude reads the words that are there, not the intent behind them.

This lesson is about removing the gap between what you intend and what you write.

Specificity in three dimensions

Prompts fail on specificity in three places. Fixing all three is the difference between a prompt that works most of the time and one that works almost every time.

Dimension 1: Audience. Who is the output for? "Non-technical" is a start, but it is still abstract. "A marketing manager who has run email campaigns for five years and has never written a line of code" is a picture. Claude can write for a picture. It cannot write for an adjective.

Dimension 2: Format. "Brief" means three words to one person and three pages to another. Give Claude a number. "Under 50 words." "Three bullet points, each one sentence." "A two-paragraph memo." Numbers are unambiguous.

Dimension 3: Constraints. What should the output avoid? What should it include? "Use only cooking analogies" is a constraint. "Do not use technical jargon" is a constraint. "Include the product name in the first sentence" is a constraint. Constraints narrow the space of valid answers, which narrows the space of bad answers.

Before and after

Before: "Explain machine learning."

After: "Explain machine learning to a non-technical marketing manager in 3 bullet points, using only cooking analogies. Each bullet should be one sentence. Do not use the words 'algorithm,' 'model,' or 'data.'"

The before version produces a general explanation. The after version produces something specific, bounded, and constrained. The constraint about banned words forces Claude to find analogies rather than falling back on jargon.

A note on directness

Claude does not need to be flattered or coaxed. It does not perform better when you say "please" or "this is very important." What it responds to is precision. Write the prompt the way you would write a specification: state what you want, state what you do not want, state the format.

If you find yourself writing "I need you to try to write something that kind of explains..." you have already lost. Start over. State the task as a single direct imperative sentence.

If you get stuck

If the output is still not specific enough, the audience description is probably still abstract. Replace the adjective with a job title and one concrete fact about that person's knowledge or situation.

If the output is too long, add a word count constraint. If it is too short, add "Explain in detail, covering at least X points."

Cross-reference

L2 covered the basic three-part structure (task, context, format). This lesson deepens the format and context dimensions. L6 (Assigning roles) covers a different way to sharpen audience specificity.

Deliverable

Take the LinkedIn post prompt: "Draft a 50-word LinkedIn post announcing [your company]'s new feature." Fill in your actual company and feature. Add one audience constraint, one banned word or phrase, and one structural requirement. Run it. The output should be something you could post.

Try these prompts

  • Explain machine learning to a non-technical marketing manager in 3 bullet points, using only cooking analogies.
  • Draft a 50-word LinkedIn post announcing [your company]'s new feature.

Back to contents

5. Practice - add specificity 5 min

Lesson notes

The prompts in this practice session are the kind you encounter in real work. They are not obviously bad. They just lack the specificity that would make them produce something immediately usable.

The three-question test

Before you rewrite any of these prompts, run them through three questions:

Who is the reader? (Not "customers" — a specific type of customer at a specific point in their decision process.)

What format produces the most value? (A product description that lives on a landing page is different from one that goes in a catalog that goes to retailers.)

What constraints would make the output immediately usable? (Word count, tone, banned phrases, required inclusions.)

Answer all three questions in plain language. Then put those answers into the prompt.

Worked example

Before: "Write a product description for our new coffee maker."

The author knows this is a high-end pour-over coffee maker for specialty coffee enthusiasts. It costs $299. The description goes on a product page. The competition is described in terms of precision and ritual. The reader has already decided they want a premium coffee maker and is choosing between three.

None of that is in the prompt. Claude has to guess.

After: "Write a 120-word product description for a $299 pour-over coffee maker aimed at specialty coffee enthusiasts who are comparing premium options. The description goes on a product page. Emphasize precision and ritual. Do not use the words 'simple,' 'easy,' or 'convenient.' End with a single sentence about the experience of using it."

Run both versions. The after version will produce something close to usable. The before version will produce something generic.

Your turn

Prompt 1: "Summarize the quarterly report."

What does the summary need to cover? Who reads it and what decisions do they make with it? What format — bullets, memo, one paragraph? How long?

Prompt 2: "Draft a message to the team about the new policy."

What policy? What does the team need to understand or do? What tone — direct, reassuring, explanatory? What should the message not say?

If you get stuck

If you do not know enough about the task to add specificity, that is useful information. It means the prompt is not ready to be written yet — you need to gather the context first. Real prompts fail for the same reason: the person writing them does not yet know what they need.

Deliverable

Rewrite both prompts with full specificity. For each, run the before and after version. The after version should produce something you could use without editing.

Try these prompts

  • Write a product description for our new coffee maker.
  • Summarize the quarterly report.
  • Draft a message to the team about the new policy.

Back to contents

6. Assigning roles 5 min

Lesson notes

Claude's default voice is helpful and informative, which is useful for many tasks and exactly wrong for others. If you are trying to find problems in a business plan, helpful and informative is not what you need. You need skeptical and rigorous.

Assigning a role changes Claude's perspective, vocabulary, and reasoning patterns. It is one of the highest-leverage changes you can make to a prompt.

How to assign a role

Start the prompt with a role declaration: "You are a [role] with [relevant experience or perspective]."

The role declaration works because it activates a coherent cluster of behaviors. A skeptical security auditor looks for edge cases and attack vectors. A patient kindergarten teacher simplifies, uses analogies, and repeats key ideas. A senior engineer reviewing a pull request notices architectural problems, not just syntax.

You do not have to justify the role. Just declare it.

Examples that work

"You are a skeptical security auditor with ten years of experience in API security. Review this API design and list every vulnerability you can find, ranked from most to least severe."

"You are a patient kindergarten teacher explaining photosynthesis to a five-year-old. Use one analogy involving food. Check for understanding at the end with a simple question the child could answer."

"You are a senior engineer reviewing a pull request for a payment processing system. Your job is to find problems, not to validate the work. List every issue you see, starting with the most serious."

Roles that do not work

The role must be relevant to the task. "You are Shakespeare" does not help with Python debugging. "You are a friendly assistant" is too generic to change anything — it is Claude's default. The role should activate a specific perspective that you actually need for the task.

Avoid roles that conflict with the task. "You are an optimistic coach" reviewing a business plan for risks will produce an optimistic evaluation of risks, which is not useful.

If you get stuck

If the role assignment does not change the output, the role is probably too generic. Add a specific qualification or perspective: not "you are an editor" but "you are an editor who specializes in cutting text by 30% without losing meaning."

If the output sounds like a caricature rather than the actual role, soften the role and add a specific task. The role is a frame, not a performance.

Cross-reference

L4 covers specificity in the task and format dimensions. The role dimension is a third axis of specificity — it shapes Claude's approach to the task, not just what it produces.

Deliverable

Take a prompt you use regularly. Assign a role that matches the perspective you actually need. Run the same prompt with and without the role declaration. Note what changes in the output — not whether it got "better," but what specifically changed.

Try these prompts

  • You are a skeptical security auditor. Review this API design for common vulnerabilities.
  • You are a patient kindergarten teacher. Explain photosynthesis to a 5-year-old.

Back to contents

IntermediateShaping the Output

7. Separating data from instructions 7 min

Lesson notes

When instructions and data are mixed together in a single block of text, Claude has to guess where the instructions end and the data begins. That guess is sometimes wrong. The fix takes thirty seconds and eliminates an entire class of prompt failures.

The problem in concrete terms

Imagine you paste a customer email into a prompt like this:

"Summarize the key requests in this email and classify each as urgent or not. Dear Support Team, I am writing to ask about my subscription which was supposed to renew on March 1st but I have not received a confirmation email yet. Also I wanted to check whether the API rate limits have changed recently as I am seeing more 429 errors than usual. Please let me know as soon as possible."

Claude has to figure out that "Dear Support Team" is the beginning of the email and not part of the instruction. It usually gets this right. But "usually" is not good enough in a production prompt that runs on thousands of inputs.

The solution: delimiters

Delimiters are markers that explicitly separate instructions from data. The most common options are XML tags, triple backticks, and section headers in all caps.

XML tags:

Summarize the key requests in this email and classify each as urgent or not.

<email>
Dear Support Team, I am writing to ask about my subscription...
</email>

Triple backticks:

Summarize the key requests in the following email and classify each as urgent or not.

Dear Support Team, I am writing to ask about my subscription...


Both work. XML tags are preferred when you have multiple sections to separate (instructions, examples, data, format specification) because they are labeled.

Rules for using delimiters

Place instructions before the data. Claude reads the prompt in order. Instructions at the top mean Claude knows what to do before it reads the data. Instructions at the bottom mean Claude reads the data first, then discovers what to do with it, and sometimes has to re-interpret what it already processed.

Use consistent delimiters throughout a prompt. If you open with <email> tags, do not switch to triple backticks partway through. Inconsistent delimiters create ambiguity.

Label every section. If your prompt has instructions, examples, and data, give each its own labeled section. <instructions>, <examples>, <data>. Claude processes labeled sections correctly even when they are long.

If you get stuck

If the output is treating part of your data as an instruction, the delimiter is either missing or inconsistent. Check that the tag opens exactly where the data begins and closes exactly where it ends.

If you are using backticks and the data itself contains backticks (code, for example), switch to XML tags. They are more robust when the data contains the delimiter character.

Cross-reference

L9 (Format a JSON output) builds on this technique — the data goes inside tags, the schema goes in the instructions.

Deliverable

Take a prompt where you paste in a block of text (an email, a document excerpt, a code snippet). Add XML tags around the data. Run both versions. If the outputs are identical, that is fine — the delimiter is insurance, not a magic ingredient. If the output changes, note which version is more accurate.

Try these prompts

  • Summarize the following article using triple backticks to wrap the text: \`\`\`[paste article here]\`\`\`
  • Extract the action items from this meeting transcript wrapped in <meeting> tags.

Back to contents

8. Formatting & speaking for Claude 6 min

Lesson notes

Claude responds to the structure of your prompt, not just its content. A prompt written as a wall of text asks Claude to produce output that fits the shape of the input. A prompt written with clear sections, labeled parts, and explicit format instructions asks Claude to produce something structured and usable.

This lesson is about how to write a prompt that communicates structure, and how to ask for output in a format you can actually use.

How formatting affects Claude's output

Claude is trained on a large amount of well-structured text. It has seen millions of examples of what a numbered list looks like, what a markdown table looks like, what a code block looks like. When you use these structures in your prompt, you activate Claude's pattern recognition for them.

If your prompt uses bullet points, Claude tends to produce bullet points. If your prompt uses numbered steps, Claude tends to produce numbered steps. If you want a specific format, model that format in the prompt itself.

Explicit format instructions

Modeling format is not enough on its own. Always add an explicit instruction about the output format:

"Explain how HTTPS works. Use numbered steps for the sequence of events. Bold the name of each protocol involved. Keep each step to one sentence."

"Compare these two project management tools. Produce a markdown table with four rows: cost, learning curve, integration options, and best use case. Fill in one cell per tool per row."

The explicit instruction removes ambiguity. Claude does not have to infer what "compare these tools" means as a format — you told it.

What works in practice

Line breaks between sections signal transitions. If your prompt has instructions in one section and data in another, leave a blank line between them.

Numbered lists work for sequential steps. Use them when order matters.

Bullet points work for parallel options or requirements. Use them when order does not matter.

Headers (markdown ## or ALL CAPS) work for multi-section prompts. If your prompt has instructions, examples, and data, give each section a header.

Triple backticks signal code or exact text. Use them when you want Claude to treat the content literally.

What does not work

Burying the format instruction at the end of a long prompt. Put it near the top or just before the data.

Asking for a format Claude cannot produce in the interface you are using. JSON works in a chat with Claude. Rendered markdown tables may or may not render depending on where the output lands.

If you get stuck

If Claude is not producing the format you asked for, add "Produce only the [table/list/JSON]. No introduction, no explanation." This removes Claude's tendency to preface structured output with a sentence of explanation.

If the output structure is close but not quite right, paste the structure you want into the prompt as an empty template and ask Claude to fill it in.

Cross-reference

L9 (Practice — format a JSON output) is the applied version of this lesson. L13 (Building complex prompts from scratch) covers how to use headers and sections to build multi-step prompts.

Deliverable

Pick a comparison you need to make — two tools, two vendors, two approaches. Write a prompt that asks Claude to produce a markdown table with at least three criteria. Run it. If the table structure is wrong, add an explicit empty template to the prompt and run it again.

Try these prompts

  • Write a prompt that asks Claude to explain a concept using numbered steps and bold headers.
  • Ask Claude to compare [Product A] vs [Product B] in a markdown table with 4 criteria.

Back to contents

9. Practice - format a JSON output 6 min

Lesson notes

JSON is the most common format for getting structured data out of Claude in a way that a downstream system can consume. The technique for getting reliable JSON is specific: you tell Claude the exact schema you want, you put the data inside delimiters, and you tell Claude to produce nothing else.

Why JSON output fails

The most common failure is asking for JSON without specifying the schema. "Extract the names and dates as JSON" produces different JSON every time — sometimes an array of objects, sometimes an object with arrays, sometimes something else. If your downstream system expects a specific structure, you have to specify it.

The second most common failure is Claude wrapping the JSON in an explanation. "Here is the JSON you requested: ..." followed by the JSON. If you are piping the output to a system, that prefix breaks the parse.

The pattern that works

Step 1: State the task. Step 2: Specify the schema. Step 3: Put the data in delimiters. Step 4: Tell Claude to produce only the JSON, no explanation.

Assembled:

Extract the people and dates mentioned in the following paragraph.
Return your answer as JSON with this exact structure:
{"people": [{"name": "string", "date": "string", "context": "string"}]}
If no people or dates are found, return {"people": []}.
Produce only the JSON. No explanation, no introduction.

<paragraph>
Sarah Chen joined the project on April 3rd. Marcus Webb had been leading the infrastructure work since January and was scheduled to hand off to the new team by May 15th.
</paragraph>

Expected output:

{"people": [{"name": "Sarah Chen", "date": "April 3rd", "context": "joined the project"}, {"name": "Marcus Webb", "date": "January", "context": "leading infrastructure work"}, {"name": "Marcus Webb", "date": "May 15th", "context": "scheduled handoff"}]}

Handling edge cases in the schema

Always specify what Claude should return when the data is empty or ambiguous. "If no people or dates are found, return {"people": []}." Without this, Claude may return null, an empty string, or an explanation of why there was nothing to extract — none of which parse correctly.

If you get stuck

If Claude is returning JSON with a different structure than you specified, check that your schema example is valid JSON. An extra comma or a missing bracket causes Claude to produce what it inferred you meant, not what you wrote.

If Claude keeps adding an explanation before the JSON, add "Your entire response must be valid JSON. Begin your response with {." This constraint is usually sufficient.

Cross-reference

L7 (Separating data from instructions) covers the delimiter technique used here. L13 (Building complex prompts from scratch) shows how to combine schema specification, delimiters, and guardrails into a production-grade prompt.

Deliverable

Write a prompt that extracts structured data from a short paragraph of your choice. Define the schema explicitly. Run it. Paste the output into a JSON validator (jsonlint.com or similar). If it passes validation, the prompt works. If it does not, debug the schema specification and try again.

Try these prompts

  • Extract the names and dates from this paragraph.
  • List the top 3 risks in the project update.
  • Summarize the customer feedback as JSON with sentiment scores.

Back to contents

10. Precognition (think step-by-step) 7 min

Lesson notes

Claude generates text token by token, left to right. The text it has already produced is visible to it as it produces the next token. This is not a metaphor or a simplification — it is a description of how the model works.

The implication is direct: if Claude articulates its reasoning before it produces an answer, the reasoning is on the page when the answer is generated. The answer is conditioned on the reasoning. Answers conditioned on written reasoning are more accurate than answers produced without it.

This is what "think step by step" does. It is not encouragement. It is an instruction to produce the reasoning before the conclusion.

The bat and ball problem

"A bat and a ball cost $11 in total. The bat costs $10 more than the ball. How much does the ball cost?"

Without step-by-step reasoning, the intuitive answer is $1. That answer is wrong. The ball costs $0.50 (bat = $10.50, ball = $0.50, total = $11.00).

Most people get this wrong. Claude without step-by-step reasoning gets this wrong. Claude with step-by-step reasoning — "Let x be the cost of the ball. The bat costs x + 10. Together they cost x + (x + 10) = 11, so 2x = 1, x = 0.50." — gets it right.

The technique does not require the phrase "think step by step." Any instruction that asks Claude to produce its reasoning before its conclusion has the same effect:

  • "Explain your reasoning before answering."
  • "Show your work."
  • "List the steps you are following."
  • "Walk through this one step at a time."

When to use it

Step-by-step reasoning helps with: multi-step math, logical deduction, code debugging, causal analysis, any task where a wrong intermediate step produces a confidently wrong final answer.

It does not help with: tasks where the answer is a single fact, creative writing, formatting tasks. Adding "think step by step" to "Write a haiku" just produces a haiku with a paragraph of preamble.

Asking Claude to think first, then answer

For high-stakes reasoning tasks, separate the thinking from the answer:

"Calculate the ROI on a $50,000 marketing spend that generated 1,200 leads and 45 conversions at $1,200 annual contract value. Show your calculations. Then state the ROI as a percentage in a single final line."

The last sentence separates the answer from the reasoning, which makes the output easier to scan.

If you get stuck

If step-by-step reasoning produces a wrong answer, the error is usually in one specific step. Identify which step went wrong and add a constraint for that step: "When calculating percentages, always use the base amount in the denominator."

If the reasoning is correct but the conclusion contradicts it, ask Claude to re-read its own reasoning: "Given the steps above, what is the correct answer?"

Cross-reference

L11 (Using examples) shows how to combine step-by-step reasoning with example patterns for classification tasks. L13 (Building complex prompts from scratch) covers how to structure multi-step tasks where each step feeds the next.

Deliverable

Take the ROI calculation prompt from this lesson. Fill in actual numbers from your work — a real campaign, a real budget, a real conversion rate. Run it with "Show your work." Check whether the answer is correct. If it is wrong, find the step where the error occurs and add a constraint.

Try these prompts

  • A bat and ball cost $11 total. The bat costs $10 more than the ball. How much does the ball cost? Think step by step.
  • Calculate the ROI on a $50K marketing spend that generated 1,200 leads and 45 conversions at $1,200 ACV. Show your work.

Back to contents

11. Using examples (few-shot) 7 min

Lesson notes

Instructions describe what you want. Examples show it. For most tasks involving classification, tone, structure, or style, examples communicate the target more precisely than any description.

This technique is called few-shot prompting. "Few-shot" means a small number of examples — typically two to five — provided before the actual task.

Why examples outperform instructions

Consider the instruction: "Write a warm but professional apology email." Every word in that instruction is ambiguous. What is warm? What is professional? How long? What tone markers indicate warmth without sacrificing professionalism?

Now consider providing an example:

Complaint: "My order arrived damaged."
Email: "We're sorry your order arrived in that condition — that is not the experience we want you to have. We have shipped a replacement and it should arrive within two business days. If there is anything else we can do, please reply to this email and we will take care of it."

The example answers every question the instruction left open: length (three sentences), tone (direct apology, no hedging, specific action), format (no subject line in the example, so the email starts immediately with the apology), and level of warmth ("that is not the experience we want you to have" is warm; "we have shipped" is professional).

The structure of a few-shot prompt

[Task instruction]

[Example input 1]
[Example output 1]

[Example input 2]
[Example output 2]

[Actual input]
[Leave this blank for Claude to fill in]

The actual input is at the bottom with no output. Claude fills in the output following the pattern established by the examples.

How many examples

Two examples establish a pattern. Five examples establish a pattern plus cover edge cases. More than five examples are rarely necessary and can make the prompt unwieldy.

Use at least one example per category in a classification task. If you are classifying sentiment as positive, neutral, or negative, include one example of each.

Choosing examples

Choose examples that represent the range of variation in your inputs, not just the easy cases. If some of your complaints are polite and some are aggressive, include both in the examples. If some of your documents are short and some are long, include both.

Examples that only cover the easy cases produce a model that handles easy cases well and fails on everything else.

If you get stuck

If Claude is following the pattern of your examples but the pattern is wrong, the examples need to be revised. The examples are the specification — if the output is wrong, the specification is wrong.

If Claude is ignoring your examples and producing something generic, the examples may be embedded in a way that makes them look like data rather than instructions. Separate them with clear labels: Example 1:, Output 1:.

Cross-reference

L10 (Precognition) and few-shot prompting combine well: provide examples that include step-by-step reasoning, and Claude will reason step by step on new inputs.

Deliverable

Pick a classification task from your work — categorizing support tickets, tagging content, classifying sentiment. Write a few-shot prompt with two to three examples. Run it on five real inputs. If the accuracy is lower than you expected, examine which cases failed and add an example that covers that failure mode.

Try these prompts

  • Convert these customer complaints into apology emails. Provide 2 examples, then do the third.
  • Classify the sentiment of these 3 product reviews as Positive, Neutral, or Negative.

Back to contents

AdvancedProduction-Grade Prompts

12. Avoiding hallucinations 8 min

Lesson notes

A hallucination is a confident, fluent, wrong answer. Claude does not know it is wrong. The answer is generated using the same mechanism as a correct answer — the model produces the most plausible-sounding next token given what it has already generated. If the training data does not contain the right answer, the model can still produce a plausible-sounding one.

You cannot prevent hallucinations entirely. You can prevent them from causing damage in the outputs you rely on.

Why hallucinations happen

Claude's training data contains a vast amount of text. For common topics — major historical events, well-documented scientific facts, widely published technical information — Claude's knowledge is reliable. For niche topics, recent events, private data, and anything that changes frequently (prices, regulations, personnel), Claude's knowledge is unreliable.

The pattern that creates the most damage: Claude knows something adjacent to what you asked, the adjacent knowledge is plausible in the context of your question, and Claude produces the adjacent knowledge as if it were the answer to your actual question. The answer sounds right because it is coherent and relevant. It is wrong because it is not about your specific situation.

Technique 1: Ground in context

Provide the source material in the prompt and instruct Claude to answer only from that material.

Answer the following question using only the text below.
If the answer is not in the text, say "I don't have that information in the provided text."

<text>
Acme Inc. was founded in 2010. The company has 47 full-time employees and operates in three markets: healthcare, finance, and logistics. Its headquarters are in Austin, Texas.
</text>

Question: What year was Acme Inc. founded, and what markets does it serve?

The instruction "using only the text below" is explicit. The fallback instruction "say 'I don't have that information'" gives Claude a path when the text does not contain the answer. Without the fallback, Claude may fill the gap with a plausible-sounding answer from its training data.

Technique 2: Ask for citations

When Claude answers from a provided text, ask it to cite the specific sentence that supports each claim.

"Cite the exact sentence from the provided text that supports each claim in your answer."

If Claude cannot cite a sentence, the claim is not in the text. This forces Claude to stay grounded and gives you a way to verify.

Technique 3: Encourage uncertainty

Add an explicit permission to say "I don't know":

"If you are uncertain about any part of the answer, say so explicitly. Do not guess."

Claude's default behavior leans toward confident answers. This instruction opens space for uncertainty.

Red flag patterns

When Claude says "As of my knowledge cutoff..." or "Based on my training data...", it is signaling that it is drawing on training knowledge rather than provided context. In a grounded prompt, this means Claude has left the text you provided. Ask it to answer only from the text you provided.

If you get stuck

If Claude is still producing information that is not in your source text, the source text may be too long for Claude to process accurately in a single prompt. Break it into sections and ask about each section separately.

If the citation technique produces citations that do not match what Claude said, the mismatch is the hallucination — Claude generated an answer, then found a plausible-sounding citation for it. Both the answer and the citation should be checked against the source.

Cross-reference

L19 (Search and retrieval) covers RAG — a system-level technique for automatically injecting relevant source documents into the prompt at query time, which extends grounding beyond what fits in a single prompt.

Deliverable

Take a question about a topic where Claude might hallucinate — a specific company, a recent event, a piece of internal data. Write a grounded prompt that provides the source text and instructs Claude to answer only from it, with a fallback for missing information. Verify that the answer is accurate against the source.

Further reading

Try these prompts

  • Answer using only the following text. If the answer isn't in the text, say "I don't have that information." Text: "Acme Inc. was founded in 2010 and has 47 employees."
  • Cite the specific sentence that supports your answer. What year was Acme founded?

Back to contents

13. Building complex prompts from scratch 10 min

Lesson notes

A production prompt is not a sentence. It is a small system: an input specification, a task definition, a set of constraints, an output format, and guardrails for the cases where the input does not match expectations. Building one from scratch is a skill you develop by doing it wrong several times, then doing it right.

This lesson gives you the sequence that produces a working prompt on the first try more often than not.

Step 1: Write the task in one sentence

Before you write any prompt, write one sentence that describes exactly what the prompt should do. Not what it should produce — what it should do.

"This prompt takes a customer complaint, assigns it a severity level (low/medium/high/critical), and drafts a response that addresses the complaint and explains the next step."

If you cannot write that sentence, you do not yet understand the task well enough to prompt for it.

Step 2: Specify the inputs

What does the prompt receive? Define the shape and format of the input. If the input is free text, define its expected range. If the input is structured (a JSON object, a form field), define the schema.

"Input: a customer complaint submitted via the support contact form. It may be one sentence or several paragraphs. It may reference an order number, a product name, or neither."

Step 3: Specify the outputs

What should the prompt produce? Define the format, the fields, and the success criterion for each.

"Output: a JSON object with three fields: severity (string: low/medium/high/critical), reasoning (one sentence explaining the severity), response (2–3 paragraph customer-facing reply)."

Step 4: Add examples

Provide one or two examples of input → output pairs. Cover the easy case and the hard case. The hard case is the one where the input is ambiguous or the classification is not obvious.

Step 5: Add guardrails

Guardrails handle inputs that fall outside the expected range. Every prompt that runs in production will eventually receive an input you did not anticipate. Define what the prompt should do in those cases.

"If the complaint is vague or does not contain enough information to classify severity, assign severity 'low' and include in the response a question that will help clarify the issue."

Step 6: Test on five inputs before shipping

Run the prompt on five real inputs from your actual data. Include at least one edge case: a very short complaint, a very long one, one with no identifying information, one with an angry tone, one with a technical question you cannot answer. See where it fails. Add constraints or examples for the failure modes.

If you get stuck

If the prompt works on simple inputs but fails on complex ones, the failure is usually in the output format specification. Complex inputs produce complex outputs, which may not fit a simple format. Add a format constraint that handles the complex case explicitly.

If the severity classification is inconsistent, the classification criteria are not specific enough. Replace the labels (low/medium/high/critical) with behavioral descriptions: "high: customer is unable to use the product due to the issue. medium: customer is significantly inconvenienced but can work around the issue."

Cross-reference

L11 (Using examples) covers how to write effective few-shot examples. L12 (Avoiding hallucinations) covers guardrails for knowledge-related failures. L14–16 apply this technique to real domain tasks.

Deliverable

Build a prompt following the six steps in this lesson. The prompt should take a short text input, perform a classification or extraction, and return structured JSON. Test it on five inputs and fix at least one failure mode before you consider it done.

Try these prompts

  • Build a prompt that takes a customer complaint, classifies severity, and drafts a response. Include guardrails for unclear inputs.
  • Write a prompt that extracts named entities, dates, and dollar amounts from a contract paragraph.

Back to contents

14. Industry use case - legal 25 min

Lesson notes

Project: Draft a limitation-of-liability clause

You are a legal assistant at a SaaS company. The company is revising its standard customer agreement and needs a limitation-of-liability clause that caps damages at the annual subscription value. The CEO wants to be able to read it. The company's attorney will review it before it goes into production.

What this project tests

This project tests whether you can write a prompt that produces a specific legal artifact — not a general explanation of what the clause should say, but the actual clause text — with the right structure, the right carve-outs, and the right level of language for a non-lawyer executive to read.

The gap between "explain what a limitation-of-liability clause is" and "draft one for this specific context" is exactly the gap between a general prompt and a production prompt.

Building the prompt

Start with the task in one sentence: "Draft a limitation-of-liability clause for a SaaS customer agreement."

Then add the specifics:

  • Damages cap: the annual subscription fee paid by the customer
  • Carve-outs: gross negligence, willful misconduct, indemnification obligations, and intellectual property infringement
  • Jurisdiction: Delaware
  • Language register: readable by a non-lawyer CEO, but legally valid
  • Length: no more than two paragraphs

Add a role: "You are a corporate attorney with experience drafting SaaS customer agreements."

Add a format constraint: "Produce the clause text only. No explanation of the clause. No preamble."

Iteration

Run your first draft. Then run a second pass with this prompt: "You are a skeptical corporate attorney reviewing this clause for ambiguity and loopholes. List every problem you see."

Use the critique to revise the clause. Run it again. Repeat until the skeptical attorney finds no problems or only minor ones.

The self-check

Read the clause out loud. If any sentence takes more than one reading to understand, it is too complex. Ask Claude to simplify that sentence without changing its legal meaning.

If you get stuck

If the clause is too generic (does not reference the subscription fee specifically), add the specific language: "The cap should be expressed as 'the total fees paid by Customer to Company in the twelve months preceding the claim.'"

If the carve-outs are missing or incomplete, list them explicitly in the prompt. Do not assume Claude knows which carve-outs are standard for SaaS agreements.

Deliverable

A two-paragraph limitation-of-liability clause, plus a one-sentence plain-English summary of what each paragraph does. The clause should pass the skeptical attorney review prompt with no major issues identified.

Try these prompts

  • Draft a limitation-of-liability clause that caps damages at the annual subscription value.
  • Write a plain-English NDA for a contractor working on a mobile app.
  • Summarize this lease agreement for a non-lawyer CEO in 3 bullets.

Back to contents

15. Industry use case - finance 25 min

Lesson notes

Project: Build an earnings call analysis prompt

You are an analyst who monitors five companies for a portfolio team. Every quarter, each company holds an earnings call. You need to extract the same set of data from every transcript: revenue, guidance, headcount changes, and product announcements. You also need a sentiment reading on each topic — is the executive team bullish, neutral, or bearish about each area?

The deliverable is a reusable prompt template you can apply to any transcript and get consistent, comparable output.

Why this is hard

Earnings call transcripts are long, unstructured, and full of hedged language. ("We remain cautiously optimistic about our trajectory in the second half, contingent on macroeconomic normalization...") The sentiment in that sentence is not bullish or bearish — it is a hedge. Your prompt has to handle hedged language, not just classify it as one of three labels.

Building the prompt

Step 1: Define the output schema.

{
  "company": "string",
  "quarter": "string",
  "metrics": {
    "revenue": {"value": "string", "vs_guidance": "string", "sentiment": "bullish|neutral|bearish|hedged"},
    "guidance_next_quarter": {"value": "string", "sentiment": "bullish|neutral|bearish|hedged"},
    "headcount": {"change": "string", "sentiment": "bullish|neutral|bearish|hedged"},
    "product_announcements": [{"name": "string", "description": "string", "sentiment": "bullish|neutral|bearish|hedged"}]
  },
  "risk_flags": ["string"],
  "overall_sentiment": "bullish|neutral|bearish|hedged"
}

Step 2: Write the extraction instruction.

"Extract the following fields from the earnings call transcript. For each field, classify the executive team's sentiment as bullish (confident, raised guidance, positive framing), bearish (cautious, missed targets, defensive language), neutral (on track, no change), or hedged (qualified language, contingent on external factors, both positive and negative framing)."

Step 3: Add the grounding instruction.

"Base your extraction only on statements made in the transcript. If a field is not mentioned, return null for that field. Do not infer or estimate."

Step 4: Add the delimiter.

Wrap the transcript in <transcript> tags.

Testing the prompt

Run the prompt on a real public transcript (any large public company's recent earnings call is available on their investor relations page). Check: Does the revenue figure match the announced number? Does the sentiment on guidance match what you heard when you read it? Are the risk flags real risks mentioned in the transcript or inferences?

If you get stuck

If the sentiment classifications are inconsistent between runs, add examples of each sentiment type with quotes from the transcript format: 'Revenue up 12% year over year' is bullish. 'We expect revenue growth to normalize in the second half' is hedged.

If the JSON is malformed, check that the transcript contains characters that break JSON strings (quotes inside strings, for example). Add: "Escape any quotation marks inside string values."

Deliverable

A reusable prompt template with the schema embedded. Test it on one real transcript and include the extracted JSON in your deliverable. The JSON should be valid (paste it into a validator) and the sentiment classifications should match what you observe when you read the transcript.

Try these prompts

  • Extract key metrics and sentiment from a Q3 earnings call transcript.
  • Build a prompt that converts a balance sheet into a JSON summary.
  • Write a prompt that flags risk factors in an investment memo.

Back to contents

16. Industry use case - coding 25 min

Lesson notes

Project: Refactor a function and write tests

You have a poorly written Python function. It works, but it has no type hints, no docstring, inconsistent naming, and no tests. Your job is to build a prompt that produces a clean, tested version — not just cleaner code, but code you would actually merge.

What this project tests

Code generation is one of the highest-stakes uses of Claude. A wrong answer in a legal clause gets flagged in review. A wrong answer in code may ship. This project tests whether you can write a prompt specific enough that the output requires minimal review.

The function to refactor

Use this as your starting point (or substitute one of your own):

def calc(items, d):
    t = 0
    for i in items:
        if i['qty'] > 0:
            p = i['price'] * i['qty']
            if d:
                p = p * (1 - d)
            t += p
    return t

Building the refactor prompt

Start with the role: "You are a senior Python engineer reviewing a pull request."

Add the task: "Refactor the following function to meet the requirements below."

List the requirements explicitly:

  • Add type hints to all parameters and the return value
  • Add a docstring following the Google docstring format
  • Rename variables to be descriptive (no single-letter names)
  • Add input validation: raise ValueError if items is empty, raise ValueError if discount is not between 0 and 1
  • Do not change the logic or the return value

Add the code in delimiters:

<code>
[function here]
</code>

Add the format constraint: "Return only the refactored function. No explanation."

Building the test prompt

After the refactor, run a second prompt: "Write three pytest unit tests for this function. Cover: the normal case (a list of items with a discount), the edge case (an empty list should raise ValueError), and the boundary case (a discount of exactly 0 and a discount of exactly 1)."

Checking the output

Copy the refactored function and the tests into a Python file and run pytest. If the tests pass, the prompt worked. If they fail, the error message tells you what went wrong — use it to refine the prompt.

If you get stuck

If the refactored function changes the logic, the refactor prompt needs a stronger constraint: "The function must produce the same output as the original for all valid inputs. Do not change the logic."

If the tests fail because the function raises an error the test did not expect, the test prompt needs to be more specific about the expected exception type and message.

Deliverable

The refactored function, the three tests, and the output of pytest showing all tests passing. If you cannot run Python locally, use Claude: paste the function and tests and ask Claude to simulate the test output.

Try these prompts

  • Refactor this Python function with type hints and docstrings.
  • Write 3 unit tests for a function that parses CSV dates.
  • Explain what this code does and identify potential bugs.

Back to contents

AppendixBeyond Standard Prompting

17. Chaining prompts 7 min

Lesson notes

A single prompt can do a surprising amount of work. A chain of prompts can do work that no single prompt can — because each step can be inspected, corrected, and verified before feeding into the next.

Prompt chaining is the technique of breaking a complex task into a sequence of simpler steps, where each step's output becomes the next step's input.

Why chain instead of doing it in one prompt

A single prompt that tries to extract claims, classify them, and draft a response simultaneously will sometimes get all three right and sometimes get one wrong in a way that corrupts the others. When it fails, you cannot tell which step failed. When you chain the steps, you see the output of each step. If step two is wrong, you fix step two without touching steps one and three.

The second reason is accuracy. Each step in a chain is a simpler task. Simpler tasks produce more accurate outputs. The chain of three accurate steps usually outperforms the single prompt trying to do all three at once.

The pattern

Step 1 prompt: extraction "Extract all claims from the following user review. Return them as a numbered list, one claim per line. A claim is any statement of fact or opinion about the product."

Step 2 prompt (receives the numbered list from Step 1): "Classify each of the following claims as 'factual' (can be verified), 'opinion' (subjective evaluation), or 'inflammatory' (language designed to provoke rather than inform). Return a JSON array where each item has 'claim' and 'type' fields."

Step 3 prompt (receives the JSON from Step 2): "Draft a response to the user review. Address only the factual claims. Acknowledge the opinions without agreeing or disagreeing. Do not respond to the inflammatory claims. Keep the response under 100 words."

What to inspect at each step

After Step 1: Are all claims present? Are there false positives (things classified as claims that are not claims)?

After Step 2: Are the classifications correct? This is where most chains fail — classification is harder than it looks, and the categories may overlap. If the classifications are wrong here, everything downstream is wrong.

After Step 3: Does the response address the right claims? Is the tone appropriate?

If you get stuck

If the chain produces the right output on most inputs but fails on some, identify which step fails on the difficult inputs. Fix that step in isolation before re-running the full chain.

If passing the output of one step into the next is creating format problems (the JSON from Step 2 is malformed when it becomes part of Step 3's prompt), add a format normalization step between them.

Cross-reference

L13 (Building complex prompts from scratch) covers single-prompt complexity. Chaining is the alternative when a single prompt becomes too complex to debug reliably.

Deliverable

Take a task from your work that involves at least two sequential operations — extract then classify, summarize then prioritize, analyze then recommend. Break it into a two-step chain. Run each step separately. Verify the output of step one before running step two. Note whether the chained version produces better output than a single prompt trying to do both.

Try these prompts

  • Step 1: Extract all claims from this user review. Step 2: Classify each as factual, opinion, or inflammatory.
  • Chain 3 prompts to turn a raw support ticket into a priority label, a suggested fix, and a customer reply.

Back to contents

18. Tool use primer 8 min

Lesson notes

Claude's training data has a cutoff. It cannot browse the web in real time. It cannot query a database. It cannot run code. It can, however, call external functions — if you define those functions and give it a way to invoke them.

This is tool use. It is the technique that powers most production Claude integrations that do something beyond text generation.

The concept

You define a set of tools — a calculator, a search function, a database query function. You give Claude the name and description of each tool. When Claude needs to use one, it produces a structured tool call — a function name and arguments — instead of answering directly. Your code intercepts the tool call, executes the actual function, and returns the result to Claude. Claude then uses the result to produce the final answer.

Claude does not execute the tool. Claude writes the instruction to execute the tool. Your code executes it.

A worked example

You want Claude to answer: "What is the total Q3 revenue for the North American segment?"

Without tool use, Claude either retrieves this from training data (unreliable for your specific company) or tells you it does not have access to that information.

With tool use:

  1. You define a tool: database_query(sql: string) -> string
  2. Claude produces: database_query("SELECT SUM(revenue) FROM sales WHERE quarter='Q3' AND region='North America'")
  3. Your code runs the query and returns: "12,450,000"
  4. Claude formats the final answer: "Q3 revenue for the North American segment was $12.45 million."

The answer is accurate because it came from the actual database. Claude's role was to write the right query and format the result — two things it does well.

Defining tools in a prompt

When you are prototyping tool use without building the infrastructure, define the tools in the prompt and ask Claude to simulate the call:

"You have access to the following tools:

  • calculator(expression: string) -> number: evaluates a mathematical expression and returns the result
  • search(query: string) -> string: searches the web and returns a summary of the top result

When you need to use a tool, write the tool call on its own line. I will provide the result. Then continue your answer."

This lets you test whether Claude produces the right tool calls before you build the execution layer.

If you get stuck

If Claude is trying to answer without using the tool, add: "You must use the tool to answer this question. Do not estimate or guess."

If Claude is producing tool calls with the wrong arguments, the tool description is not specific enough. Add a description of what valid arguments look like: "Expression must be a standard arithmetic expression using +, -, *, /. No functions."

Cross-reference

L19 (Search and retrieval) covers the specific case of search tools and how to use retrieved text as context. L17 (Chaining prompts) covers how to chain tool calls when one tool's output feeds into the next.

Deliverable

Define two tools in a prompt using the simulation technique from this lesson. Write a question that requires using both tools to answer. Run the prompt. For each tool call Claude produces, write the result it would receive, then continue the conversation until Claude produces the final answer.

Try these prompts

  • What is the total revenue for Q3? Use calculator(expression) if exact math is needed.
  • Look up the current weather in [city] using search(query) and summarize it in one sentence.

Back to contents

19. Search & retrieval 7 min

Lesson notes

Claude's training data ends at a fixed date. Your company's internal documentation was never in Claude's training data to begin with. Retrieval-Augmented Generation — RAG — is the pattern that bridges both gaps.

The idea is simple: instead of asking Claude to answer from memory, you find the relevant documents yourself and put them in the prompt. Claude answers from the documents. The answer is grounded in real text you control.

The pattern in four steps

Step 1: The user asks a question.

Step 2: Your system searches a knowledge base — a documentation site, a support ticket database, an internal wiki — and retrieves the top three to five most relevant chunks of text.

Step 3: You inject those chunks into the prompt as context, wrapped in delimiters.

Step 4: Claude reads the chunks and answers the question based on them.

The question Claude answers is about text you provided, not about what it learned during training. The answer is only as good as the retrieval step — if you retrieve the wrong chunks, Claude answers from the wrong context.

The prompt structure

Answer the following question using only the documents provided below.
If the answer is not in the provided documents, say "I don't have that information in the provided documents."
Do not use knowledge from outside the provided documents.

<document id="1">
[retrieved text chunk 1]
</document>

<document id="2">
[retrieved text chunk 2]
</document>

<document id="3">
[retrieved text chunk 3]
</document>

Question: [user's question]

The id attribute on each document tag is optional but useful — it allows Claude to cite which document supports each claim.

The fallback instruction

"If the answer is not in the provided documents, say 'I don't have that information.'" This instruction is required. Without it, Claude fills gaps with training knowledge, which defeats the purpose of grounding the answer.

Evaluating retrieval quality

The quality of the answer is bounded by the quality of retrieval. If Claude is producing wrong answers despite the grounding instruction, the retrieved chunks probably do not contain the relevant information. Check the retrieved chunks before Claude sees them. If the right information is not there, the retrieval step — not the prompt — needs to be fixed.

If you get stuck

If Claude is answering from its training data despite the grounding instruction, the instruction is probably buried at the end of the prompt. Move it to the top, before the documents.

If Claude is citing document IDs that do not match the claims it is making, it is hallucinating citations. Add: "Cite only documents that contain the exact information you are using. Do not cite a document unless you can quote the sentence that supports the claim."

Cross-reference

L12 (Avoiding hallucinations) covers the grounding technique used here. L18 (Tool use primer) covers search as a tool — the difference is that in tool use, the retrieval happens at query time during the conversation; in RAG, the retrieval happens in your system before the prompt is sent.

Deliverable

Find a short document from your work — a policy page, a support article, a product specification. Paste it into the prompt template from this lesson as a single document. Ask a question whose answer is in the document. Verify that Claude cites the document. Ask a second question whose answer is not in the document. Verify that Claude returns the fallback response rather than an answer from its training data.

Try these prompts

  • Answer using only the provided documents. If the answer isn't in the documents, say "I don't have that information."
  • Retrieve the top 3 relevant sections from a knowledge base about [topic], then summarize them in 2 bullets.

Back to contents