Building AI Systems
- 1. Foundations of AI
- 2. NLP
- 3. How LLMs work
- 4. Working with LLMs
- 5. Building AI systems
- 6. Practical & responsible AI
Content
Anatomy of an LLM application
The figure at the top of this page shows the typical parts. In words:
| Component | Job | Examples |
|---|---|---|
| Interface | Where users interact | Chat UI, IDE plug-in, API endpoint, Slack bot |
| Orchestrator | Your code: builds the context, calls the model, runs tools, loops | Plain Python, LangChain, LlamaIndex, LangGraph, an agent SDK |
| Model | Understands and generates text | Hosted API (Claude, GPT, Gemini) or local (Llama, Qwen, Mistral via Ollama) |
| Retrieval | Finds relevant knowledge for each request | Vector database, keyword search, SQL |
| Tools | Lets the model act and fetch live data | Web search, code execution, internal APIs, MCP servers |
| Memory | Keeps information across sessions | Conversation summaries, user preferences, notes files |
| Guardrails | Checks inputs and outputs | PII filters, prompt-injection detection, schema validation, human approval |
| Evaluation & observability | Measures quality, cost and failures | Test 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:
| Prompting | RAG | Fine-tuning | |
|---|---|---|---|
| Changes | Instructions and examples | Knowledge provided at run time | Model weights |
| Best for | Format, tone, task definition | Private, large or frequently changing knowledge; citations | Consistent style or format, specialised behaviour, smaller/cheaper model for a narrow task |
| Adds new facts? | Only what fits in the prompt | Yes, and easy to update | Poorly; not a reliable way to teach facts |
| Effort | Minutes to hours | Days to weeks (data pipeline) | Weeks (data collection, training, evaluation) |
| Data needed | A few examples | Your documents | Hundreds 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.
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.
| Strategy | How it splits | Good for |
|---|---|---|
| Fixed size | Every N tokens (e.g. 300–800) with some overlap (e.g. 10–20%) | Simple baseline; uniform text |
| Recursive / structural | By headings, then paragraphs, then sentences | Manuals, reports, Markdown, HTML |
| Semantic | Where the topic changes (embedding similarity between sentences drops) | Long narrative documents |
| Code-aware | By function or class | Source code |
Store metadata with each chunk (source file, section, page, date, access rights). It enables filtering ("only documents from 2025") and citations.
Vector search
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.
| Option | Type | Notes |
|---|---|---|
| FAISS | Library (Meta) | Fast in-process similarity search; no server |
| Chroma | Embedded / server DB | Simple to start with in Python |
| Qdrant, Weaviate, Milvus | Dedicated vector databases | Filtering, scaling, hybrid search |
| pgvector | PostgreSQL extension | Vectors next to your relational data |
| Elasticsearch / OpenSearch | Search engines | Combine 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: 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.
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.
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.
| Pattern | How it works | Example |
|---|---|---|
| Prompt chaining | Fixed sequence of LLM calls, each using the previous output | Outline → draft → proofread |
| Routing | Classify the input, then send it to a specialised prompt or model | Support ticket → billing / technical / general |
| Parallelisation | Run several calls at once and combine (or vote on) the results | Check a document for security, style and accuracy in parallel |
| Orchestrator–workers | One LLM splits the task and delegates sub-tasks to worker calls | Change code across many files |
| Evaluator–optimiser | One call produces, another critiques, and the loop repeats | Translation refined until the reviewer is satisfied |
| Autonomous agent | The LLM chooses tools and steps in an open-ended loop | Coding 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 server feature | Controlled by | What it provides | Example |
|---|---|---|---|
| Tools | The model decides when to call them | Functions that do things | create_issue, run_query |
| Resources | The application chooses what to attach | Read-only data for context | File contents, database schema |
| Prompts | The user picks them | Reusable prompt templates | "Summarise this pull request" |
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).
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.
| Method | What it checks | Notes |
|---|---|---|
| Exact / programmatic checks | Valid JSON, correct label, code passes tests, required fields present | Cheap and reliable; use wherever possible |
| Reference metrics | Overlap with a reference answer (BLEU, ROUGE, embedding similarity) | Weak for open-ended answers |
| LLM-as-a-judge | A model grades answers against a rubric | Scales well; calibrate against human ratings; watch for bias toward long answers |
| Human review | Expert judgement | Gold standard; expensive; use for spot checks and calibration |
| Online metrics | User feedback, task completion, escalations, cost per task | Measures real-world value |
For RAG, evaluate retrieval and generation separately. A common set of metrics (used by tools such as RAGAS and TruLens):
| Metric | Question it answers |
|---|---|
| Context relevance / precision | Are the retrieved chunks relevant to the question? |
| Context recall | Did retrieval find all the information needed? |
| Faithfulness (groundedness) | Is every claim in the answer supported by the retrieved context? |
| Answer relevance | Does 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
| Misconception | Reality |
|---|---|
| "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
Papers
- P. Lewis et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. NeurIPS.
- S. Yao et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models.
- E. J. Hu et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models.
- T. Dettmers et al. (2023). QLoRA: Efficient Finetuning of Quantized LLMs.
- Y. A. Malkov, D. A. Yashunin (2016). Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (HNSW).
- L. Zheng et al. (2023). Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena.
- S. Es et al. (2023). RAGAS: Automated Evaluation of Retrieval Augmented Generation.
- Y. Gao et al. (2023). Retrieval-Augmented Generation for Large Language Models: A Survey.
Guides & documentation
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:
- Visit my pages on Machine learning & Deep learning
- Visit my website on Data engineering
- Visit my website on Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.