Intermediate
AI engineering
Building reliable products on large language models — prompting, retrieval, agents, evals and production — without treating the model as magic.
- Sections
- 6
- Pages
- 155
- Reading time
- ~6 h
- Take first
- Foundations, System design
What you will be able to do
- Choose a model for a task by weighing quality, latency, cost, context length and deployment constraints, backed by your own evals.
- Write prompts and structured-output schemas that are robust, testable and versioned.
- Build a RAG system with hybrid search, reranking and retrieval metrics, and know when long context beats retrieval.
- Design tools, agent loops, MCP servers and multi-agent systems with sensible stopping, state and human-in-the-loop controls.
- Build an eval suite with code-based checks and calibrated LLM judges, and use it to drive every change.
- Defend an LLM app against prompt injection and data exfiltration, and add guardrails without wrecking UX.
- Cut latency and cost with streaming, routing, prompt caching and batching, and observe it all in production.
An LLM is a probabilistic text function: tokens in, a distribution over the next token out. Chatbots, RAG systems, coding agents and support bots are all the same loop with different context and tools. AI engineering is the craft of making that loop dependable enough to ship — choosing models, shaping prompts and context, retrieving the right evidence, calling tools safely, measuring quality and controlling cost.
The machine learning course covers how models are trained. These pages assumes you will mostly call models, and focuses on what changes when the model is a black-box API (or a self-hosted checkpoint) inside a product.
Who this is for
You are a software engineer who needs to put LLMs into real systems: an API route that answers from company docs, a workflow that extracts fields from PDFs, an agent that can open tickets and escalate. You write TypeScript or Python comfortably. You do not need a deep learning background — when a CS idea matters (token, logit, embedding, attention), lessons define it inline.
If you want GPU kernels, quantization math and serving fleets, that is the inference course. If you want transformers from first principles, start in ML and come back here for the product layer.
How to study it
Read in unit order the first time. Foundations (tokens, transformers, sampling, APIs) make every later page less mysterious; skip them and you will fight cost and latency without a model of why.
For each technique page, do one small end-to-end exercise: a prompt with three golden cases, a tiny RAG corpus, a tool-calling loop with one function, an eval set of twenty examples. The Further learning links are reference depth, not homework — pull them when you are stuck on a decision.
When you change a prompt, a model or a retrieval setting, re-run the same eval set. That habit matters more than any single architecture pattern.
Expect the fundamentals unit to take a focused afternoon if you already call LLM APIs daily, or two or three sittings if the token/attention vocabulary is new. Retrieval and agents each deserve a weekend project of their own. Production pages repay a second pass after you have something live — the latency and caching notes make more sense once you have a bill.
Unit roadmap
The numbered list is a shorter path. The sections below are every lesson: 155 in all, about 6 hours of reading.
LLM fundamentals
What the model is doing when you call it, and how to choose one.
- The LLM landscape and model choice — frontier vs open-weight, reasoning models, a selection process driven by your evals
- Tokens and context windows — tokenization, cost math, budgeting the window
- How transformers work (practitioner view) — attention, prefill/decode, KV cache, why position matters
- Sampling and decoding — temperature, top-p, penalties, when to leave defaults alone
- Working with LLM APIs — messages, streaming, stop reasons, retries, batch APIs
Prompting and context
What you put in the window.
- Prompting — instructions, examples and structure as specification
- Structured outputs — schemas, constrained decoding, validation
- Context engineering — ordering, compaction, memory, long context vs retrieval
- Multimodal inputs and outputs — images, PDFs, audio and video
Retrieval
Grounding answers in your data.
- Embeddings and similarity — vectors, similarity metrics, choosing an embedder
- Vector search and vector databases — ANN algorithms and store choices
- Retrieval-augmented generation — ingest, chunk, retrieve, generate with citations
- Advanced RAG — hybrid search, reranking, query rewriting, retrieval metrics
Agents and tools
Letting the model act.
- Tool use and function calling — schemas and the tool loop
- Agents and agent architectures — workflows vs agents, ReAct, stopping
- Model Context Protocol (MCP) — the open standard for tools and data
- Multi-agent systems — orchestrators, isolation, coordination cost
- Agent infrastructure — sandboxes, durable execution, permissions
- Voice agents — STT→LLM→TTS vs speech-to-speech, latency budgets
Quality and safety
Knowing whether it works and keeping it safe.
- Evaluating LLM apps — datasets, error analysis, metrics that drive changes
- LLM-as-a-judge — grader design and calibration
- Guardrails, security and safety — injection, exfiltration, jailbreaks
- Fine-tuning vs prompting vs RAG — when each lever is worth it
Production and case studies
Shipping under latency, cost and UX constraints.
- Latency and cost optimization — streaming, routing, cascades, batching
- Caching for LLM apps — prompt, exact and semantic caches
- LLMOps and observability — tracing, prompt management, online monitoring
- Designing AI product experiences — trust, control, failure states
- Case study: customer support agent
- Case study: coding agent
- Case study: document extraction pipeline
Course resources
Chip Huyen's AI Engineering is the closest book-length companion to this syllabus — systems view, not research papers.
AI Engineering (Chip Huyen, O'Reilly)oreilly.comKarpathy's intro talk is the best one-hour mental model of what an LLM is and is not. Watch it before the fundamentals unit if the topic is new.
His longer deep dive is useful when you want training and post-training intuition without committing to a full ML course.
For live quality and cost comparisons across providers, keep Artificial Analysis and LMArena bookmarked — then build your own eval set before you trust either for a product decision.
LLM fundamentals
The LLM landscape and model choice
Frontier vs open-weight models, reasoning models, and a process for picking one with your own evals.
Frontier vs open-weight
Frontier models arrive through a vendor API. Open-weight models are downloadable parameters, not automatically open source.
Reasoning models
Extra inference-time compute, often a hidden chain of thought, billed as output tokens. Use them on the hard slice, not on "summarize this email."
Choosing a model
Prove the product on a strong model, freeze an eval, then step down the ladder. Your suite decides, not a leaderboard.
Why benchmarks lie
Leaderboards answer "is this model generally strong?" They do not answer whether it extracts your invoice fields at 99% with your schema.
What a token is
Models read integer IDs, not words. The same sentence can be a different number of tokens on two APIs.
Tokenization quirks
Letter-counting, long numbers and some languages fail because the model sees pieces, not characters. Measure real payloads.
Tokens and context windows
How text becomes tokens, what that means for cost and limits, and how to budget a context window.
Context windows
The window is input plus output. Everything you send — instructions, tools, history, retrieved docs — shares one budget.
Token pricing
Bills are USD per million tokens. Output is often 3 to 5 times input. Caching a stable prefix can cut the input line.
Budgeting a context window
Treat the window like RAM for one request. Cap history, drop old tool dumps and leave room for the answer.
The next-token loop
A decoder-only model is a function from tokens so far to the next token. Products wrap that loop with different prompts and stop rules.
Attention for builders
Each position mixes earlier positions with a weighted average. Anything in the context can influence the next token.
How transformers work (practitioner view)
Just enough transformer internals to predict model behavior — attention, context, and why the KV cache shapes pricing.
Lost in the middle
Attention can look anywhere earlier in the context, but quality is often best at the edges and worse in the middle of a long prompt.
Prefill, decode and the KV cache
One parallel pass over the prompt, then one token at a time. Reusing keys and values is why a stable prefix saves money.
Weights vs context vs tools
Grammar lives in the weights. Private docs live in the prompt. Live account state lives in tools. Hallucinations thrive when you pick the wrong row.
Sampling and decoding
Temperature, top-p, top-k and other knobs that turn logits into text, and when to touch them.
Temperature
Temperature divides logits before softmax. Low values peak on the top token. High values flatten the distribution and let rare tokens through.
Top-k, top-p and min-p
Truncation deletes the long tail of the vocabulary, then renormalizes. Top-p adapts to confidence. Top-k does not.
Decoding controls
Max tokens, stop sequences, penalties and logprobs. Temperature 0 removes sampling noise. It does not make two API calls bit-identical.
Self-consistency and best-of-n
Sample several times and pick with a vote or a verifier. You buy robustness with n times the output tokens, and only when the answer is checkable.
Working with LLM APIs
Messages, roles, streaming, stop reasons, errors, rate limits and batch APIs. The plumbing of every LLM app.
Chat messages and roles
Each call resends the full conversation. Roles mark who said what. Pin the model id and version the system prompt.
Streaming and stop reasons
Tokens arrive as events. The model always stops for a reason. Branch on that reason. Do not assume success.
Retries and rate limits
Retry 429 and 5xx with exponential backoff and jitter. Never blindly retry a tool that already had a side effect.
Batch LLM APIs
Submit a file of requests, get results hours later, typically at about half the sync token price. For overnight work, not chat.
Prompting and context
Prompting
Clear instructions, examples, structure and chain-of-thought: prompting as specification writing.
Prompts as specifications
A prompt is a written spec: goal, inputs, constraints, output shape and success criteria. Vague asks produce vague answers.
Prompt structure
Where each part of a prompt goes: durable rules in the system message, per-request data in labeled sections, and the question last.
Few-shot examples
Input and output demonstrations that teach format and judgment, why diversity beats volume, and when examples over-constrain.
Chain-of-thought and extended thinking
When asking the model to reason step by step helps, how native thinking differs from prompted reasoning, and how to keep the reasoning out of the answer.
Structured outputs
Getting reliable JSON: schemas, constrained decoding, validation and repair.
Constrained decoding
How a schema can be enforced during generation by masking tokens that would break it, and what that guarantee does not cover.
Schema design
How to write JSON schemas the model fills in correctly, using flat shapes, enums, explicit nulls and field descriptions as instructions.
Validation and repair
Why every structured output still needs code-level validation, how a bounded repair loop works, and how to handle refusals and truncated output.
Field-level evals for extraction
How to score structured outputs field by field, with worked arithmetic, and why "100% valid JSON" can hide wrong invoice IDs.
Context engineering
Deciding what goes into the context window: ordering, compaction, memory and long context vs retrieval.
Context ordering
Put a stable, cacheable prefix first and the live question last, so quality and prompt caches both win.
Compaction and just-in-time retrieval
Summarize old turns, trim tool dumps and re-fetch full payloads only when the agent can navigate to them.
Long context vs RAG
Paste the working set when it fits. Retrieve when the corpus is large and only a few passages matter. Many products do both.
Multimodal inputs and outputs
Images, PDFs, audio and video in LLM apps: what works, what it costs and how to evaluate it.
Vision tokens and cost
Providers bill images as tokens after a resize. Resolution, crops and detail settings decide both the invoice and whether small text is readable.
Document understanding
PDFs, tables and charts: prefer a native text layer when it exists, and use vision for the parts text cannot see.
Audio and video
Audio is either speech-to-text plus a text model, or native audio tokens. Video is sampled frames. Cost scales with duration and resolution.
Multimodal evals
Grade real photos and screenshots, not clean demos. Schema validity is not a correct total, and production lighting is part of the fixture.
Retrieval
Embeddings and similarity
Turning text into vectors, measuring similarity, and choosing an embedding model.
Vector similarity: cosine, dot product and distance
How to compare two embeddings with cosine, dot product or Euclidean distance, and why normalizing vectors makes them agree.
Bi-encoders and cross-encoders
Why retrieval encodes the query and documents separately, why reranking reads them together, and how the two work in sequence.
Choosing an embedding model
How to pick an embedding model by running a small bake-off on your own documents, weighing quality, dimension, input length, language and cost.
Embeddings beyond search
Clustering, near-duplicates, cheap classifiers and recommendations all use the same vectors you already store for retrieval.
Exact vs approximate search
Exact kNN checks every vector. ANN misses a few neighbors on purpose so a 10-million-row index can answer in milliseconds.
Vector search and vector databases
Approximate nearest neighbor algorithms (HNSW, IVF, PQ) and choosing between pgvector and dedicated stores.
HNSW
A layered graph. Search walks sparse highways first, then a dense bottom layer. Tune M, efConstruction and efSearch.
IVF, PQ and DiskANN
Cluster, compress or spill to SSD when a pure HNSW graph no longer fits in RAM.
Filtered vector search
Almost every real query is nearest neighbors among documents the caller may see. Filter at retrieval, never in the prompt.
Choosing a vector store
Start with pgvector when Postgres is enough. Move to a dedicated store for RAM, filters, hybrid search or ops pain.
Retrieval-augmented generation
The core RAG pipeline: ingest, chunk, embed, retrieve, generate with citations.
The RAG ingestion pipeline
The offline half of RAG, from parsing documents to syncing edits, deletes and access rules, so the index never drifts from the source.
Chunking for RAG
How to cut documents into passages for retrieval, why naive character cuts break facts, and how size, overlap and context prefixes change what can be found.
Grounded answers with citations
The query-time path of RAG, from question to top-k chunks to a grounded prompt that refuses when evidence is missing and cites sources that code can check.
RAG failure modes and debugging
Five ways a RAG answer goes wrong, how to tell them apart from one failing trace, and the first fix for each.
Retrieval metrics
Recall@k, MRR and nDCG tell you whether the right chunk was found, before you blame the prompt or the model.
Advanced RAG
Hybrid search, reranking, query rewriting, contextual retrieval and measuring retrieval quality.
Hybrid search
Run BM25 for exact tokens and dense vectors for paraphrases, then fuse the two ranked lists with reciprocal rank fusion.
Reranking
Retrieve a wide pool with a bi-encoder, then score query and passage together with a cross-encoder so the prompt gets the best 5 to 10.
Query transformation
Rewrite, split, expand or hypothesise a search query before retrieval, so messy questions still hit the right chunks.
Contextual retrieval
Situate every chunk with document and section context before you embed it, so "Revenue grew 3%" still names the company.
Agents and tools
The tool loop
The model emits a structured call. Your runtime runs it, or refuses it, and sends the result back. Bound the loop.
Tool use and function calling
Letting models call your code: tool schemas, the tool loop, and designing tools models use well.
Tool schemas
Names, descriptions and JSON Schema are prompts. Vague contracts are the most common cause of the wrong tool.
Designing tools
Fewer, higher-level tools with compact, paginated outputs beat a pile of micro-endpoints the model must stitch together.
Safe tool execution
Your executor owns auth, idempotency and approvals. The model proposes. It does not authorize.
Evaluating tool use
Score tool choice, arguments and error recovery — not only the final sentence. Fifty good cases beat a thousand random chats.
Agents and agent architectures
Workflows vs agents, the core patterns, ReAct loops, planning and knowing when to stop.
Workflow patterns
Chaining, routing, parallelization, orchestrator-workers and evaluator-optimizer cover most production systems before you need an open agent loop.
The ReAct loop
Reason, act, observe, repeat, with hard stop conditions so the loop cannot run forever.
Agent planning
Write a plan first when you need approval or a large decomposition. Interleave the next action when the environment keeps surprising you.
Agent autonomy and stopping
Autonomy is a dial. Pick a level, cap the loop, verify writes with external signals and put a human on irreversible actions.
Model Context Protocol (MCP)
The open standard for connecting models to tools and data: architecture, primitives, transports and security.
Hosts, clients and servers
MCP turns N times M custom adapters into N plus M. A host owns the app, a client talks to one server, and a server exposes tools and data.
Tools, resources and prompts
MCP servers expose three primitives: tools the model calls, resources the app can read, and prompt templates the user can insert.
stdio and HTTP transports
Two ways to move MCP messages: a local subprocess over stdin/stdout, or a remote HTTP server with OAuth.
MCP security
A connected server can steer the model, act with the user's token and read tool results that contain attacker text. Pin, scope and enforce policy in code.
Multi-agent systems
When multiple agents beat one: orchestrator-subagent designs, context isolation and the cost of coordination.
Orchestrator and workers
One planner writes a task list. Workers run those tasks in parallel with their own tools, then return condensed results.
Context isolation
Each worker should see only its brief and its own tool results. Summaries at the boundary must keep citations and caveats, not raw HTML.
Coordination and cost
Extra agents multiply tokens and create new failure modes. Budget the fan-out, then watch duplication, conflicting edits and lossy merges.
Evaluating multi-agent systems
Score the final artifact, then slice failures into coverage, handoff fidelity, efficiency and contradictions.
Agent infrastructure
Running agents for real: sandboxes, durable execution, state, permissions and long-running tasks.
Agent sandboxes
Code, browsers and filesystems run somewhere else, with no production secrets, capped resources and an allowlisted network.
Durable agent execution
Record each completed step so a crash, a deploy or an overnight approval resumes instead of starting over.
Agent state and memory
Split conversation, artifacts, working memory and run control. Persist after each step. Reload a hot working set, not the whole transcript.
Agent permissions and audit
Authorize every tool against the real user, keep policy in code next to the executor and log who approved each side effect.
Cascaded vs speech-to-speech
STT then LLM then TTS gives you control. A native speech model gives you feel. Many teams ship one and prototype the other.
Voice agents
Real-time speech AI: STT→LLM→TTS pipelines vs speech-to-speech models, latency budgets and turn-taking.
Voice latency budgets
Humans notice gaps. Target roughly 500 to 800 ms from end of speech to first audio, and get there by overlapping stages.
Turn-taking and barge-in
VAD finds speech. Endpointing decides the turn is over. Barge-in must stop TTS and cancel the old generation immediately.
Streaming the voice pipeline
Overlap STT partials, LLM tokens and TTS frames. Flush on clause boundaries. Speculate only on safe, read-only prep.
Evaluating voice agents
Score latency, barge-in, ASR impact and task success together. A scripted call suite belongs in CI next to text evals.
Quality and safety
Evaluating LLM apps
A fixed set of inputs plus a way to score outputs, so you can tell whether a change helped.
Error analysis and failure taxonomies
Read real traces, name what went wrong, and group the notes into categories. Those categories decide which evals you write.
Eval graders
A grader is the rule that decides whether one output passes. Use the cheapest grader that catches the failure reliably.
Offline and online evals
Offline evals run on a fixed dataset before you ship. Online evals score live traffic. You need both, and every run should record its versions.
Eval noise and sample size
A pass rate is a proportion, and proportions wobble. Learn how big the wobble is at your sample size before you celebrate a small gain.
LLM-as-a-judge
Using models to grade models: when a judge is the right grader, how to design one, and why an uncalibrated judge is a vibes function.
Judge design
Ask for a short critique and a binary verdict. One criterion per judge. Make the verdict parseable.
Calibrating LLM judges
Label 100 to 200 examples with a human, then treat FAIL-detection as a classification problem. Fix the rubric before you swap models.
Judge biases
Judges prefer some answers for reasons that are not quality. Position, verbosity and self-preference are the ones to plan for.
Pairwise judge comparisons
When comparing two prompts or models, ask which answer is better on one criterion, then swap the order and only count consistent winners.
Guardrails, security and safety
Prompt injection is unsolved. Cut blast radius with architecture, not a classifier that claims to detect it.
Prompt injection
Untrusted text that the model treats as instructions. Direct injection is in the user message. Indirect injection hides in fetched content.
The lethal trifecta
An agent becomes dangerous when it has private data, untrusted content and a way to send data out. Break any one leg.
Safety controls
Prefer mechanical enforcement over asking the model to behave. Least privilege, confirmation, allowlists and quarantine.
Red teaming LLM apps
Write attacker stories from the trifecta, turn them into eval cases, and retest whenever tools or data sources expand.
Fine-tuning vs prompting vs RAG
When to change weights instead of the prompt or the retrieved context, and how to decide with evals.
Kinds of fine-tuning
SFT teaches an input-to-output map. Preference methods rank answers. Distillation copies a teacher. LoRA makes the update cheap.
Fine-tuning data
Quality and coverage of the examples dominate the training run. Match production inputs and freeze a held-out eval first.
Serving fine-tunes
Managed APIs trade control for speed. Open-weight LoRA trades ops for isolation. Plan for base-model upgrades either way.
Production and case studies
Latency and cost optimization
Streaming, routing, cascades, batching and parallelism: making LLM apps fast and affordable without dropping quality.
LLM latency metrics
Measure TTFT, tokens per second, end-to-end latency and cost per successful task before you change the prompt or the model.
Streaming for perceived latency
Send tokens as they arrive. The model still takes the same time to finish, but users feel time-to-first-token instead of a blank wait.
Reducing LLM tokens
Tokens are both latency and money. Shorten the prompt, cap the output, and drop unused tools before you reach for a new model.
Model routing and cascades
Send easy work to a small model and hard work to a frontier model. A cascade tries cheap first and escalates when a check fails.
Caching for LLM apps
Prompt caching, exact-match and semantic caches: where each fits, and how to avoid serving the wrong answer.
Prompt caching
Providers reuse KV state for an identical prompt prefix. Put static content first. A one-token change early in the prompt misses everything after it.
Exact-match LLM cache
When the full request fingerprint is identical and sampling is deterministic enough, store the completion and skip the model.
Semantic LLM cache
Embed the query, reuse a prior answer if it is close enough. High leverage on public FAQ. Dangerous on anything personal or policy-sharp.
Cache invalidation
Every LLM cache key needs model, prompt, tools, knowledge and tenant. Prefer versioned keys over hoping a TTL saves you.
LLMOps and observability
Tracing, prompt management, feedback loops and online monitoring for LLM applications.
Tracing and logging LLM calls
What to record for each model call, how to build a trace tree for a whole request, and how to keep the logs private.
Prompt versioning
How to version prompts like code, where to keep them, and the rules that let you trace any production answer back to the exact prompt that produced it.
Online evals, feedback and alerts
How to check live traffic with cheap code checks, sampled judges and user feedback, and which signals should page someone when quality drops.
LLM gateways
The proxy between your apps and model providers that centralizes keys, quotas, retries, fallbacks and spend, and the rules that keep retries and fallbacks safe.
Designing AI product experiences
Interaction design for probabilistic systems: trust, control, failure states and human-in-the-loop.
AI interaction models
Chat, inline assist, copilot, autonomous agent or background batch. Pick the shape that matches stakes and how structured the task is.
Calibrated trust
Users over-trust fluent systems. Show limits, citations and honest uncertainty so they rely on the product when it is strong and check it when it is weak.
Designing for AI failure
Assume the model will be wrong. Make correction, undo, partial success and empty retrieval first-class screens, not polish.
Human-in-the-loop
A human approves, edits or takes over before the system proceeds. Use it for irreversible actions and the long tail your evals have not made safe.
Support agent requirements
Write autonomy, safety, handoff, freshness, latency and cost as constraints. Define in-scope and what "resolved" means.
Case study: customer support agent
End-to-end: RAG over help docs, account tools, escalation to humans, evals and cost.
Support agent architecture
A router, a read-only RAG answerer, a bounded tool agent and a handoff pack. Not one free-roaming agent on day one.
Support tools and permissions
Session-scoped reads, propose-then-confirm for money, humans for irreversible actions. Bind identity from the session.
Support evals and cost
Label 200 to 500 real tickets. Gate on policy and never-call cases. The cost model only counts if CSAT holds.
Support agent rollout
Shadow, then FAQ, then reads, then confirmed writes. Keep a kill switch. Staff the desktop so humans improve the bot.
Case study: coding agent
How coding agents work: repo context, edit tools, test loops, sandboxes and review.
Agentic code search
Grep, glob and targeted reads beat dumping a repo or trusting a nearest-neighbor hit that looks relevant and is the wrong module.
Patch edit tools
Unique-match search-and-replace with a clear error beats sloppy full-file rewrites for most coding-agent edits.
Coding agent evals
SWE-bench compares scaffolds. Your own suite catches monorepo conventions, test gaming and over-eager edits.
Coding agent review
Force a branch and a PR. Humans own architecture, security and test integrity. A fresh-context reviewer catches what the author agent missed.
Case study: document extraction pipeline
Structured data from millions of documents: schemas, batch APIs, validation and human review.
Extraction schemas and validators
A versioned JSON schema plus business-rule checks in code. Schema-valid is not the same as a total that adds up.
Extraction tiering and batch cost
At a million documents a month, batch APIs and a cheap-to-frontier model ladder matter more than a single sync call.
Extraction confidence and review
Models are not calibrated out of the box. Route on validators, agreement and a plot you measured, then make correction cheap.
Extraction reprocessing
Treat every extract as a pure function of bytes, schema and extractor version. Re-runs write a new row. Never overwrite a human-approved value in silence.