Contents
Key concepts
Start simple: prompt, retrieve, fine-tune, then agents
Begin with a well-specified prompt and an eval. Add retrieval when answers depend on private or changing knowledge, fine-tuning when you need consistent behaviour or a cheaper model on a narrow task, and agentic loops only when the path to the answer cannot be fixed in advance. Predefined workflows (prompt chaining, routing, parallel sections or votes, orchestrator–workers, evaluator–optimiser) are easier to test and cheaper than open-ended agents; each added step must earn its latency and failure modes.
Flow · 4 stepsChoosing prompt, retrieval, fine-tuning or agents
- Start Start from the user problem with a well-specified prompt and an eval.
- Add only when needed Add retrieval for private or changing knowledge, fine-tuning for consistent behaviour or a cheaper model, and predefined workflows when the path is fixed.
- Agents last Use an agentic loop only when the path to the answer cannot be fixed in advance.
- Verify Ship from the first rung that passes the eval; each added step must earn its latency and failure modes.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Start | Start from the user problem with a well-specified prompt and an eval. |
| 2 | Add only when needed | Add retrieval for private or changing knowledge, fine-tuning for consistent behaviour or a cheaper model, and predefined workflows when the path is fixed. |
| 3 | Agents last | Use an agentic loop only when the path to the answer cannot be fixed in advance. |
| 4 | Verify | Ship from the first rung that passes the eval; each added step must earn its latency and failure modes. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| User problem | Start | simplest design that could work |
| Prompt + eval | Start | well-specified prompt and an eval |
| Retrieval | Add when needed | private or changing knowledge |
| Fine-tuning | Add when needed | consistent behaviour, cheaper model |
| Predefined workflow | Add when needed | prompt chaining, routing, votes |
| Agentic loop | Add when needed | path cannot be fixed in advance |
| Evals + online metrics | Ship | offline eval, online signals |
Source: This page's text
Anatomy of an LLM application
Around the model sit: context construction (retrieval, tools, user and session data), input and output guardrails (PII filtering, injection and policy checks, schema validation, groundedness), a router and gateway (model selection, auth, quotas, cost tracking, provider fallback), caches (provider prompt cache, exact-match and semantic response caches), orchestration for multi-step logic and write actions, and observability (traces of every prompt, retrieval, tool call, cost and latency) feeding evaluation and debugging.
Context engineering
The model only knows what is in its window, and quality degrades as that window fills with marginally relevant tokens; facts buried mid-context are used less reliably than those at the start or end. Curate the smallest high-signal context: tight system prompts, few well-described tools, retrieved chunks ranked and deduplicated, and for long tasks compaction (summarising history), structured notes outside the window, and sub-agents that return condensed results. Keep stable content first so prefix caching works.
Structured outputs and tool interfaces
Use JSON-schema-constrained decoding or native tool calling instead of parsing free text; validate every output and retry with the error message on failure. Design tools like APIs for a new colleague: distinct names, precise descriptions with examples, minimal required arguments, useful error messages, idempotent writes and pagination for large results. Forty overlapping tools confuse models; consolidate, namespace, or route to a subset per task.
Security: treat model inputs and outputs as untrusted
The OWASP LLM Top 10 (2026 edition) keeps prompt injection first and sensitive information disclosure second, with excessive agency now third. Indirect injection arrives through retrieved documents, emails, web pages and tool results. Controls: least-privilege tool scopes and per-user credentials, human approval for irreversible or financial actions, separating trusted instructions from untrusted data, sanitising rendered output (markdown images and links can exfiltrate data), output validation before execution, rate and spend limits, and red-teaming before launch.
Cost, latency and reliability
Cost per request = input tokens × input price + output tokens × output price (+ tool and retrieval costs); output tokens are usually several times dearer and slower. Levers: route easy requests to smaller models with a cascade or classifier, cache prefixes and frequent answers, cap output length, batch offline jobs, and distil. For latency, stream tokens, parallelise independent calls and keep prompts short. For reliability, use timeouts, retries with backoff, idempotency keys and a fallback model or provider; single-vendor dependence is a business-continuity risk. Plan for provider churn as well as outages: OpenAI shut down its Assistants API in August 2026, so keep conversation state you own behind a thin adapter and pin model versions.
Evals and feedback loops
Ship with an offline eval built from real queries and error analysis, then connect it to online signals: task success, edits, escalations, thumbs, retention and cost. Log traces to find new failure modes, add them to the eval set and regression-test every prompt, model or retrieval change. Define success with product owners before building, including the guardrail metrics that would stop a launch.
Where LLMs fit alongside existing systems
LLMs excel at language-shaped work: understanding free-text intent, extracting structure from documents, summarising, drafting and conversational interfaces. Keep specialised models where data is tabular, high-volume or latency-critical (fraud scoring, ranking) and let the LLM translate between users and those systems: for example, turning a free-text request into structured constraints that an existing retrieval and ranking stack can serve. For AI coding and research tools, the professional standard is human ownership: review diffs, run tests, check licences and secrets, and keep juniors learning fundamentals rather than accepting output unread.
Worked examples
Prompting, retrieval, long context or fine-tuning for 20,000 policy documents?
A team wants an assistant that ‘knows’ 20,000 internal policy documents averaging ~2,500 tokens, updated weekly, with answers that cite sources. Choose an approach using rough numbers (assume an illustrative input price of $3 per million tokens and a 1M-token context window).
Corpus size: 20,000 × 2,500 = 50M tokens, 50× the largest window. Stuffing everything is impossible; even a 1M-token slice costs 1M × $3 / 1M = $3 per query and adds many seconds of prefill.
Retrieval: top 10 chunks × ~500 tokens = 5,000 tokens → $0.015 per query, ~200× cheaper, with citations to the retrieved passages and weekly updates handled by re-indexing changed documents.
Fine-tuning: poor fit for the knowledge itself. It cannot cite, goes stale with weekly changes, and encourages confident fabrication. Use it, if at all, for answer style or a smaller serving model.
Long context still has a role: once retrieval has picked the 2–3 relevant policies, putting them in full (say 3 × 2,500 = 7,500 tokens) often beats tiny chunks for questions that need whole- document reasoning.
When retrieval is unnecessary: a small, stable corpus (a 40-page handbook ≈ 30k tokens) can sit in a cached system prompt; or the task only transforms text the user supplies.
Bake-off economics for summarisation at 2 million requests a day
Each request has ~1,500 input and ~200 output tokens. Illustrative prices: model A $3 / $15 per million input/output tokens; model B $0.25 / $1.25. Estimate daily cost for each, for a router that sends 80% to B, and the throughput a self-hosted option must sustain.
Daily tokens: input 2M × 1,500 = 3.0B; output 2M × 200 = 0.4B.
Model A: 3,000 × $3 + 400 × $15 = $9,000 + $6,000 = $15,000/day (~$5.5M/year).
Model B: 3,000 × $0.25 + 400 × $1.25 = $750 + $500 = $1,250/day.
Router 80/20: 0.8 × $1,250 + 0.2 × $15,000 = $1,000 + $3,000 = $4,000/day, a 73% saving versus A, if B meets the quality bar on the routed 80% (validate per slice, monitor for drift).
Self-hosting load: 2M / 86,400 ≈ 23 requests/s on average; assume a 3× peak ≈ 70 requests/s → ~105k prefill tokens/s and ~14k decode tokens/s at peak. Compare the GPU fleet’s cost at that load, with redundancy, against $1,250–4,000/day, and include engineering and on-call time.
Bake-off itself: a fixed set of real documents stratified by length and type, rubric-based faithfulness and coverage checks (code checks plus a validated judge), latency at production concurrency, and cost per acceptable summary rather than per request.
Free-text playlist generation on top of an existing recommender
Users type prompts like ‘upbeat 90s indie for a rainy run, nothing explicit’. Design how an LLM should work with the existing retrieval and ranking stack, and how you would evaluate it.
Division of labour: the LLM parses the prompt into a structured query (genres, era 1990–1999, mood/energy ranges, activity, explicit = false, length) validated against a schema; the existing candidate generators (embedding search over track and audio features plus metadata filters) retrieve a few thousand candidates; the existing personalised ranker orders them; business rules apply diversity and artist caps. The LLM may also write the title and description. It never picks tracks freely, which avoids hallucinated songs and keeps personalisation.
Latency budget (illustrative): parse 300–600 ms with a small model, retrieval 50 ms, ranking 50 ms; stream the title while tracks load.
Evaluation: offline, constraint satisfaction on a labelled prompt set (era, explicitness and genre checks are code-checkable; mood needs a validated judge or audio features), parse accuracy and refusal handling; online, listen-through rate, skips in the first 30 seconds, saves, repeat use, and guardrails on latency and explicit-content incidents.
Flow · 4 stepsFree-text prompt to existing recommender stack
- Parse The LLM parses the prompt into a structured query and validates it against a schema.
- Retrieve The structured query drives embedding search over track and audio features plus metadata filters.
- Rank and filter The personalised ranker orders candidates, then business rules apply diversity and artist caps.
- Return The LLM writes the title and description while tracks load, and the playlist is returned.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Parse | The LLM parses the prompt into a structured query and validates it against a schema. |
| 2 | Retrieve | The structured query drives embedding search over track and audio features plus metadata filters. |
| 3 | Rank and filter | The personalised ranker orders candidates, then business rules apply diversity and artist caps. |
| 4 | Return | The LLM writes the title and description while tracks load, and the playlist is returned. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Free-text prompt | Input | user request |
| LLM parser | LLM | structured query, schema-validated |
| Title writer | LLM | title and description |
| Candidate generators | Existing stack | embedding search + metadata filters |
| Personalised ranker | Existing stack | orders candidates |
| Business rules | Existing stack | diversity and artist caps |
| Playlist | Output | tracks plus title |
Source: This page's text
What changed recently
OpenAI shuts down the Assistants API
The Assistants API, deprecated in August 2025, was switched off on 26 August 2026; the replacement is the Responses API with the Conversations API for stored state. Architectures built on threads, runs and assistant objects, common in 2023–24 tutorials, are now obsolete. Interviewers use it to test whether you design for provider churn: thin adapters, conversation state you own, pinned model versions and a migration plan.
Claude structured outputs become generally available
Anthropic launched schema-constrained JSON outputs and strict tool inputs in public beta in November 2025 and made them generally available in February 2026, joining other major providers that already offered schema-constrained output. Constrained decoding guarantees the shape, not the content: field-level validation, evals and retries on semantic errors are still your job. Expect questions on choosing between structured outputs and tool calls, and on what guaranteed parsing does and does not fix.
MCP Apps: interactive UI inside assistants
The first official MCP extension, developed by the MCP maintainers with OpenAI and the MCP-UI project, lets a server ship interactive UI from ui:// resources that hosts such as Claude, ChatGPT, VS Code and Goose render in sandboxed iframes. It standardised what OpenAI’s Apps SDK started in October 2025, so one integration can reach several assistants. Interviewers ask about the sandbox’s security model, data minimisation and how to test an app that lives inside someone else’s product.
Apps in ChatGPT and the MCP-based Apps SDK
OpenAI opened ChatGPT to third-party apps built with an Apps SDK on top of MCP, initially outside the EEA, Switzerland and the UK. Assistants became distribution platforms, so product questions now include how a model discovers and invokes your service, what user data it receives, and how you measure success when users never visit your site.
The Responses API and built-in tools
OpenAI launched the Responses API with built-in web search, file search and computer use alongside its Agents SDK, merging chat-style calls with agent tooling and optional server-side state. It marked the shift from stateless text-in, text-out endpoints to item-based APIs that carry tool calls and reasoning between turns. Know what state you hand the provider, how reasoning is preserved across turns, and what that means for retention and portability.
Pitfalls
- Jumping to agents or fine-tuning before a prompt-plus-eval baseline exists.
- Fine-tuning to add frequently changing knowledge that should come from retrieval.
- Stuffing the context window instead of curating it, then blaming the model for missed facts.
- Trusting retrieved documents, emails or tool results as instructions (indirect prompt injection).
- Quoting cost per request without separating input and output tokens or measuring peak load.
- Using an LLM where a classical model is faster, cheaper and easier to validate (tabular scoring, ranking).
How interviewers probe it
- When do you use prompting, retrieval, fine-tuning or an agentic design? Give examples.
- Choose between three hosted models and a self-hosted model for a high-volume feature: design the bake-off.
- How would you let users generate playlists (or search, or reports) from free text while reusing the existing ML stack?
- Where do LLMs add real value in fraud and financial crime, and where would you keep classical models?
- As a new Head of AI, how would you spend 90 days building a company-wide LLM strategy, and what goes in the board paper?
- How do you and your team use AI coding tools, and how do you manage quality, security and skill development?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
When do you use prompting, retrieval, fine-tuning or an agentic design? Give examples.
Model answer, written in a candidate's voice
- Start with prompting and a small eval set; add complexity only with evidence.
- Use retrieval/RAG for fresh, grounded, or source-backed answers.
- Fine-tune for narrow, stable format, style, latency, or cost needs, not for facts.
- Use agents only for multi-step tool use with acceptable risk and clear gates.
- Escalate on failure evidence and count maintenance cost before choosing heavier options.
How would you set up evaluation for an LLM application your team is building?
Model answer, written in a candidate's voice
- Layered evaluation: task quality, safety, and regressions, not one score
- Golden sets from real representative traffic with expected outcomes
- Human review using explicit rubrics for faithfulness, correctness, tone, and usefulness
- LLM-as-judge calibrated against human labels, with safety and red-team sets
- CI regression suite gating prompt, model, and config changes
- Online feedback signals plus versioned datasets, judges, thresholds, and results
You have just joined as Head of AI. The CEO wants a company-wide LLM strategy in front of the board in 90 days. How would you spend those 90 days, and what goes in the board paper?
Model answer, written in a candidate's voice
- Days 0-15: align mandate with CEO, CFO and CRO: decision rights, budget, reporting line, risk appetite, success definition
- Days 0-45: discovery across the business: current AI use and shadow AI, data readiness, vendor contracts, talent, live pilots; interview roughly 15-25 stakeholders
- Score use cases on value, feasibility, risk tier and time-to-value; pick 2-3 lighthouse bets; set a productivity baseline
- Design operating model and governance: team topology, AI policy, inventory, risk tiers, approval route, UK regulatory mapping and EU AI Act if EU exposure
- Set platform and sourcing stance: model access, evaluation harness, observability, security, build/buy/partner principles
- Board paper: thesis, 3 bets with KPIs and kill criteria, phased investment ask, risks and controls, hiring plan, explicit not-do list
- Deliver one small win live by day 90 and make the paper decision-ready
You have finished this topic.
Reading
- Building effective agentsWorkflow patterns versus agents, and why to start with the simplest composable design.
- Building A Generative AI PlatformComponent-by-component view of the system around the model: context, guardrails, routing, caching, observability.
- What We've Learned From A Year of Building with LLMsTactical, operational and strategic lessons from practitioners shipping LLM products.
- Patterns for Building LLM-based Systems & ProductsSeven reusable patterns (evals, RAG, fine-tuning, caching, guardrails, defensive UX, feedback).
- Effective context engineering for AI agentsHow to curate context for long-running agents: compaction, notes and sub-agents.
- Lost in the Middle: How Language Models Use Long ContextsEvidence that position within a long context changes how reliably information is used.
- OWASP GenAI LLM Top 10 2026Current industry list of LLM application security risks and mitigations.
- Migrate to the Responses APIWhat changes when moving from Chat Completions or Assistants to an item-based, stateful API: items, previous_response_id, built-in tools and encrypted reasoning.
Practise this topic
- When do you use prompting, retrieval, fine-tuning or an agentic design? Give examples.
- How would you set up evaluation for an LLM application your team is building?
- You have just joined as Head of AI. The CEO wants a company-wide LLM strategy in front of the board in 90 days. How would you spend those 90 days, and what goes in the board paper?
- How does your team use AI coding and research tools, and how do you manage quality, security and skill development?
- Where do LLMs add real value in fraud and financial-crime work, and where would you keep classical or transaction-sequence models?
- How would you let users generate a playlist from a free-text prompt while still using the existing recommendation stack?
- Tell me about something you owned end to end under ambiguity and time pressure. How do you use AI coding tools in your daily work, and how do you check their output?
- A product team wants the assistant to “know” 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and fine-tuning — and when would you not use retrieval at all?
- Choose between three hosted models and one self-hosted open-weight model for a summarisation feature at 2 million requests a day. Describe the bake-off.
- It is early 2026 and your product is built on the OpenAI Assistants API (threads, runs and hosted file search), which is scheduled to shut down on 26 August 2026. Plan the migration, and the architecture that keeps the next forced migration cheap.
- Your platform exposes internal capabilities to agents. When would you publish something as an MCP server, and when as an A2A agent? Compare what each protocol standardises, how authorisation and long-running work are handled, and the security risks you would plan for.
- You are building an agent that reads a user’s email and calendar and can send messages and book meetings. Model-level prompt-injection defences are probabilistic. Design a defence that still holds if the model is fooled, and say how you would measure it.
- Inspired by GDPval, your company wants an eval of whether a model can produce real deliverables (for example a credit memo or a contract review) as well as your experts. Design it: task sourcing, grading, metrics and limitations.
- Product wants your booking service available inside ChatGPT and Claude as an MCP-based app with interactive UI. Design it: which tools the model sees, what the UI does, authorisation and state, data minimisation, and how you measure success.
- It is November 2026. Your team serves EU users a customer-facing chatbot and an image-generation feature, both built on a third-party general-purpose model that you fine-tune lightly. Which EU AI Act obligations apply now, which are coming, and who carries each?
- You are A/B testing a new LLM model and prompt for a customer-support assistant. Outputs are non-deterministic, the provider may update the model mid-test, and your main quality metric comes from an LLM judge. Design the experiment so the result is trustworthy.
- GPT-5 shipped as a fast model, a deeper reasoning model and a real-time router between them. Design and evaluate a similar router for your own assistant, which today sends every request to an expensive reasoning model.
- Your team retrieves candidates for a 50-million-item video catalogue with a two-tower model and ANN search. A research group proposes replacing it with generative retrieval over semantic IDs, as YouTube (PLUM) and Spotify (GLIDE) have deployed. How would you build the semantic IDs, serve the model within the retrieval latency budget, and decide whether to ship it?