# AI Engineering from First Principles > A free, open study guide to AI engineering: 34 chapters on LLMs, tokenization, embeddings, RAG, evals, agents, MCP and production LLM systems, built up from the mechanism, with interview questions, system-design drills and real code annotated in the margin. Each chapter builds one topic from the mechanism up, then covers production concerns, interview questions with model answers, a hands-on exercise, and real code examples tagged solid, naive or missing. Written by Gaurav Singh. ## Part I: Foundations - [01. What AI Engineering Is](https://ai-engineering-first-principles.netlify.app/01-what-ai-engineering-is/): Explain what an AI engineer builds and owns in 2026, judge whether a feature should use an LLM at all, and plan the path from demo to product with an eval baseline, a cost and latency budget, and a cheap way to switch models. - [02. Text as Numbers: Tokenization](https://ai-engineering-first-principles.netlify.app/02-tokenization/): Understand how text becomes the integer tokens a model reads, build a byte-level BPE tokenizer by hand, and turn that into production skills: measuring Hindi and code token inflation on your own traffic, counting tokens before a call, catching chat-template and special-token bugs, and estimating what a feature will cost. - [03. Embeddings and Vector Space](https://ai-engineering-first-principles.netlify.app/03-embeddings-and-vector-space/): Understand how text and images become vectors whose geometry encodes meaning, from word2vec to contrastively trained bi-encoders, so you can pick, size, calibrate and migrate an embedding model in production and defend each choice in an interview. - [04. Language Modeling and Sampling](https://ai-engineering-first-principles.netlify.app/04-language-modeling-and-sampling/): See a model call as what it is, a loop that turns logits into a probability distribution and draws one token at a time, so you can reason about temperature, top-p, min-p, log-probs, finish reasons and non-determinism, and design code that stays correct when the output is a sample. - [05. Transformer Intuition](https://ai-engineering-first-principles.netlify.app/05-transformer-intuition/): Build a working engineer's model of a decoder-only transformer, from embeddings through attention, MLP and residual stream to logits, so you can explain attention on a whiteboard and turn parameters, context length, GQA and MoE into memory, FLOPs and cost. - [06. Pretraining, Data and Scaling](https://ai-engineering-first-principles.netlify.app/06-pretraining-and-scaling/): Know where a model's knowledge comes from and what it cost: the pretraining objective, how web data is filtered and deduplicated, training compute as 6·N·D, Kaplan versus Chinchilla, and why that explains knowledge cutoffs, strong small models and misleading benchmark scores. - [07. Post-Training and Alignment](https://ai-engineering-first-principles.netlify.app/07-post-training-and-alignment/): Understand how a pretrained text predictor becomes an assistant (SFT, chat templates, reward models, RLHF, DPO, constitutional methods and RL with verifiable rewards), and turn that understanding into concrete engineering habits: behaviour regression suites, refusal and sycophancy probes, and never treating alignment as a security boundary. - [08. Reasoning Models and Test-Time Compute](https://ai-engineering-first-principles.netlify.app/08-reasoning-models/): Understand how models came to think before they answer, from chain-of-thought prompts to RL-trained reasoning, and decide per route how much thinking to buy, what it costs in tokens and seconds, and when it makes answers worse. - [09. Fine-Tuning in Practice](https://ai-engineering-first-principles.netlify.app/09-fine-tuning-in-practice/): Decide with a procedure, not a slogan, whether a failure needs a better prompt, retrieval or new weights; then do the GPU memory arithmetic, build and clean the dataset, train a LoRA or QLoRA adapter, and prove it beats the base model before it ships. ## Part II: Inference and serving economics - [10. Inference Mechanics](https://ai-engineering-first-principles.netlify.app/10-inference-mechanics/): Explain what actually happens on a GPU when a model answers a request, and do the memory, latency and throughput arithmetic (KV cache, batching, quantization, speculative decoding, caching) that decides whether a deployment fits, how fast it is and what each token costs. - [11. Serving, Model Selection and Economics](https://ai-engineering-first-principles.netlify.app/11-serving-and-model-economics/): Decide between an API and self-hosted open weights with arithmetic you can show, pick a model by measuring it on your own task, and put a gateway in front of providers so outages, rate limits, price changes and deprecations stop being emergencies. ## Part III: Talking to models - [12. Prompting Fundamentals](https://ai-engineering-first-principles.netlify.app/12-prompting-fundamentals/): Explain why a prompt works as conditioning on a next-token distribution, write prompts that hold up in production (clear contracts, fenced context, chains, prefill), and improve, version and migrate them with evals instead of vibes. - [13. Structured Output](https://ai-engineering-first-principles.netlify.app/13-structured-output/): Turn a model call into a typed function your code can trust: choose between JSON mode, schema-enforced output and local grammar decoding, validate and repair what comes back, design schemas that make wrong answers representable, and measure extraction accuracy field by field. - [14. Multimodal and Realtime Voice](https://ai-engineering-first-principles.netlify.app/14-multimodal-and-realtime-voice/): Work out what an image, a scanned page or a minute of audio costs from a provider's published formula, choose between OCR and a vision model for documents, and design a voice loop (cascade or speech-to-speech) with a latency budget, endpointing, barge-in and Indic code-mixing handled, then evaluate all of it. ## Part IV: Retrieval and RAG - [15. Information Retrieval Foundations](https://ai-engineering-first-principles.netlify.app/15-information-retrieval-foundations/): Build a retriever from an inverted index up: derive BM25 and its parameters, know when dense, late-interaction and learned-sparse retrieval win, fuse and rerank them, and measure every stage with recall@k, MRR and nDCG you can compute by hand. - [16. Vector Search and Indexing](https://ai-engineering-first-principles.netlify.app/16-vector-search-and-indexing/): Understand how approximate nearest-neighbour indexes (IVF, PQ, HNSW, quantization) trade recall for latency and memory, why filters break them, and how to size, tune, update and benchmark a vector store you can defend in an interview. - [17. RAG Pipelines](https://ai-engineering-first-principles.netlify.app/17-rag-pipelines/): Build a retrieval-augmented generation pipeline end to end, from parsing and chunking to cited, verified, abstaining answers, and defend every stage with numbers in a system-design interview. - [18. Advanced and Agentic RAG](https://ai-engineering-first-principles.netlify.app/18-advanced-and-agentic-rag/): Extend a single-shot RAG pipeline to multi-hop, structured, graph, web and code questions, decide when to hand retrieval to the model as a tool, and keep the result safe, permission-aware and affordable. ## Part V: Evaluation - [19. Evals I: Methodology and Error Analysis](https://ai-engineering-first-principles.netlify.app/19-evals-methodology/): Turn real traces into a failure taxonomy, the taxonomy into a versioned eval set with cheap checks, and eval scores into decisions you can defend with error bars. - [20. Evals II: Judges, RAG/Agent Evals and Continuous Evaluation](https://ai-engineering-first-principles.netlify.app/20-evals-judges-and-ci/): Build LLM judges you can trust (validated against human labels, with their biases controlled), evaluate RAG pipelines and agents step by step, and run evals as a regression gate in CI and as sampled monitoring in production. ## Part VI: Agents - [21. Tool Use / Function Calling](https://ai-engineering-first-principles.netlify.app/21-tool-use/): Understand what actually happens when a model calls a function, design tools a model uses correctly, and make tool calls safe to retry, approve and evaluate in production. - [22. The Agent Loop and Architectures](https://ai-engineering-first-principles.netlify.app/22-agent-loop/): Write an agent loop from scratch with step, token and cost budgets, error feedback, checkpoints and human approval, and decide when a fixed workflow beats an agent. - [23. Memory](https://ai-engineering-first-principles.netlify.app/23-memory/): Design an agent's short-term and long-term memory from first principles: what to keep in the window, what to write to a store and with which metadata, how to retrieve, update, forget and evaluate it, and how to keep it private and hard to poison. - [24. Planning and Reasoning in Agents](https://ai-engineering-first-principles.netlify.app/24-planning/): Decide when an agent should plan before it acts, represent plans as structured data that code validates, run them as dependency graphs, replan and verify when they break, and measure whether planning paid for itself. - [25. Multi-Agent Systems](https://ai-engineering-first-principles.netlify.app/25-multi-agent-systems/): Decide when splitting work across several agents pays for its extra tokens and coordination, then build it: an orchestrator with sub-agents, handoffs, shared state and critics, failure defences you can test, and an eval against a single-agent baseline. - [26. MCP and Agent Protocols](https://ai-engineering-first-principles.netlify.app/26-mcp/): Understand what the Model Context Protocol standardises and how it works on the wire, build and secure an MCP server without a framework, and decide when MCP, Agent Skills, A2A or a plain function call is the right tool. - [27. Context Engineering](https://ai-engineering-first-principles.netlify.app/27-context-engineering/): Treat the context window as an agent's working memory and budget: decide what goes in, in what form and order, when to trim, compact, take notes or delegate, how to lay it out for the prompt cache, and how to measure whether it is any good. - [28. Coding and Computer-Use Agents](https://ai-engineering-first-principles.netlify.app/28-coding-and-computer-use-agents/): Build and reason about agents that edit code and drive screens: the tools they need, how they find and patch code, how tests close the loop, how SWE-bench and OSWorld grade them and where those grades mislead, and how sandboxes, permission modes and git keep their work safe and reviewable. ## Part VII: Production - [29. Guardrails and Safety](https://ai-engineering-first-principles.netlify.app/29-guardrails-and-safety/): Put the right checks around every model call: deterministic code first, then classifiers, then LLM judges, each with a defined action, a latency budget, a fail mode and a measured precision and recall, so the product blocks what it must without refusing the users it exists for. - [30. Observability](https://ai-engineering-first-principles.netlify.app/30-observability/): Instrument an LLM or agent system so you can reconstruct any request, see what it cost and whether quality is moving, and turn bad production traces into eval cases and fixes. - [31. Cost and Latency Engineering](https://ai-engineering-first-principles.netlify.app/31-cost-and-latency-engineering/): Find out where every rupee and millisecond of an LLM feature goes, then cut both with caching, routing, batching, effort tuning, trimming and budgets, while proving on your eval set that quality held. - [32. Deployment and LLMOps](https://ai-engineering-first-principles.netlify.app/32-deployment-and-llmops/): Ship and change an LLM system safely: version prompts and models as release artifacts, roll changes out through eval gates, shadow traffic and canaries, run long jobs on queues and streams that survive deploys, and protect paid endpoints with rate limits, timeouts, circuit breakers and failover. - [33. Security: Prompt Injection and Agent Security](https://ai-engineering-first-principles.netlify.app/33-security-prompt-injection/): Understand why prompt injection cannot be filtered away, threat-model any LLM feature or agent, and design the capability limits, data-flow rules, sandboxes and approval gates that keep a fooled model from doing damage. - [34. Product UX for AI and the Feedback Loop](https://ai-engineering-first-principles.netlify.app/34-product-ux-and-feedback/): Design the screens around a model that is sometimes wrong (states, progress, citations, approvals, errors) and build a feedback loop whose signals become eval cases and fixes, measured with product metrics you can defend. ## Interview prep - [Interview hub](https://ai-engineering-first-principles.netlify.app/interview/): fast-track reading order, 25 core concepts with one-minute answers, every chapter's interview questions. - [Production RAG over 10M documents at 1K QPS](https://ai-engineering-first-principles.netlify.app/interview/d01/): system-design drill. Design a question-answering system over 10 million internal documents that serves 1,000 queries per second at peak, with cited answers. Walk me through the architecture, the numbers and how you know it works. - [Customer-support agent with escalation](https://ai-engineering-first-principles.netlify.app/interview/d02/): system-design drill. Design an AI agent that handles customer support chats for an e-commerce company: it answers policy questions, looks up orders, can issue small refunds, and hands off to a human when it should. How do you build it and how do you know it is safe to ship? - [AI coding agent or PR reviewer](https://ai-engineering-first-principles.netlify.app/interview/d03/): system-design drill. Design an AI reviewer that comments on every pull request in a large company's repositories. Then tell me what changes if it is also allowed to push fixes. - [Voice assistant](https://ai-engineering-first-principles.netlify.app/interview/d04/): system-design drill. Design a voice assistant that customers can call or talk to in the app, in Hindi, English or a mix, to check account status and do simple actions. It has to feel like a conversation, not an IVR menu. - [Deep-research agent with citations](https://ai-engineering-first-principles.netlify.app/interview/d05/): system-design drill. Design an agent that takes a research question, searches the web for several minutes, and returns a report where every factual claim is cited. How do you make the citations trustworthy, and how do you keep cost under control? - [Text-to-SQL analyst assistant](https://ai-engineering-first-principles.netlify.app/interview/d06/): system-design drill. Design an assistant that lets business users ask questions in plain English about the company's data warehouse and get back correct numbers, a chart and the SQL it ran. How do you make it correct and safe? - [Eval and CI pipeline for an agent](https://ai-engineering-first-principles.netlify.app/interview/d07/): system-design drill. Your team ships an agent that plans, calls tools and writes answers for customers. Design the eval and CI pipeline so that a prompt, model or tool change cannot quietly make it worse. - [LLM gateway with routing, caching and fallbacks](https://ai-engineering-first-principles.netlify.app/interview/d08/): system-design drill. Twenty internal teams call three LLM providers directly, each with its own keys and retry code. Design a shared LLM gateway that handles routing, caching, fallbacks, rate limits and cost attribution. - [Document extraction at scale](https://ai-engineering-first-principles.netlify.app/interview/d09/): system-design drill. We receive about 2 million PDFs a month (invoices, contracts and scanned forms) and need structured fields out of each one, accurately enough to post into our finance system. Design the extraction pipeline. - [Cut LLM cost by 50% with no quality loss](https://ai-engineering-first-principles.netlify.app/interview/d10/): system-design drill. Your LLM bill doubled last quarter. Finance wants it halved next quarter, and product says users must not notice any drop in quality. How do you do it? - [Memory for a long-lived assistant](https://ai-engineering-first-principles.netlify.app/interview/d11/): system-design drill. Design memory for a personal assistant that people use every day for years. It should remember preferences, past conversations and facts about their life without becoming creepy, stale or expensive. - [Threat-model an email agent](https://ai-engineering-first-principles.netlify.app/interview/d12/): system-design drill. We are building an agent that reads a user's inbox, drafts replies, schedules meetings and can send email on their behalf. Threat-model it and design the defences. ## Optional - [What to build next](https://ai-engineering-first-principles.netlify.app/gaps/): AI-engineering skills with no example yet, each with a project to build. - [Real code by chapter](https://ai-engineering-first-principles.netlify.app/repos/): code examples mapped to chapters. - [Library](https://ai-engineering-first-principles.netlify.app/library/): open-licence readings by other authors, with attribution.