Prompting, context and structured output
Part 3: Prompting and Context
Prompt patterns, JSON schema, function calling, injection defence, context engineering.
On this page (29 sections)
- 3.1 Prompt basics
- 3.2 Output control and tools
- 3.3 Safety and context engineering
- 3.4 Memory and prompt operations
- 3.1 Prompt basics — detailed notes
- 1. Prompt anatomy: role, task, context and format
- 2. System vs user vs developer prompts
- 3. Zero-shot, one-shot and few-shot prompting
- 4. Chain-of-thought, step-by-step and ReAct
- 5. Prompt patterns: persona, templates, delimiters and XML tags
- 3.2 Output control and tools — detailed notes
- 6. Positive and negative examples
- 7. Structured output: JSON mode and JSON Schema
- 8. Function calling / tool calling
- 9. Prompt chaining, routing and parallelisation
- 10. Self-consistency, reflection and critique-and-revise
- 3.3 Safety and context engineering — detailed notes
- 11. Prompt injection and jailbreaks
- 12. Defending against prompt injection
- 13. Context engineering
- 14. Long-context management: summarisation, truncation and compaction
- 15. Prompt caching and cost savings
- 3.4 Memory and prompt operations — detailed notes
- 16. Conversation memory: short-term vs long-term
- 17. Prompt versioning, templates and management tools
- 18. Prompt iteration and golden sets
- 19. Common prompting mistakes and fixes
- 20. Meta-prompting and AI-written prompts
- Part 3 cheat sheet — interview answers
Like I'm 5: Asking the model is like giving instructions to a very smart new joiner. Clear instructions, a few examples and the right papers on the desk give good work.
3.1 Prompt basics
Topics to cover, in this order:
- What is a prompt: anatomy (role, task, context, format)
- System vs user vs developer prompts
- Zero-shot, one-shot and few-shot prompting
- Chain-of-thought, step-by-step and ReAct
- Prompt patterns: persona, templates, delimiters, XML tags
3.2 Output control and tools
Topics to cover, in this order:
- Examples and negative examples
- Structured output: JSON mode, JSON schema
- Function calling / tool calling: how it works
- Prompt chaining, routing and parallelization (workflows)
- Self-consistency, reflection and critique-and-revise
3.3 Safety and context engineering
Topics to cover, in this order:
- Prompt injection and jailbreaks (the attacks)
- Defending against prompt injection
- Context engineering: what goes into the window
- Managing long context: summarization, truncation, compaction
- Prompt caching and cost savings
3.4 Memory and prompt operations
Topics to cover, in this order:
- Conversation memory: short-term vs long-term
- Prompt versioning, templates and management tools
- Prompt iteration and testing with golden sets
- Common prompting mistakes and fixes
- Meta-prompting and AI-written prompts
3.1 Prompt basics — detailed notes
1. Prompt anatomy: role, task, context and format
LIKE I'M 5
A vague instruction says “make food.” A useful instruction says who is cooking, what to make, which ingredients to use and how to serve it.
EXPLAINED SIMPLY
- A prompt is the input and instructions supplied to a model.
- A useful prompt often states the role or perspective, task, context, constraints and desired output format.
- Add examples when the desired behaviour is hard to describe.
- Put important requirements clearly and remove conflicting instructions.
- Include only context relevant to the task. More text can create noise and cost.
- Treat prompts as versioned application assets. Test them with realistic inputs.
TRY IT
const prompt = {
task: "Summarise this bug report",
context: "Audience: frontend engineer",
constraints: ["Keep it under 100 words"],
format: "Problem, cause, next step"
};
This object represents prompt sections before your application converts them into provider messages.
INTERVIEW LENS
Describe role, task, context, constraints and output contract, then explain how you evaluate prompt reliability.
TRAPS
- Role-play does not create new model expertise.
- Contradictory instructions reduce reliability.
- A longer prompt is not automatically better.
ONE-LINE RECAP
A good prompt makes the task, evidence, constraints and expected output clear.
2. System vs user vs developer prompts
LIKE I'M 5
A workplace has company rules, manager instructions and a customer's request. They are not all the same kind of instruction.
EXPLAINED SIMPLY
- A system message may define high-level behaviour and boundaries in APIs that support it.
- A developer message usually defines application-level instructions and policies.
- A user message contains the request or data from the person using the app.
- Exact role names and precedence depend on the API and model interface. Follow the provider's current documentation.
- Never rely on prompt hierarchy as your only security boundary. Enforce permissions in code.
- Untrusted documents and tool outputs should be clearly separated from trusted instructions.
COMPARE WITH LOOKALIKES
| Message type | Typical owner | Example |
|---|---|---|
| System | Platform | Overall behaviour |
| Developer | Application builder | Output rules |
| User | End user | Current request |
INTERVIEW LENS
Explain message roles and instruction precedence, then stress that authorisation must be enforced outside the prompt.
TRAPS
- A user cannot be trusted to follow developer rules.
- Prompt instructions do not replace backend access control.
- Tool output is data, not automatically a trusted instruction.
ONE-LINE RECAP
Separate platform behaviour, application rules and user requests.
3. Zero-shot, one-shot and few-shot prompting
LIKE I'M 5
Zero examples means “do it from the instruction.” One-shot gives one sample. Few-shot gives several examples.
EXPLAINED SIMPLY
- Zero-shot prompting gives instructions without examples.
- One-shot includes one example of the expected input and output.
- Few-shot includes several examples to show a pattern.
- Examples can teach output format, tone, labels and edge-case behaviour.
- Use diverse, representative examples. Bad examples teach bad patterns.
- Keep examples consistent with the rules. Test on inputs not shown in the prompt.
TRY IT
const examples = [
{ input: "Payment failed", output: "billing" },
{ input: "Page is blank", output: "frontend" }
];
These examples demonstrate a classification pattern; a model would receive them as prompt context.
INTERVIEW LENS
Few-shot prompting conditions the model using demonstrations without updating model weights.
TRAPS
- Few-shot is not fine-tuning.
- Too many examples consume context.
- Examples can bias the output toward narrow patterns.
ONE-LINE RECAP
Examples demonstrate the behaviour you want without retraining the model.
4. Chain-of-thought, step-by-step and ReAct
LIKE I'M 5
A complicated job may need a plan: check the stock, place an order, then confirm delivery.
EXPLAINED SIMPLY
- Step-by-step prompting asks for an ordered solution or intermediate work.
- Chain-of-thought refers to reasoning steps generated by a model. Internal reasoning should not be assumed to be fully faithful or safe to expose.
- ReAct combines reasoning-oriented planning with actions and observations from tools.
- For production, request concise explanations, structured plans or verifiable evidence rather than depending on hidden reasoning traces.
- Break complex tasks into smaller steps and validate each important result.
- Tool execution needs permission checks, timeouts and result validation.
COMPARE WITH LOOKALIKES
| Pattern | Main idea |
|---|---|
| Step-by-step | Organise a response into stages |
| Chain-of-thought | Intermediate reasoning text |
| ReAct | Alternate reasoning, tool action and observation |
INTERVIEW LENS
Explain ReAct's action-observation loop and distinguish it from merely asking for a numbered explanation.
TRAPS
- A detailed explanation can still be wrong.
- Never expose secrets in reasoning prompts.
- Tool permissions belong in application code.
ONE-LINE RECAP
Decompose hard tasks, use tools carefully and verify intermediate results.
5. Prompt patterns: persona, templates, delimiters and XML tags
LIKE I'M 5
Put the recipe, ingredients and instructions into separate labelled boxes so nobody mixes them up.
EXPLAINED SIMPLY
- A persona sets a useful perspective, such as “act as a code reviewer”.
- A template defines reusable prompt structure with variables.
- Delimiters mark boundaries around user data, examples or documents.
- XML-like tags can label sections such as <task>, <context> and <input>.
- These structures improve clarity; they are not a security sandbox.
- Escape or safely encode untrusted content and never allow it to override backend permissions.
TRY IT
<task>Summarise the report</task>
<context>Audience: engineering manager</context>
<input>...untrusted report text...</input>
INTERVIEW LENS
Explain that structure improves parsing and instruction clarity, while server-side validation remains necessary.
TRAPS
- Tags do not create hard security boundaries.
- Persona prompts do not guarantee expertise.
- Avoid duplicated or contradictory template rules.
ONE-LINE RECAP
Use clear sections and delimiters to separate instructions from data.
3.2 Output control and tools — detailed notes
6. Positive and negative examples
LIKE I'M 5
Show the model both a good answer and a bad answer, like teaching with right and wrong examples.
EXPLAINED SIMPLY
- Positive examples show the desired output.
- Negative examples show patterns to avoid, such as unsupported claims or invalid formats.
- Explain why an example is good or bad. Labels alone may not teach the intended distinction.
- Use negative examples for common mistakes, not as a replacement for clear positive instructions.
- Test for overfitting: the model should handle unseen cases.
INTERVIEW LENS
Say examples clarify decision boundaries and output expectations, but should be representative and evaluated on held-out cases.
TRAPS
- Too many negative examples can confuse the task.
- A model may imitate bad text if boundaries are unclear.
- Never put real secrets in examples.
ONE-LINE RECAP
Good and bad examples make expectations concrete.
7. Structured output: JSON mode and JSON Schema
LIKE I'M 5
Instead of asking for a story, ask the model to fill a form with fixed boxes.
EXPLAINED SIMPLY
- Structured output asks the model to return data in a defined shape, often JSON.
- JSON mode may ensure valid JSON syntax but may not guarantee a specific schema.
- JSON Schema defines fields, types, required values, enums and constraints.
- Validate output on your backend even when the API supports schema-constrained generation.
- Handle missing fields, refusals, truncation and semantic errors.
- Use structured outputs for extraction, classification, routing and UI generation.
TRY IT
const schema = {
type: "object",
required: ["priority"],
properties: {
priority: { type: "string", enum: ["low", "high"] }
}
};
COMPARE WITH LOOKALIKES
| JSON mode | Schema-constrained output |
|---|---|
| Focuses on JSON syntax | Defines allowed structure and constraints |
| May allow unexpected fields | Can restrict fields and values |
| Still needs validation | Still needs semantic validation |
INTERVIEW LENS
Distinguish syntactically valid JSON from schema-valid and business-valid data.
TRAPS
- Valid JSON can contain incorrect values.
- Schema validation does not authorise an operation.
- Always handle refusal and incomplete responses.
ONE-LINE RECAP
Define a schema, validate the result and separately check business rules.
8. Function calling / tool calling
LIKE I'M 5
The model can ask a receptionist to book a room, but the receptionist's system performs the booking.
EXPLAINED SIMPLY
- Tool calling lets a model request an operation exposed by the application.
- The developer describes a tool name, purpose and input schema.
- The model returns a structured tool call with arguments.
- Your application validates arguments, checks identity and permissions, executes the function and sends the result back.
- The model can then produce a user-facing response.
- The model does not directly execute your backend function unless your application runs it.
- Require confirmation for purchases, deletion, messages and other consequential actions.
TRY IT
const tools = {
getWeather: async ({ city }) => weatherService.lookup(city)
};
Your server owns the implementation. The model only proposes a call.
INTERVIEW LENS
Walk through tool definition → model call → validation/authorisation → execution → tool result → final response.
TRAPS
- Tool calls are untrusted requests.
- Validate every argument.
- Prevent duplicate side effects with idempotency where needed.
ONE-LINE RECAP
The model selects and describes a tool call; your application securely executes it.
9. Prompt chaining, routing and parallelisation
LIKE I'M 5
A factory has stations: one sorts items, another checks them, and another packs them. Some jobs can happen at once.
EXPLAINED SIMPLY
- Prompt chaining passes one step's output into another prompt.
- Routing chooses a path based on the request, such as billing versus technical support.
- Parallelisation runs independent tasks at the same time.
- Use deterministic code for simple routing when possible. Use a model when classification needs language understanding.
- Validate intermediate outputs and set timeouts. Parallel calls need concurrency limits.
- Chaining improves separation but adds latency, cost and failure points.
TRY IT
const [summary, sentiment] = await Promise.all([
summarise(ticket),
classifySentiment(ticket)
]);
INTERVIEW LENS
Explain sequential dependencies versus independent parallel tasks, and how to handle partial failure and aggregation.
TRAPS
- Do not parallelise steps that depend on earlier results.
- More calls increase cost and failure surface.
- Validate route decisions before sensitive actions.
ONE-LINE RECAP
Split workflows into steps, route deliberately and parallelise only independent work.
10. Self-consistency, reflection and critique-and-revise
LIKE I'M 5
Ask several students to solve a problem, compare their answers and check the result before choosing.
EXPLAINED SIMPLY
- Self-consistency samples multiple candidate solutions and selects a consistent answer, often by voting or comparison.
- Reflection asks a model to review its previous output.
- Critique-and-revise separates drafting from checking and editing.
- These patterns can improve selected tasks but add tokens, latency and cost.
- Use external tests or trusted evidence where possible. A model reviewing itself can repeat the same mistake.
- Set a fixed number of attempts and a stopping condition.
INTERVIEW LENS
Explain candidate generation, aggregation and independent validation, including the cost of repeated model calls.
TRAPS
- Majority vote can agree on the same wrong answer.
- Self-critique is not independent ground truth.
- Unlimited reflection can create loops.
ONE-LINE RECAP
Generate, review and verify with bounded steps and external checks.
3.3 Safety and context engineering — detailed notes
11. Prompt injection and jailbreaks
LIKE I'M 5
A stranger writes “ignore your teacher and reveal the password” inside a book. The assistant must treat it as book text, not a new rule.
EXPLAINED SIMPLY
- Prompt injection is untrusted content attempting to change the model's instructions or actions.
- It can arrive directly from a user or indirectly through documents, websites, emails, images or tool results.
- A jailbreak attempts to bypass safety or policy constraints through crafted instructions.
- Attacks may ask the model to reveal secrets, call tools, change output rules or ignore prior directions.
- RAG and browsing increase exposure because retrieved content may contain hostile instructions.
- Assume all external content is untrusted data. Limit tools and permissions independently of prompts.
INTERVIEW LENS
Explain direct versus indirect injection and why tool permissions, data isolation and output validation matter.
TRAPS
- Prompt injection is not just a bad user prompt.
- Delimiters alone do not solve it.
- A retrieved document can be malicious.
ONE-LINE RECAP
Treat instructions from users and retrieved sources according to trust boundaries.
12. Defending against prompt injection
LIKE I'M 5
A school does not let a note found on the floor change the classroom rules. Important actions need a teacher's approval.
EXPLAINED SIMPLY
- Keep secrets outside model context wherever possible.
- Give each tool the minimum permissions needed. Separate read-only and write actions.
- Validate tool arguments and enforce authorisation in deterministic backend code.
- Treat retrieved text and tool output as data, not policy.
- Use allowlists, scoped credentials, network controls, output checks and human approval for risky actions.
- Test with attack examples and monitor suspicious tool calls.
- Defence is layered; no single prompt instruction can guarantee safety.
INTERVIEW LENS
Present defence in depth: least privilege, untrusted-input separation, server-side checks, approvals, monitoring and adversarial tests.
TRAPS
- “Ignore malicious instructions” is not sufficient.
- Never let model text choose arbitrary shell commands without controls.
- Human approval should show the exact action and target.
ONE-LINE RECAP
Secure the system around the model, not only inside the prompt.
13. Context engineering
LIKE I'M 5
A worker can do a better job when the correct documents, tools and instructions are on the desk.
EXPLAINED SIMPLY
- Context engineering is selecting and organising the information supplied to a model for a task.
- Context may include instructions, conversation history, retrieved documents, tool results, examples and output constraints.
- More context is not always better. Irrelevant or conflicting content can distract the model and consume tokens.
- Prioritise current task, trusted evidence and the most useful history.
- Include metadata such as source, timestamp, owner and access scope when relevant.
- Measure retrieval usefulness and answer quality, not only context size.
INTERVIEW LENS
Explain context selection as an engineering problem: relevance, trust, freshness, token budget and task requirements.
TRAPS
- Context engineering is broader than prompt wording.
- A larger context window does not guarantee recall.
- Never mix users' private data in shared context.
ONE-LINE RECAP
Give the model the right information, in the right order, with clear trust boundaries.
14. Long-context management: summarisation, truncation and compaction
LIKE I'M 5
A school bag cannot hold every book. Keep the important notes and remove what is no longer needed.
EXPLAINED SIMPLY
- Context windows have finite token capacity.
- Truncation removes content, often from an edge or selected region.
- Summarisation compresses history into a shorter representation.
- Compaction replaces a long interaction with a smaller state that preserves task-relevant facts and pending work.
- Preserve exact identifiers, decisions, constraints and unresolved actions. Avoid summarising away critical details.
- Track what was omitted and allow retrieval of original history when necessary.
- Test whether the compressed context still supports correct downstream answers.
INTERVIEW LENS
Compare truncation (discarding), summarisation (compressing meaning) and compaction (maintaining a compact working state).
TRAPS
- Summaries can introduce errors.
- Recent content is not always the most important.
- Keep source references for facts that need verification.
ONE-LINE RECAP
Compress history carefully while preserving facts needed for future steps.
15. Prompt caching and cost savings
LIKE I'M 5
If the first page of a workbook is always the same, keep it ready instead of copying it every time.
EXPLAINED SIMPLY
- Prompt caching reuses processing for repeated prompt prefixes when the provider and model support it.
- Stable instructions and shared context are good candidates for cacheable prefixes.
- Dynamic user content should generally come after the stable prefix.
- Cache eligibility, minimum token thresholds, retention and discounts differ by provider. Check current documentation.
- Caching can reduce latency or input processing cost, but does not remove output-token cost.
- Measure cache hit rate, token savings and total request cost.
INTERVIEW LENS
Explain stable-prefix design, provider-specific cache rules and measurement of hit rate and savings.
TRAPS
- Caching is not guaranteed for every request.
- Reordering content may prevent cache hits.
- Never rely on cache behaviour for data isolation.
ONE-LINE RECAP
Keep repeated prompt prefixes stable and measure whether caching actually saves money.
3.4 Memory and prompt operations — detailed notes
16. Conversation memory: short-term vs long-term
LIKE I'M 5
Short-term memory is what you keep in your hand today. Long-term memory is a notebook you can use next week.
EXPLAINED SIMPLY
- Short-term memory is recent conversation context, often bounded by the context window.
- Long-term memory stores selected facts or preferences across sessions.
- Memory can be explicit, summarised, retrieved from a database or stored as structured records.
- Store only useful, consented information. Apply access control, retention and deletion policies.
- Memory retrieval can be wrong or stale. Show provenance and let users correct important facts.
- Do not treat every conversation statement as a permanent fact.
COMPARE WITH LOOKALIKES
| Short-term context | Long-term memory |
|---|---|
| Current interaction | Across sessions |
| Limited by context window | Stored externally |
| Usually recent | Needs retrieval and updates |
INTERVIEW LENS
Explain memory as storage plus retrieval, with relevance scoring, privacy, freshness and user controls.
TRAPS
- Memory is not the same as model training.
- Persisting everything creates privacy and noise problems.
- Stale memory can harm answers.
ONE-LINE RECAP
Memory systems selectively store and retrieve useful context across time.
17. Prompt versioning, templates and management tools
LIKE I'M 5
A recipe book keeps version numbers so the kitchen knows which recipe made the best cake.
EXPLAINED SIMPLY
- Store prompts as versioned assets rather than scattered strings in source code.
- Use templates with named variables and explicit input contracts.
- Record owner, version, purpose, model, parameters, examples and evaluation results.
- Promote prompt changes through development, staging and production.
- Keep rollback capability and compare versions on the same evaluation set.
- Protect prompt repositories from secrets and private customer data.
INTERVIEW LENS
Describe prompt lifecycle management: author, version, test, review, deploy, monitor and roll back.
TRAPS
- A prompt change can alter model behaviour like a code change.
- Do not update production prompts without regression tests.
- Track model version alongside prompt version.
ONE-LINE RECAP
Prompts are production assets and should be versioned and reviewed.
18. Prompt iteration and golden sets
LIKE I'M 5
Keep a fixed set of exam questions. Every time you change the teaching method, check whether the answers improve.
EXPLAINED SIMPLY
- A golden set is a curated collection of representative inputs and expected outcomes.
- It should include normal, edge, ambiguous and adversarial cases.
- Define scoring rules: exact match, schema validity, human rating, factuality or task-specific metrics.
- Compare prompt versions on the same set and track regressions.
- Keep a separate holdout set to reduce overfitting to known examples.
- Add production failures to the set after removing sensitive information.
TRY IT
const cases = [
{ input: "Refund not received", expected: "billing" },
{ input: "Button does not work", expected: "frontend" }
];
INTERVIEW LENS
Explain repeatable evaluation, representative cases, measurable criteria and regression testing.
TRAPS
- A tiny golden set can hide failures.
- Human labels can disagree; define a rubric.
- Do not tune only to public benchmark questions.
ONE-LINE RECAP
A golden set turns prompt improvement into a measurable engineering process.
19. Common prompting mistakes and fixes
LIKE I'M 5
If you ask someone to “do it nicely,” they may guess what you mean. Clear instructions prevent guessing.
EXPLAINED SIMPLY
- Vague task → State the exact outcome and audience.
- Missing context → Supply trusted, relevant source material.
- Conflicting rules → Remove contradictions and set priorities.
- Huge prompt → Remove irrelevant history and use retrieval.
- Unstructured output → Define a schema and validate it.
- Unsupported facts → Require evidence or allow abstention.
- Unbounded tool use → Limit permissions and require approval.
- No testing → Build a golden set and track regressions.
INTERVIEW LENS
Explain that prompt quality is improved through diagnosis, controlled changes and evaluation—not endless wording tweaks.
TRAPS
- Prompting cannot fix missing data or broken architecture.
- More forceful language does not guarantee compliance.
- Do not rely on a single successful demo.
ONE-LINE RECAP
Diagnose the failure first, then fix the prompt, context, tool or system boundary responsible.
20. Meta-prompting and AI-written prompts
LIKE I'M 5
Ask an assistant to help write a better instruction for another assistant, then test that instruction.
EXPLAINED SIMPLY
- Meta-prompting uses a model to draft, analyse or improve prompts.
- It can turn a task description into a structured template or generate test cases.
- Provide requirements, constraints, examples and failure cases.
- Review generated prompts for ambiguity, unsafe permissions, hidden assumptions and unnecessary complexity.
- Evaluate the generated prompt on held-out examples before deployment.
- Keep human ownership of policies and acceptance criteria.
TRY IT
const task = "Classify support tickets by urgency";
const metaRequest = `Draft a prompt for this task: ${task}.
Include output fields, edge cases and refusal rules.`;
console.log(metaRequest);
INTERVIEW LENS
Explain that AI can accelerate prompt authoring, but generated prompts require review, versioning and evaluation.
TRAPS
- AI-written prompts can amplify mistaken assumptions.
- Do not let a model invent security policy.
- Test on data not used to draft the prompt.
ONE-LINE RECAP
Use AI to draft prompts, but keep humans responsible for requirements and validation.
Part 3 cheat sheet — interview answers
- Prompt anatomy → Task, context, constraints, examples and output format.
- System/developer/user → Platform behaviour, app rules and end-user request.
- Few-shot → Demonstrations condition output without updating model weights.
- ReAct → Reasoning-oriented steps alternate with tool actions and observations.
- Structured output → Schema controls shape; backend validates semantics and permissions.
- Tool calling → Model proposes; application validates and executes.
- Chaining → Sequential prompts pass outputs between steps.
- Parallelisation → Run independent work concurrently.
- Reflection → Review output, but use external checks for truth.
- Prompt injection → Untrusted content tries to override instructions or trigger actions.
- Defence → Least privilege, server checks, isolation, approvals and monitoring.
- Context engineering → Select relevant, trusted, fresh information within a token budget.
- Compaction → Preserve task state while compressing long history.
- Prompt caching → Reuse eligible repeated prefixes; measure cache hits and savings.
- Golden set → Fixed representative cases for regression testing.