---
title: Building LLM applications
url: https://gurkanozkan.ai/learn/topics/llm-applications/
markdown: https://gurkanozkan.ai/learn/topics/llm-applications.md
kind: topic
tracks:
  - Applied LLM
  - AI leadership
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/llm-applications.json
---

# Building LLM applications

Most applied-LLM and AI-lead interviews ask how you would turn a model into a product that is useful, safe and affordable: choosing between prompting, retrieval, fine-tuning and agents; assembling the surrounding system (context construction, guardrails, routing, caching, observability); handling untrusted inputs; and proving value with evals and online metrics. Interviewers reward candidates who start from the user problem and the simplest design that could work, and who reason with numbers about cost and latency. They also look for judgement about where classical ML still wins, and for a credible account of how you use AI tools in your own work without giving up verification.

## 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.

### 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).

**Solution**

**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.

**Solution**

**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.

**Solution**

**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.


## What changed recently

- **Aug 2026: 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. [Source](https://developers.openai.com/api/docs/deprecations)
- **Feb 2026: 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. [Source](https://claude.com/blog/structured-outputs-on-the-claude-developer-platform)
- **Jan 2026: 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. [Source](https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/)
- **Oct 2025: 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. [Source](https://openai.com/index/introducing-apps-in-chatgpt/)
- **Mar 2025: 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. [Source](https://openai.com/index/new-tools-for-building-agents/)

## 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?

## Reading

- [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents) (Blog, 25 min, Intro): Workflow patterns versus agents, and why to start with the simplest composable design.
- [Building A Generative AI Platform](https://huyenchip.com/2024/07/25/genai-platform.html) (Blog, 50 min, Core): Component-by-component view of the system around the model: context, guardrails, routing, caching, observability.
- [What We've Learned From A Year of Building with LLMs](https://applied-llms.org/) (Blog, 90 min, Deep): Tactical, operational and strategic lessons from practitioners shipping LLM products.
- [Patterns for Building LLM-based Systems & Products](https://eugeneyan.com/writing/llm-patterns/) (Blog, 75 min, Core): Seven reusable patterns (evals, RAG, fine-tuning, caching, guardrails, defensive UX, feedback).
- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) (Blog, 25 min, Core): How to curate context for long-running agents: compaction, notes and sub-agents.
- [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) (Paper, 35 min, Core): Evidence that position within a long context changes how reliably information is used.
- [OWASP GenAI LLM Top 10 2026](https://genai.owasp.org/resource/owasp-genai-llm-top-10-2026/) (Docs, 45 min, Core): Current industry list of LLM application security risks and mitigations.
- [Migrate to the Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) (Docs, 20 min, Core): What 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.](https://gurkanozkan.ai/learn/questions/lead-td-05.md)
- [How would you set up evaluation for an LLM application your team is building?](https://gurkanozkan.ai/learn/questions/lead-td-04.md)
- [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…](https://gurkanozkan.ai/learn/questions/lead-sc-01.md)
- [How does your team use AI coding and research tools, and how do you manage quality, security and skill development?](https://gurkanozkan.ai/learn/questions/lead-pl-15.md)
- [Where do LLMs add real value in fraud and financial-crime work, and where would you keep classical or transaction-sequence models?](https://gurkanozkan.ai/learn/questions/applied-llm-dom-05.md)
- [How would you let users generate a playlist from a free-text prompt while still using the existing recommendation stack?](https://gurkanozkan.ai/learn/questions/applied-llm-dom-09.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-beh-05.md)
- [A product team wants the assistant to "know" 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-01.md)
- [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.](https://gurkanozkan.ai/learn/questions/applied-llm-evl-08.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-llmapps-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-agents-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-agents-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-eval-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-llmapps-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-gov-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-exp-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-system-design-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-recommendation-01.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
