In one line A useful AI product is a system, not just a model: the LLM is combined with your data (retrieval), actions (tools), control logic (workflows and agents) and checks (evaluation and guardrails).

Anatomy of an LLM application

The figure at the top of this page shows the typical parts. In words:

ComponentJobExamples
InterfaceWhere users interactChat UI, IDE plug-in, API endpoint, Slack bot
OrchestratorYour code: builds the context, calls the model, runs tools, loopsPlain Python, LangChain, LlamaIndex, LangGraph, an agent SDK
ModelUnderstands and generates textHosted API (Claude, GPT, Gemini) or local (Llama, Qwen, Mistral via Ollama)
RetrievalFinds relevant knowledge for each requestVector database, keyword search, SQL
ToolsLets the model act and fetch live dataWeb search, code execution, internal APIs, MCP servers
MemoryKeeps information across sessionsConversation summaries, user preferences, notes files
GuardrailsChecks inputs and outputsPII filters, prompt-injection detection, schema validation, human approval
Evaluation & observabilityMeasures quality, cost and failuresTest sets, LLM-as-judge, tracing (Langfuse, LangSmith, OpenTelemetry)

Prompting vs RAG vs fine-tuning

There are three main ways to adapt a general model to your task. Try them roughly in this order, because each step costs more effort than the last:

Three ways to adapt an LLM, in increasing effort: prompting, RAG, fine-tuning 1. Prompt engineeringchange the instructions 2. RAGgive the model the rightknowledge at question time 3. Fine-tuningchange the model's weightswith your own examples more effort, data and cost →
Figure 1. Start simple. Many problems never need fine-tuning.
PromptingRAGFine-tuning
ChangesInstructions and examplesKnowledge provided at run timeModel weights
Best forFormat, tone, task definitionPrivate, large or frequently changing knowledge; citationsConsistent style or format, specialised behaviour, smaller/cheaper model for a narrow task
Adds new facts?Only what fits in the promptYes, and easy to updatePoorly; not a reliable way to teach facts
EffortMinutes to hoursDays to weeks (data pipeline)Weeks (data collection, training, evaluation)
Data neededA few examplesYour documentsHundreds to thousands of high-quality examples

Retrieval-Augmented Generation (RAG)

RAG (Lewis et al., 2020) answers a question in two steps: first retrieve relevant passages from your own documents, then generate an answer with the LLM using those passages as context. It is the most common way to let an LLM answer questions about private or recent information, with citations.

RAG pipeline with an offline indexing phase and an online query phase A. Indexing (offline, once per document update) DocumentsPDF, wiki, code Split intochunks Embeddingmodel Vector databasevectors + text + metadata B. Query (online, every question) User question"What is OLCI's swath?" Embed thequestion Similaritysearch Top-k chunksmost relevant passages Prompt = instructions +retrieved chunks + question LLM Answerwith citations
Figure 2. RAG: index your documents once, then retrieve the most relevant chunks for every question.
Analogy A closed-book exam versus an open-book exam. A plain LLM answers from memory (closed book). RAG lets it look up the relevant pages first (open book), so answers are more accurate and can point to the page they came from.

Chunking

Documents are split into chunks because embedding models and context windows have limits, and because a small, focused passage matches a question better than a whole document. Chunk size is a trade-off: too small loses context, too large dilutes relevance.

A document split into overlapping chunks Document text ………………………………………………………………………………………………………………………… Chunk 1 Chunk 2 Chunk 3 Chunk 4 overlap
Figure 3. Overlapping chunks so that a sentence on a boundary is not cut off from its context.
StrategyHow it splitsGood for
Fixed sizeEvery N tokens (e.g. 300–800) with some overlap (e.g. 10–20%)Simple baseline; uniform text
Recursive / structuralBy headings, then paragraphs, then sentencesManuals, reports, Markdown, HTML
SemanticWhere the topic changes (embedding similarity between sentences drops)Long narrative documents
Code-awareBy function or classSource code

Store metadata with each chunk (source file, section, page, date, access rights). It enables filtering ("only documents from 2025") and citations.

The question is embedded with the same embedding model used for the chunks, and the database returns the chunks whose vectors are closest (highest cosine similarity). Comparing against millions of vectors one by one would be slow, so vector databases use approximate nearest neighbour (ANN) indexes such as HNSW (a navigable graph) or IVF (clustering), trading a tiny amount of accuracy for large speed-ups.

OptionTypeNotes
FAISSLibrary (Meta)Fast in-process similarity search; no server
ChromaEmbedded / server DBSimple to start with in Python
Qdrant, Weaviate, MilvusDedicated vector databasesFiltering, scaling, hybrid search
pgvectorPostgreSQL extensionVectors next to your relational data
Elasticsearch / OpenSearchSearch enginesCombine keyword (BM25) and vector search

Improving retrieval

Most poor RAG answers are caused by poor retrieval: the right passage never reached the model. Common improvements:

Hybrid search: keyword and vector results are merged, reranked, and the best few are sent to the LLM Question Keyword searchBM25: exact terms, IDs Vector searchmeaning, synonyms Mergee.g. ~50 candidates Rerankercross-encoder Top 5→ LLM
Figure 4. Hybrid search with reranking, a strong default for production RAG.
  • Hybrid search: vectors capture meaning but can miss exact terms such as product codes or requirement IDs ("REQ-0421"); keyword search (BM25) catches those. Use both.
  • Reranking: a cross-encoder model scores each (question, chunk) pair together, which is more accurate than vector similarity alone, then keeps only the best few.
  • Query rewriting: let the LLM rephrase or expand a vague or conversational question ("and what about the second one?") before searching.
  • Metadata filters: restrict by date, product, language or user permissions.
  • Contextual chunks: prepend a short description of the document and section to each chunk before embedding, so the chunk makes sense on its own.

AI agents

An AI agent is an LLM that works in a loop: it decides on an action, uses a tool, observes the result, and decides what to do next until the goal is reached. Unlike a single question and answer, the model directs its own process. This pattern was described in the ReAct paper (Yao et al., 2022): interleaving reasoning and acting.

Agent loop: goal, think, act with a tool, observe the result, repeat until done Goal from the user ThinkLLM plans next step Actcall a tool Observetool result → context Done?check against goal no yes Final answer / result
Figure 5. The agent loop. Each turn adds to the context, so long tasks need context engineering.

Examples: a coding agent that reads files, edits code and runs tests until they pass; a research agent that searches, reads and writes a report; a data agent that writes SQL, runs it, and fixes errors.

Agents need limits Because errors compound over many steps, give agents a step or budget limit, narrow permissions (read-only where possible), a sandbox for code execution, and human approval before irreversible actions such as sending emails, deleting data or making payments.

Workflows vs agents

Anthropic's guide "Building effective agents" draws a useful line: in a workflow, your code defines the steps and the LLM fills them in; in an agent, the LLM decides the steps. Workflows are more predictable and cheaper; agents are more flexible. Start with the simplest pattern that works.

PatternHow it worksExample
Prompt chainingFixed sequence of LLM calls, each using the previous outputOutline → draft → proofread
RoutingClassify the input, then send it to a specialised prompt or modelSupport ticket → billing / technical / general
ParallelisationRun several calls at once and combine (or vote on) the resultsCheck a document for security, style and accuracy in parallel
Orchestrator–workersOne LLM splits the task and delegates sub-tasks to worker callsChange code across many files
Evaluator–optimiserOne call produces, another critiques, and the loop repeatsTranslation refined until the reviewer is satisfied
Autonomous agentThe LLM chooses tools and steps in an open-ended loopCoding agents, deep-research agents

Model Context Protocol (MCP)

Every AI application used to need custom code to connect each tool or data source. The Model Context Protocol (MCP), an open standard introduced by Anthropic in November 2024 and since adopted by many AI tools, standardises this connection. It is often compared to USB-C for AI: build an MCP server for a system once, and any MCP-compatible application can use it.

MCP architecture: a host application with MCP clients connects to several MCP servers, each exposing a system MCP host e.g. Claude Desktop, an IDE, your own app LLM MCP client 1 MCP client 2 MCP client 3 JSON-RPC overstdio or HTTP MCP serverfile system MCP serverGitHub MCP serverPostgreSQL Local files GitHub API Database
Figure 6. MCP: one client per server connection inside the host application.
MCP server featureControlled byWhat it providesExample
ToolsThe model decides when to call themFunctions that do thingscreate_issue, run_query
ResourcesThe application chooses what to attachRead-only data for contextFile contents, database schema
PromptsThe user picks themReusable prompt templates"Summarise this pull request"
Security An MCP server runs with whatever permissions you give it. Install servers only from sources you trust, review the tools they expose, and be aware that text returned by a tool (a web page, an email, an issue comment) can contain prompt-injection instructions.

Fine-tuning & LoRA

Fine-tuning continues training a pre-trained model on your own examples so that it adopts a behaviour, format or style. Full fine-tuning updates all weights and needs a lot of GPU memory. Parameter-efficient fine-tuning (PEFT) updates only a small number of extra parameters; the most popular method is LoRA (Low-Rank Adaptation, Hu et al., 2021).

LoRA: the original weight matrix is frozen and a small low-rank update B times A is trained and added Wd × k, frozen + Bd × r Ar × k only A and Bare trainedr ≪ d, k (e.g. r = 8) W′ = W + B·A
Figure 7. LoRA learns a small low-rank correction instead of changing the large matrix W.

Worked example: for a 4096 × 4096 weight matrix (16.8 million parameters) and rank \(r = 8\), LoRA trains \(4096 \times 8 + 8 \times 4096 = 65{,}536\) parameters, about 0.4% of the original. QLoRA (Dettmers et al., 2023) goes further by keeping the frozen base model in 4-bit precision, which made fine-tuning a 65B-parameter model possible on a single 48 GB GPU.

Evaluating AI systems

LLM outputs are free text, so "accuracy" is not enough. Build a test set of realistic inputs with expected answers or criteria (start with 20–50 cases from real use), and re-run it every time you change the prompt, model, or retrieval settings.

MethodWhat it checksNotes
Exact / programmatic checksValid JSON, correct label, code passes tests, required fields presentCheap and reliable; use wherever possible
Reference metricsOverlap with a reference answer (BLEU, ROUGE, embedding similarity)Weak for open-ended answers
LLM-as-a-judgeA model grades answers against a rubricScales well; calibrate against human ratings; watch for bias toward long answers
Human reviewExpert judgementGold standard; expensive; use for spot checks and calibration
Online metricsUser feedback, task completion, escalations, cost per taskMeasures real-world value

For RAG, evaluate retrieval and generation separately. A common set of metrics (used by tools such as RAGAS and TruLens):

MetricQuestion it answers
Context relevance / precisionAre the retrieved chunks relevant to the question?
Context recallDid retrieval find all the information needed?
Faithfulness (groundedness)Is every claim in the answer supported by the retrieved context?
Answer relevanceDoes the answer actually address the question?

Guardrails & observability

  • Input guardrails: detect prompt injection, block disallowed topics, redact personal data before it reaches the model.
  • Output guardrails: validate against a schema, check that citations exist in the sources, filter harmful content, require human approval for actions.
  • Tracing: log every model call, tool call, retrieved chunk, token count and latency so failures can be reproduced and debugged.
  • Versioning: version prompts, models and indexes together, so a quality change can be traced to its cause.

Key terms

  • RAGRetrieve relevant passages, then generate an answer grounded in them.
  • ChunkA piece of a document that is embedded and retrieved as a unit.
  • Vector databaseStores embeddings and finds the nearest ones quickly.
  • RerankerA model that re-scores retrieved passages for relevance.
  • AgentAn LLM that chooses and runs tools in a loop toward a goal.
  • MCPOpen protocol connecting AI applications to tools and data sources.
  • LoRAFine-tuning by training small low-rank matrices added to frozen weights.
  • LLM-as-a-judgeUsing a model to grade outputs against a rubric.

Common misconceptions

MisconceptionReality
"Fine-tune the model on our documents so it knows them."Fine-tuning is unreliable for teaching facts and is hard to update. RAG is usually the right tool for knowledge.
"RAG eliminates hallucinations."It reduces them, but the model can still misread or go beyond the retrieved text. Measure faithfulness.
"Every LLM feature should be an agent."Fixed workflows are cheaper, faster and easier to test. Use agents when the steps really cannot be known in advance.
"If it works on my five examples, it works."Build a test set from real inputs and re-run it on every change.

Next: costs, hardware, local models and risks in Practical & responsible AI.

References

Books

  • AI Engineering: Building Applications with Foundation Models — Chip Huyen (O'Reilly, 2025)
  • Building LLMs for Production — Louis-François Bouchard, Louie Peters (Towards AI, 2024)
  • LLM Engineer's Handbook — Paul Iusztin, Maxime Labonne (Packt, 2024)

Some other interesting things to know: