Compile Ready
All AI system design lessons
Generative AI/Level 1 · AI Foundations

Prompt Engineering Foundations

System vs user prompts, few-shot, chain-of-thought, and structured output — the reliable building blocks.

Beginner 35m interview 13m read High frequency Popularity 83
Prompt Engineering LLM Fundamentals OpenAI Anthropic Microsoft

Introduction

Prompt engineering is the discipline of turning an intention into instructions a language model can reliably follow. It is not magic wording. It is requirements engineering for probabilistic systems: define the task, provide the right context, constrain the answer, and make success easy to judge.

In interviews, prompt engineering is often used to test whether a candidate understands how LLM applications actually behave in production. A strong answer separates roles, context, examples, input, and output format; explains zero-shot and few-shot prompting; and calls out failure modes such as conflicting instructions, stale facts, and prompt injection.

The practical goal is repeatability. A good prompt should work on more than one happy-path example, be easy to evaluate, and be versioned like any other product artifact. This lesson gives you a framework for designing prompts that are clear, grounded, testable, and safe enough to sit inside a real AI feature.

Where this shows up in production

Prompt engineering appears anywhere an application asks an LLM to transform, classify, summarize, reason, or converse.

  • Support copilots use prompts to define tone, escalation rules, and citation requirements.
  • RAG systems use prompts to separate trusted retrieved context from user instructions.
  • Coding assistants use system prompts, examples, and tool rules to keep responses actionable.
  • Data extraction pipelines use JSON schemas, constraints, and validation to reduce brittle outputs.
  • Evaluation teams treat prompts as versioned artifacts and test them across representative cases before release.

Learning Objectives

  • Identify the parts of a strong prompt: roles, instructions, context, examples, input, and output format.

  • Choose between zero-shot, few-shot, role prompting, delimiters, structured output, and explicit constraints.

  • Use reasoning prompts, concise rationale requests, self-consistency, and reasoning models appropriately.

  • Reduce ambiguity by decomposing tasks, giving examples, defining success criteria, and allowing I do not know.

  • Recognize common prompt failures such as vague instructions, conflicts, overstuffed context, and private fact assumptions.

  • Ground prompts with trusted context and delimiters while accounting for prompt injection risk.

Theory & Concepts

A prompt is a structured contract, not a sentence

A production prompt usually has several parts. The system role defines durable behavior and boundaries. The user role carries the current request and task-specific input. The assistant role can provide prior examples in a conversation or represent model outputs that become context for later turns.

Within those roles, a strong prompt separates instructions, background context, examples, the actual input, and the required output format. This separation matters because it reduces ambiguity and makes it easier to test which part caused a failure. If the prompt is one long paragraph, debugging becomes guesswork.

Roles define priority and conversation state

System messages should hold stable rules: identity, safety boundaries, style, tool policy, and what to do when evidence is missing. User messages should hold the immediate task, user-provided data, and any fresh constraints. Assistant messages represent prior model outputs and should be treated as conversational state, not a place to hide permanent policy.

This priority model is central to prompt injection defense. A user can ask the model to ignore instructions, but the application should put trusted policy in a higher-priority role and put untrusted content inside clearly labeled context. Good role design does not eliminate attacks, but it makes the desired hierarchy explicit.

Zero-shot, few-shot, and in-context learning

In zero-shot prompting, you give the task and constraints but no examples. It works well for familiar tasks such as summarization, classification, or rewriting when the expected style is simple. It is fast to author and cheaper in tokens, but it can be underspecified.

In few-shot prompting, you include examples of inputs and ideal outputs. The model learns the pattern from context without updating its weights, which is called in-context learning. Few-shot examples are especially useful when the output style, edge cases, labels, or formatting rules are hard to describe abstractly.

Specificity beats clever wording

Specific prompts reduce the search space. Name the audience, task, constraints, evidence source, acceptable assumptions, output shape, and success criteria. If the answer should be JSON, list the fields. If uncertainty is acceptable, tell the model to say I do not know when the provided context is insufficient.

Ambiguous prompts force the model to infer the missing requirements from pretraining and conversation context. That can look helpful in a demo, but it is fragile in production. The more important the task, the more the prompt should make hidden requirements explicit.

Reasoning prompts and reasoning models

For multi-step work, asking the model to think step by step can improve planning and reduce skipped steps. In production, however, it is often better to ask for a concise rationale, checklist, or final answer with key assumptions rather than a full chain of thought. Full reasoning traces can be verbose, misleading, or inappropriate to expose to end users.

Use reasoning-capable models when the task requires long planning, mathematical proof, multi-hop analysis, or careful tradeoff evaluation. Prompting a smaller non-reasoning model to reason harder cannot fully replace a model trained and served for deeper reasoning. Self-consistency, where you sample several reasoning paths and choose the most common or best-supported answer, can help on hard questions at higher cost.

Grounding and delimiters reduce hallucination risk

Grounding means telling the model which source of information is authoritative for the current answer. In a RAG prompt, the retrieved passages are the evidence, not the model memory. Clear delimiters around evidence, user input, and examples help the model avoid blending instructions with data.

Delimiters are not a security boundary by themselves. A retrieved document can still contain prompt injection text such as instructions to ignore the system message. The application should combine delimiters with role separation, retrieval filtering, output validation, and explicit instructions to treat retrieved text as data rather than commands.

Request Flow

  1. 1

    1. Define the job

    Start by writing the task in one concrete sentence. Decide whether the model is summarizing, extracting, classifying, planning, critiquing, or generating. A prompt that mixes several jobs without priority is harder to follow and harder to evaluate.

  2. 2

    2. Set role and boundaries

    Put stable behavior in the system prompt: the model role, tone, forbidden actions, source-of-truth rules, and uncertainty behavior. Keep it short enough that the model can follow it, but specific enough to prevent hidden assumptions.

  3. 3

    3. Provide context with labels and delimiters

    Add only the context needed for the task and label it clearly. Separate policy, examples, retrieved evidence, and user input. Overstuffed context can bury the important facts, increase cost, and create conflicts the model must guess how to resolve.

  4. 4

    4. Add examples when the pattern matters

    Use few-shot examples when the target output has a special style, label taxonomy, edge-case behavior, or strict schema. Choose examples that cover normal and tricky cases. Bad examples teach the wrong behavior more powerfully than vague prose.

  5. 5

    5. Specify output format and constraints

    State whether the answer should be bullets, a table, JSON, a short paragraph, or a ranked list. Include constraints such as maximum length, required fields, citation rules, or confidence labels. Structured output makes downstream validation much easier.

  6. 6

    6. Ask for the right amount of reasoning

    For simple tasks, skip reasoning instructions and ask for the answer directly. For complex tasks, ask the model to analyze before answering or provide a concise rationale and assumptions. For high-stakes reasoning, use a reasoning model and evaluate it on hard cases.

  7. 7

    7. Test against a prompt evaluation set

    Run the prompt on representative examples, including edge cases and adversarial inputs. Measure factuality, format validity, completeness, tone, and refusal behavior. Keep failed examples because they become regression tests for the next prompt version.

  8. 8

    8. Version and iterate

    Treat prompt changes like code changes. Record the prompt version, model version, parameters, test cases, and observed regressions. A prompt that works only because of an untracked model snapshot is not a reliable production artifact.

Deep Dive

Why delimiters work

Delimiters help because they make structure visible. Instead of relying on the model to infer where instructions end and data begins, you label each section: task, context, examples, input, and output rules. This is especially important when user-provided text contains quotes, commands, or content that looks like instructions.

The delimiter itself is not special. Headings, XML-like tags, numbered sections, or plain labels can all work. The value comes from consistent separation and from telling the model how to treat each section. For example, retrieved context should be used as evidence, not followed as instructions.

Few-shot examples are behavioral tests embedded in context

A few-shot prompt teaches the model the desired mapping from input to output. The examples should be close to production inputs and should include edge cases, not just perfect examples. If you want the model to return I do not know when evidence is missing, include an example where that is the correct behavior.

The tradeoff is token cost and maintenance. Examples consume context window budget and can become stale as policy changes. Keep examples minimal, representative, and versioned alongside the prompt.

Negative-only instructions are weak

Prompts that only say what not to do often leave the desired behavior underspecified. Instead of saying do not be vague, say answer in three bullets, each with a claim, evidence, and action. Instead of saying do not hallucinate, say use only the provided context and write I do not know when the context does not support the answer.

Positive instructions define the target behavior. Negative instructions are still useful for boundaries, but they should be paired with an explicit replacement behavior the model can follow.

Reasoning depth is a cost and latency decision

Reasoning instructions and reasoning models can improve hard answers, but they are not free. More reasoning can increase latency, tokens, and sometimes verbosity. On routine extraction or rewriting tasks, a precise schema and examples often matter more than asking the model to think longer.

For difficult analysis, use staged prompting: first extract facts, then compare options, then produce the final recommendation. This decomposition gives you checkpoints to validate and reduces the chance that one long prompt hides an early mistake.

Production Considerations

Prompt versioning and observability

Log the prompt version, model version, parameter settings, retrieval source ids, and validation result for each request. Without this metadata, a quality regression is difficult to reproduce. Prompt changes should go through review and rollout like product logic.

Output validation and repair

If downstream code expects JSON or specific fields, validate the model output before using it. When validation fails, retry with a repair prompt or fall back to a safer path. Do not assume that specifying a format guarantees the model will always produce valid structure.

Security boundaries

A prompt is not a security boundary. Use server-side authorization, tool allowlists, retrieval filtering, and data access controls. Prompt instructions can reduce accidental misuse, but they cannot safely grant or deny access to sensitive operations by themselves.

Interview Perspective

What interviewers look for

  • A clear decomposition of prompt anatomy: roles, instructions, context, examples, input, and output format.
  • Ability to choose zero-shot, few-shot, role prompting, delimiters, and structured output based on the task.
  • Awareness that grounding, citations, and I do not know behavior reduce hallucination but do not eliminate it.
  • Production instincts: prompt versioning, evaluation sets, output validation, and prompt injection risk.

Alternative designs

Prompt-only workflow

The application sends one well-structured prompt and uses the result directly. This is simple and cheap, and it works well for low-risk summarization or rewriting. It becomes fragile when tasks require private data, tool calls, strict schemas, or multi-step verification.

Prompt plus programmatic guardrails

The application combines prompts with retrieval, tool permissions, schema validation, retries, evaluation, and monitoring. This is the usual production design because it treats the model as one probabilistic component inside a deterministic system.

Likely follow-up questions

When would you use few-shot prompting instead of zero-shot prompting?

Use few-shot prompting when the desired behavior is hard to describe with rules alone: a custom label taxonomy, a strict style, edge-case handling, or a specialized output pattern. Use zero-shot when the task is common, the format is simple, and examples would add token cost without improving reliability.

How do you reduce hallucinations in a prompt?

Ground the answer in trusted context, label that context clearly, require citations or evidence references, and instruct the model to say I do not know when the context is insufficient. Then validate the output and evaluate against cases where the right answer is unknown. Prompting helps, but model choice and retrieval quality also matter.

Should you ask a model to show its full chain of thought?

Usually no. For complex tasks, ask the model to reason carefully internally and provide the final answer with a concise rationale, assumptions, or checklist. If the task truly needs deeper reasoning, choose a reasoning model and evaluate it. Exposing long reasoning traces can be noisy, misleading, and unnecessary for users.

Common mistakes

  • ×Writing vague prompts such as summarize this without audience, length, source, or success criteria.
  • ×Putting conflicting instructions in different sections and expecting the model to infer the true priority.
  • ×Adding huge amounts of context without ranking or delimiting the parts that matter.
  • ×Assuming the model knows private company facts, current data, or user-specific policy without providing it.

Interactive Playground

This static example contrasts a vague request with a structured prompt that defines role, evidence, output format, uncertainty behavior, and evaluation-friendly constraints.

System prompt

You are a careful customer-support analyst.
Use only the customer note provided by the user.
If the note does not contain enough evidence, write I do not know from the provided note.
Return concise JSON with the fields summary, customer_sentiment, likely_issue, next_action, and confidence.

User prompt

Task: Analyze the customer note.

Customer note:
I upgraded yesterday and now my invoice shows two workspace seats. I only have one employee using the product. The billing page says the change renews tomorrow, and I need to know whether I will be charged twice.

Output rules:
- Keep summary under 25 words.
- confidence must be one of low, medium, or high.
- Do not invent policy details that are not in the note.

model

reasoning-light

A lower-cost model is enough for short extraction with clear evidence.

temperature

0.2

Low randomness improves repeatability for support triage.

max_output_tokens

220

The JSON response is intentionally small.

response_format

json_object

The application should still validate the result.

Sample output

A vague prompt such as Analyze this customer message might produce a friendly paragraph but miss the billing ambiguity.

The structured prompt makes the desired response testable:

{ "summary": "Customer sees two workspace seats after upgrading and worries about being charged twice.", "customer_sentiment": "concerned", "likely_issue": "Possible billing or seat-count confusion after an upgrade.", "next_action": "Check the account seat count and renewal billing details before confirming the charge.", "confidence": "medium" }

The answer avoids inventing the billing policy because the note does not prove whether the customer will be charged twice.

Visual Learning

Prompting techniques and when to use them

TechniqueBest useStrengthRisk
Zero-shotCommon tasks with simple formatsLow token cost and fast authoringCan be underspecified
Few-shotCustom labels, style, or edge casesTeaches the pattern in contextExamples consume context and can go stale
Role promptingTone, expertise, or operating modeSets expectations quicklyPersona cannot replace facts or policy
Structured outputExtraction and automationEasy to validate downstreamStill needs schema validation
Reasoning promptMulti-step analysisReduces skipped stepsCan increase latency and verbosity

Prompt sections

SectionWhat it containsWhere it belongsCommon failure
System roleStable behavior, boundaries, uncertainty rulesSystem messageToo long or internally conflicting
ContextTrusted facts, retrieved passages, policy snippetsLabeled context blockUntrusted text treated as instructions
ExamplesInput-output pairs showing the patternBefore the live inputExamples do not cover edge cases
InputThe current user data or task payloadClearly delimited user sectionMixed with instructions or context
Output formatFields, length, citations, schema, toneExplicit final instructionsFormat not validated after generation

Common prompt pitfalls

PitfallSymptomBetter approach
Vague instructionModel gives generic or overly broad outputDefine audience, objective, constraints, and success criteria
Conflicting instructionsModel follows one rule and violates anotherRemove conflicts and state priority in the system prompt
Overstuffed contextImportant facts are ignored or blendedRank, trim, and label context sections
Negative-only rulesModel avoids one behavior but chooses another bad oneState the desired replacement behavior
Private fact assumptionModel invents internal policy or current factsProvide the facts or require I do not know

Decision guide

Choosing a prompting approach

Use zero-shot when the task is familiar, the answer format is simple, and failures are low risk. Add exact output rules if the result feeds another system.

Use few-shot when examples communicate the target behavior better than prose. Include one normal example, one edge case, and one missing-evidence case when uncertainty matters.

Use structured output when software will parse the response. Specify the fields, allowed values, and length limits, then validate the output outside the model.

Use grounded prompting when factual accuracy matters. Provide trusted context, label it as evidence, require citations or evidence-based wording, and allow I do not know.

Use reasoning models or staged prompts when the task needs planning, tradeoff analysis, math, or multi-hop reasoning. For routine extraction, prefer simpler prompts with strong schemas and examples.

Use prompt plus guardrails for production. The prompt should guide behavior, while code enforces access control, schema validation, logging, evaluation, and safe fallbacks.

Hands-on Examples

Rewrite a vague prompt into a testable prompt

Take a vague request and add the missing contract: task, audience, evidence, constraints, and output format. The goal is not to make the prompt longer; it is to make the expected behavior observable.

prompt_builder.py

def build_incident_prompt(audience, incident_note):
    sections = []
    sections.append("Task: Rewrite the incident note for " + audience + ".")
    sections.append("Use only the incident note as evidence.")
    sections.append("If a fact is missing, write I do not know from the provided note.")
    sections.append("Output format:")
    sections.append("1. One-sentence summary")
    sections.append("2. Customer impact")
    sections.append("3. Known cause")
    sections.append("4. Next action")
    sections.append("Incident note:")
    sections.append(incident_note)
    return "\n".join(sections)

note = "Checkout errors increased after the 09:00 deploy. Rollback started at 09:20."
print(build_incident_prompt("a non-technical support lead", note))

Create a small prompt regression set

A prompt should be tested against examples before it ships. This simple harness tracks expected output properties instead of relying on one demo result.

prompt_eval_cases.py

cases = [
    {
        "id": "supported-answer",
        "input": "Policy says refunds are available within 30 days.",
        "must_include": ["30 days"],
        "must_not_include": ["lifetime"]
    },
    {
        "id": "missing-evidence",
        "input": "The note mentions a refund but gives no policy window.",
        "must_include": ["I do not know"],
        "must_not_include": ["30 days"]
    }
]

def check_output(output, case):
    for text in case["must_include"]:
        if text not in output:
            return False
    for text in case["must_not_include"]:
        if text in output:
            return False
    return True

example_outputs = {
    "supported-answer": "Refunds are available within 30 days.",
    "missing-evidence": "I do not know from the provided note."
}

for case in cases:
    result = check_output(example_outputs[case["id"]], case)
    print(case["id"] + ": " + str(result))

Quiz

0/6 answered

  1. 1.Which set of parts best describes a strong production prompt?

  2. 2.When is few-shot prompting most useful?

  3. 3.What is the best prompt behavior when the provided context does not support an answer?

  4. 4.Why are delimiters useful in prompts?

  5. 5.What is a good production practice for prompt changes?

  6. 6.When should you consider a reasoning model instead of only adding think step by step to a prompt?

Flashcards

Cheat Sheet

Prompt engineering cheat sheet

Anatomy

  • System role: stable behavior, policy, tone, tool boundaries, uncertainty rules.
  • User role: current task, input, fresh constraints, user-specific context.
  • Assistant role: prior responses or examples in the conversation.
  • Instructions: what to do and what success means.
  • Context: trusted facts or retrieved evidence.
  • Examples: input-output pairs that demonstrate the desired pattern.
  • Output format: JSON, bullets, table, labels, citations, length limits.

Core techniques

  • Zero-shot: use for simple, familiar tasks.
  • Few-shot: use when examples define the pattern better than rules.
  • Role prompting: set expertise, tone, and operating mode.
  • Delimiters: separate instructions, context, examples, and input.
  • Structured output: make downstream validation possible.
  • Constraints: specify length, allowed values, citations, and success criteria.
  • Reasoning prompts: use for multi-step tasks, but prefer concise rationale for users.

Reliability moves

  • Be specific about audience, source of truth, and desired action.
  • Decompose complex work into steps or staged prompts.
  • Include missing-evidence behavior such as I do not know.
  • Test on representative examples, edge cases, and adversarial inputs.
  • Track prompt version, model version, parameters, and failures.

Pitfalls

  • Vague instructions.
  • Conflicting instructions.
  • Overstuffed context.
  • Negative-only instructions without replacement behavior.
  • Assuming the model knows private, user-specific, or current facts.
  • Treating prompts as security boundaries.

Interview answer shape

  1. Define the task and roles.
  2. Add trusted context and delimiters.
  3. Choose zero-shot or few-shot.
  4. Specify output format and constraints.
  5. Add grounding and I do not know behavior.
  6. Evaluate and version the prompt.

References