PrepStack › AI › Prompt Engineering
Prompt Engineering interview cheat sheet
Prompt anatomy, reasoning patterns, structured output, context and injection defence
Prompt engineering interviews are less about magic phrases and more about engineering discipline: can you write a clear spec for a model, pick the right technique (few-shot, chain-of-thought, chaining, structured output), keep cost and latency down, measure quality with evals, and defend against prompt injection? Read the 15-minute revision first. Then answer the Q&As out loud as if you were designing an LLM feature for production.
15-minute revision
- A good prompt is a spec: role, task, context, constraints, output format and examples. Ambiguity is the number one cause of bad output.
- System/developer messages set durable rules and persona; user messages carry the request. The system prompt is guidance, not a security boundary.
- Zero-shot first. Add few-shot examples when format or labelling is subtle. Examples are copied closely, so make them diverse, balanced and shuffled.
- Chain-of-thought helps multi-step reasoning on standard models. Reasoning models already think internally, so keep their prompts short and direct.
- Self-consistency samples several reasoning paths and takes a majority vote. Tree-of-thought searches over partial thoughts. Both trade cost for accuracy.
- ReAct interleaves Thought → Action (tool call) → Observation. It is the core loop of most agents.
- Prompt chaining splits a big task into small steps with checks in between. Easier to debug, test and cache than one mega-prompt.
- JSON mode guarantees valid JSON only. Structured outputs / JSON schema uses constrained decoding to guarantee the schema. Still validate business rules.
- Wrap inputs in delimiters or XML tags (
<document>,<example>) so the model can tell instructions from data. - Temperature near 0 for extraction, classification and code; higher for brainstorming and creative writing. Sampling settings are not a fix for a vague prompt.
- Context engineering: give only relevant, high-signal context. Put long documents first and the question last; models attend less to the middle.
- Prompt caching matches an exact prefix. Put static content (tools, system, examples) first and variable content (time, user query) last.
- Treat prompts like code: version them, run an eval set on every change, and track regressions. Never judge a prompt from one good output.
- Direct injection comes from the user; indirect injection hides in web pages, emails, files or tool results the model reads.
- No prompt fully stops injection. Defend in layers: isolate untrusted input, least-privilege tools, human approval, output filtering, dual-LLM designs.
- For RAG, tell the model to answer only from the given sources, cite them, and say “I don't know” when the answer is not there.
Prompt foundations
Anatomy of a good prompt
Write the prompt like a brief for a smart new colleague: who they are, what to do, with what, within which limits, and in what shape.
- Role: who the model should act as (“You are a senior tax accountant”). It sets vocabulary, depth and tone.
- Task: one clear verb and goal (“Classify”, “Summarise for an exec”, “Extract the fields below”). Say what success looks like.
- Context: the data, audience and purpose. The model knows nothing about your company, users or why the task matters unless you say so.
- Constraints: length, language, what to avoid, what to do when unsure. Say what to do rather than only what not to do.
- Output format: exact structure (JSON keys, headings, bullet count). If code will parse it, make it machine-checkable.
- Examples: one to five input/output pairs when the format or judgement is hard to describe in words.
- Order that works well: role and rules first, then long context, then the specific task and format reminder at the end.
Interview questions
- What makes a good prompt?
- Why do you explain the reason behind an instruction?
- Where should the actual question go in a long prompt?
System, developer & user prompts
System (or developer) messages hold durable rules and persona; user messages carry each request; assistant messages are prior model turns.
- Chat APIs take a list of messages with roles:
system(ordeveloperin newer OpenAI APIs),user,assistant, plus tool messages. - The system prompt sets persona, policies, output rules and tool-use guidance. It applies to every turn and models are trained to give it higher priority.
- The user prompt holds the actual request and per-request data. Keep it free of rules that should be constant.
- Assistant messages are past answers. You can also prefill them (some APIs) to steer format, e.g. start the reply with
{. - OpenAI documents an instruction hierarchy: platform rules > developer > user. Anthropic puts the system prompt in a separate
systemparameter. - The system prompt is not secret and not a security boundary. Assume users can extract it and can try to override it.
Interview questions
- Difference between a system prompt and a user prompt?
- Can a system prompt guarantee the model never does X?
- What is prefilling the assistant response?
Delimiters, XML tags, length & tone
Fence off every piece of input with clear tags, and state length, tone and audience explicitly instead of hoping.
- Delimiters (
""",###,---, XML tags) separate instructions from data and one document from another. - XML tags like
<document>,<instructions>,<example>work well with most models (Anthropic recommends them). Tag names are free; be consistent and refer to them by name. - Nest tags for structure:
<documents><document index="1"><source>..</source><content>..</content></document></documents>. - Ask for tagged output (
<answer>,<reasoning>) so code can extract parts with a simple parser. - Length: give a number (“3 bullets”, “under 120 words”). “Brief” and “detailed” mean different things to different readers.
- Tone and audience: name them (“friendly, for a non-technical customer”, “formal, for a legal team”). The style of your prompt also leaks into the answer.
Interview questions
- Why use XML tags or delimiters in prompts?
- How do you control output length reliably?
- Do delimiters prevent prompt injection?
Temperature & sampling per task
Low temperature for tasks with one right answer, higher for tasks that need variety; change temperature or top-p, not both.
- Temperature rescales token probabilities. 0 is (nearly) greedy and repeatable; higher values flatten the distribution and add variety.
- Top-p (nucleus) samples only from the smallest set of tokens whose probability adds up to p. Providers advise tuning temperature or top-p, not both.
- Even at temperature 0, outputs are not perfectly deterministic (batching and floating-point effects). Some APIs offer a
seedfor best-effort repeatability. - Max tokens caps output length and cost. Stop sequences end generation at a marker.
- Some reasoning models fix or ignore temperature and expose a reasoning effort setting instead.
- Sampling never fixes a vague prompt. Fix the instructions first, then tune sampling.
Interview questions
- What temperature would you use for a JSON extraction pipeline, and why?
- Difference between temperature and top-p?
- Why does temperature 0 still give different outputs sometimes?
Reasoning & decomposition techniques
Zero-shot vs few-shot prompting
Start zero-shot; add a few diverse, balanced, shuffled examples when the format or the judgement is hard to explain in words.
- Zero-shot: instructions only. Works well for common tasks on modern instruction-tuned models.
- Few-shot (in-context learning): add input→output examples. Best for custom formats, house style, tricky labels and edge cases.
- Selection: pick examples that are relevant to the input (semantic similarity), diverse, and cover each label and edge case.
- Ordering bias: models over-weight the last examples (recency) and the most common label (majority bias). Balance labels and shuffle.
- Examples are copied closely: length, tone, even mistakes. A typo in an example will show up in outputs.
- Wrap examples in
<example>tags and say they are illustrations, so the model does not treat them as part of the current task.
Interview questions
- Difference between zero-shot and few-shot prompting?
- How do you choose few-shot examples?
- What is ordering bias in few-shot prompts?
- When is few-shot a bad idea?
Chain-of-thought & reasoning models
Asking a standard model to reason step by step before answering improves multi-step tasks; reasoning models do this internally, so you mostly just state the goal.
- Chain-of-thought (CoT): the model writes intermediate steps before the final answer. Helps maths, logic, multi-hop questions and complex decisions.
- Zero-shot CoT: add “Think step by step”. Few-shot CoT: examples that include worked reasoning.
- Structured CoT: ask for reasoning in
<thinking>tags and the result in<answer>tags, so code can strip the reasoning. - CoT costs more tokens and latency. Skip it for simple lookups, classification or extraction.
- Reasoning models (OpenAI o-series and GPT-5 reasoning, Claude extended/adaptive thinking, Gemini thinking) reason internally. Give a clear goal and constraints; you rarely need step-by-step instructions.
- Written reasoning is not a faithful explanation of how the model decided. Don't treat it as an audit trail.
Interview questions
- What is chain-of-thought prompting and why does it work?
- When is chain-of-thought not needed or even harmful?
- How do you prompt a reasoning model differently?
- Is the chain-of-thought a faithful explanation of the model's decision?
Self-consistency & tree-of-thought
Self-consistency votes over several sampled reasoning paths; tree-of-thought explores and prunes partial thoughts like a search algorithm.
- Self-consistency: sample N chain-of-thought answers at temperature > 0, extract each final answer, take the majority vote.
- It works because wrong reasoning paths tend to disagree, while correct ones converge. Agreement rate is also a cheap confidence signal.
- Needs answers that can be compared (numbers, labels, short strings). For free text, use a judge model to pick the most consistent answer instead.
- Tree-of-thought (ToT): generate several candidate next steps, evaluate each (by the model or a heuristic), expand the best, and backtrack with BFS/DFS/beam search.
- ToT helps puzzles and planning where early choices matter. It costs many calls, so it is rare in production.
- Cheaper cousins: best-of-N with a verifier or reward model, and reflection (draft → critique → revise).
Interview questions
- What is self-consistency and when would you use it?
- Difference between chain-of-thought and tree-of-thought?
- How would you add a confidence score to an LLM classifier?
ReAct: reasoning + acting with tools
ReAct loops Thought → Action → Observation so the model can plan, call tools, read results and continue until it can answer.
- ReAct (Reason + Act) interleaves reasoning text with tool calls and feeds each tool result back as an observation.
- Grounding in real observations reduces hallucination compared with reasoning alone, and lets the model recover from bad steps.
- Modern APIs implement this with native function/tool calling: the model returns a structured tool call, your code runs it and sends back a tool result.
- The prompt must describe each tool clearly: name, purpose, when to use it, parameters. Tool descriptions are prompts too.
- Always add a step limit, timeouts and a stop condition, or the loop can run forever and burn tokens.
- Tool results are untrusted input and a main path for indirect prompt injection.
Interview questions
- What is the ReAct pattern?
- How is ReAct different from plain chain-of-thought?
- How do you stop a ReAct agent from looping forever?
Prompt chaining & task decomposition
Split a complex job into a pipeline of small, focused prompts with code checks between steps, instead of one giant prompt.
- Prompt chaining: the output of step 1 feeds step 2, and so on. Each prompt has one clear job.
- Benefits: each step is simpler, testable and debuggable; you can use a cheaper model for easy steps; and you can validate between steps.
- Common chains: extract → transform → write; draft → critique → revise; classify → route to a specialised prompt.
- Decomposition prompting asks the model to break a question into sub-questions first (least-to-most), then answer each.
- Parallelise independent steps (e.g. summarise 10 documents at once), then merge (map-reduce).
- Trade-off: more calls mean more latency and more points of failure. Use the fewest steps that make each one reliable.
Interview questions
- What is prompt chaining and why use it?
- When would you use one big prompt instead of a chain?
- Design question: summarise a 500-page PDF accurately.
Structured output, templates & context
Structured outputs: JSON mode vs JSON schema
JSON mode only promises syntactically valid JSON; schema-based structured outputs use constrained decoding so the reply matches your schema.
- Prompt-only JSON (“reply in JSON”) usually works but can add prose, code fences or trailing commas.
- JSON mode guarantees the output parses as JSON, but not which keys or types it has. You must still mention JSON in the prompt.
- Structured outputs / JSON schema (OpenAI
strictschemas, GeminiresponseSchema, similar features elsewhere) force output to match a schema via constrained decoding. - Older alternative: force a tool call whose input schema is the shape you want, then read the arguments.
- SDKs accept Pydantic (Python) or Zod (JS) models and give back parsed objects.
- The schema guarantees shape, not truth. Still handle refusals, truncation (
max_tokens), and validate business rules (dates in range, IDs exist). - Put a
reasoningornotesfield before the answer fields if you want the model to think first; fields are generated in order.
Interview questions
- Difference between JSON mode and structured outputs?
- If the schema is enforced, what can still go wrong?
- How did people get reliable JSON before structured outputs?
- Does field order in a schema matter?
Prompt templates & variables
Keep prompts as versioned templates with named variables, rendered in code, with missing variables treated as errors.
- A prompt template is static text plus placeholders (
{{ticket}},{question}) filled at runtime. - Store templates outside business logic (files, a prompt registry) and version them like code. Log which version produced each output.
- Fail loudly on missing variables; a silently empty
{{context}}produces confident nonsense. - Escape or wrap user-supplied values (tags, delimiters) so they cannot break the template structure.
- Keep the static part first and variables late so the prefix can be cached.
- Tools: Jinja2, f-strings, LangChain
PromptTemplate, provider prompt management features, or plain functions.
Interview questions
- Why manage prompts as templates instead of inline strings?
- How do you version and roll out a prompt change safely?
Context engineering: what, where and how much
Fill the context window with the smallest set of high-signal tokens: the right instructions, facts, examples, tools and history, in a deliberate order.
- Context engineering is the wider discipline around prompting: deciding everything the model sees per call (system prompt, retrieved docs, memory, tool definitions, history, examples).
- More is not better. Irrelevant text distracts the model and costs money; quality often drops as context grows (“context rot”).
- Lost in the middle: models use information at the start and end of long contexts better than the middle. Put key facts at the edges and the question last.
- Compression: summarise old chat turns, trim tool outputs to the needed fields, deduplicate retrieved chunks, drop low-relevance chunks.
- Just-in-time context: give the agent tools to fetch details when needed (file paths, search) instead of pre-loading everything.
- Label every block with its source and trust level, so the model and your defences know what is untrusted.
Interview questions
- What is context engineering and how is it different from prompt engineering?
- What is the “lost in the middle” problem?
- A long-running chat assistant starts forgetting rules and getting slow. What do you do?
Prompt caching-friendly structure
Provider caches reuse the processed state of an identical prompt prefix, so put static content first and anything that changes last.
- Prompt caching stores the model's processed state (KV cache) for a prompt prefix. A later request with the exact same prefix skips that work: lower latency and cheaper input tokens.
- It is prefix-based: one changed character invalidates everything after it. Order: tools → system prompt → examples → long documents → conversation → new user message.
- OpenAI caches long prefixes automatically (minimum around 1,024 tokens). Anthropic uses
cache_controlbreakpoints (or automatic mode); default TTL is 5 minutes, with a paid 1-hour option. - Anthropic bills cache writes at a premium (1.25× base input for 5-minute TTL) and cache reads at about 0.1×. Check current pricing per provider.
- Cache killers: timestamps or request IDs at the top, shuffling tools or examples per request, per-user data in the system prompt, changing tool definitions.
- Track hit rate with usage fields (
cached_tokens,cache_read_input_tokens).
Interview questions
- How does prompt caching work and how do you design for it?
- Difference between prompt caching and response (semantic) caching?
- Your cache hit rate is near zero. What do you check?
Evaluation & security
Evaluating prompts, iteration & failure modes
Treat a prompt as code under test: build an eval set, measure every change, read the failures, and fix the root cause, not the symptom.
- Start with success criteria (accuracy, format validity, tone, latency, cost), then build an eval set of real and edge-case inputs with expected outputs or rubrics.
- Graders: exact match / code checks (best when possible), similarity metrics, LLM-as-judge with a rubric, and human review for a sample.
- Iterate in a loop: run evals → read failures → change one thing → re-run. Watch for regressions on cases that used to pass.
- Run each case several times if temperature > 0; one lucky output proves nothing.
- LLM judges have biases (position, verbosity, self-preference). Calibrate them against human labels.
- Common failure modes: ambiguity, conflicting instructions, over-constraining, hidden assumptions, too much context, examples that are copied too literally, and format drift.
Interview questions
- How do you evaluate a prompt?
- What is LLM-as-a-judge and what are its pitfalls?
- What does over-constraining a prompt look like?
- Your prompt works in testing but fails in production. Why might that be?
Prompt injection & jailbreaks
Prompt injection is untrusted text being treated as instructions; it comes directly from users or indirectly from content the model reads, and it is OWASP's top LLM risk.
- Root cause: LLMs receive instructions and data in the same token stream, so they cannot reliably tell them apart.
- Direct injection: the user types it (“Ignore previous instructions and…”).
- Indirect injection: hidden in content the model processes: web pages, emails, PDFs, code comments, tool results, images, even invisible Unicode. The victim never sees it.
- Jailbreaks are injections that aim to bypass safety rules: role-play personas, hypotheticals, many-shot examples, obfuscation (base64, other languages), multi-turn escalation.
- Impact depends on agency: a chatbot leaks text, but an agent with email, browsing or code tools can exfiltrate data or take actions.
- Classic exfiltration path: injected text makes the model render a markdown image or link whose URL contains private data.
Interview questions
- What is prompt injection?
- Difference between direct and indirect prompt injection?
- Difference between prompt injection and a jailbreak?
- Give an example of a real indirect injection risk.
Defences & system prompt leakage
No prompt fully stops injection, so design for containment: isolate untrusted input, give minimal privileges, check outputs, and keep humans on risky actions.
- Input isolation (spotlighting): wrap untrusted text in tags, mark it as data, escape tag characters, or datamark/encode it so the model can tell it apart.
- Least privilege: give tools the narrowest scope (read-only, per-user tokens, allow-listed domains). Enforce permissions in code, not in the prompt.
- Human-in-the-loop for high-impact actions: sending, paying, deleting, sharing.
- Output filtering: validate format, block unexpected URLs/markdown images, scan for secrets and PII, check tool-call arguments.
- Dual-LLM / quarantine pattern: a privileged model plans and calls tools but never sees raw untrusted text; a quarantined model reads untrusted text but has no tools. (Ideas extended in Google DeepMind's CaMeL.)
- System prompt leakage (OWASP LLM07): assume the prompt will be extracted. Keep secrets, credentials and access logic out of it; a canary token helps detect leaks.
- Also: injection classifiers, rate limits, logging, red-teaming, and keeping the model's “blast radius” small.
Interview questions
- How do you defend an LLM app against prompt injection?
- What is the dual-LLM pattern?
- How would you protect a system prompt from leaking?
- Your agent can browse the web and send email. What controls do you add?
Applied prompting
Prompting for code
Give the model the same things a developer needs: language and versions, existing code and conventions, exact requirements, tests, and the expected output shape.
- State language, framework and versions (“Python 3.12, FastAPI, Pydantic v2”). APIs change between versions.
- Paste relevant existing code, interfaces and style rules; ask the model to follow existing patterns.
- Be precise about inputs, outputs, edge cases and errors. Include a failing test or a sample input/output.
- Ask for the output shape: a unified diff, only the changed function, or full file; no commentary if code is parsed.
- For bigger changes: ask for a plan first, review it, then implement step by step (chaining).
- Verify by running the code and tests; feed errors back. Watch for hallucinated packages and APIs.
Interview questions
- How do you prompt an LLM to write reliable code?
- What are common failure modes of code generation?
Prompting for RAG: grounding, citations, “I don't know”
Tell the model to answer only from the supplied sources, cite them, and abstain when they don't contain the answer; then verify citations in code.
- Put retrieved chunks in tagged, numbered blocks with source metadata (title, URL, date).
- Instruct: answer only from the sources; cite with markers like
[1]; if the sources do not contain the answer, reply with a fixed fallback phrase. - Giving explicit permission to say “I don't know” is one of the biggest hallucination reducers.
- Ask the model to quote the relevant passage first for hard questions, then answer from the quotes.
- Handle conflicting sources: prefer the newest or most authoritative, or report the conflict.
- Verify in code: citations point to real chunks, quotes appear in the source text, and the fallback is used correctly. Retrieved chunks are also an indirect injection path.
Interview questions
- How do you reduce hallucinations in a RAG system through prompting?
- Why give the model explicit permission to say “I don't know”?
- How do you evaluate a RAG prompt?
Meta-prompting & automatic optimisation (DSPy)
Use models to write and improve prompts, or use frameworks like DSPy that compile declarative task specs into optimised prompts against a metric.
- Meta-prompting: ask a strong model to draft or critique a prompt for a task (“Here is the task and 5 failures; rewrite the prompt”). Many provider consoles have prompt generators/improvers.
- Automatic prompt optimisation (APO): search over instructions and examples, scoring each candidate on an eval set (e.g. APE, OPRO, GEPA).
- DSPy (Stanford NLP): you declare signatures (
question -> answer) and modules (Predict,ChainOfThought,ReAct); DSPy builds the prompts. - DSPy optimizers (e.g.
BootstrapFewShot,MIPROv2,GEPA) tune instructions and few-shot demos to maximise your metric on a training set. - Benefit: prompts become reproducible artefacts you can re-optimise when you switch models.
- All of this needs a good metric and eval data. Without them you are optimising noise or overfitting a tiny set.
Interview questions
- What is meta-prompting?
- What is DSPy and how is it different from hand-written prompts?
- What do you need before automatic prompt optimisation is worth it?
Multimodal prompting
Images, audio and documents are just more context: place them deliberately, tell the model what to look at, and remember they can carry injections too.
- Vision models accept images (and often PDFs, audio, video) as content parts next to text in the same message.
- Put the image before the question in most cases, and refer to images by label when there are several (“Image 1: invoice, Image 2: receipt”).
- Be specific about what to inspect: region, fields, units. Ask the model to describe what it sees before reasoning for hard visual tasks.
- Combine with structured outputs for document extraction (invoices, forms, charts).
- Limits: small text, counting, precise spatial positions and dense charts are error-prone. Resolution and image tokens affect both cost and accuracy.
- Cross-modal injection: instructions can hide in images (tiny or low-contrast text) or audio. Treat media from users and the web as untrusted.
Interview questions
- How do you prompt a vision model well?
- What new security risks come with multimodal input?