Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

The AI Stack in One Picture: Six Layers Every AI Product Is Built From

Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.

Chaand Sheikh

·27 November 2026LLM Fundamentals

What you will learn

  • Name the six layers of an AI product: data, model, retrieval, orchestration, serving and ops
  • Explain why evals and security run across every layer instead of sitting at the end
  • Trace one user request through all six layers
  • Describe what an AI engineer builds around the model call, and the four weak spots they design for

Before you start

  • Basic Python
  • A rough idea of what an LLM is

Every AI product, big or small, is built from the same six layers: data, model, retrieval, orchestration, serving and ops. Once you can draw that one picture, every tool you meet later (a vector store, an agent framework, a tracing dashboard) has an obvious place to live.

Let's build the picture slowly, starting with something that has nothing to do with AI.

Think of a restaurant

A dish reaches your table only because six stations work together:

  • The pantry: the ingredients on the shelves.
  • The chef: the skill that can cook pretty much anything.
  • The runner: fetches exactly what this one order needs from the pantry.
  • The head chef: decides the steps and who does what.
  • The waiter: takes the order and brings the plate.
  • The manager: looks after costs, complaints and inspections.

A great chef alone is not a restaurant. In the same way, a great model alone is not a product.

The stack in one picture

Now translate each station into AI terms:

RestaurantLayerWhat lives there
PantryDataPDFs, wikis, support tickets, databases
ChefModelAn LLM behind an API, or open weights you run yourself
RunnerRetrievalEmbeddings, vector search and RAG, which find the right pieces of data for this one question
Head chefOrchestrationPrompts, tools, MCP and agents, which decide what happens in what order
WaiterServingA FastAPI service, streaming and Docker
ManagerOpsTracing, cost, caching and versions
The six-layer AI stack with evals and security across it Data docs, tickets, databases pantry Model API or open weights chef Retrieval embeddings, vector search runner Orchestration prompts, tools, MCP, agents head chef Serving FastAPI, Docker waiter Ops tracing, cost, versions manager Evals and security: across every layer, the whole time
Six layers, and one band underneath all of them. Evals and security are not a seventh box at the end.

Look at that red band. Evals and security are not something you bolt on after the last layer. They run across every layer, the whole time. Start with why you can't ship without an eval and guardrails for LLM agents.

The bottom: data and model

This pair is what you know, and what thinks about it.

Data

  • Sources: documents, tickets, product tables.
  • Clean it: parse PDFs, drop junk, keep useful metadata like the page number.
  • Split it: cut it into chunks small enough to search. See chunking strategies for RAG.

Model

  • Closed: a hosted API. You rent it per token.
  • Open: weights you run on your own machines.
  • Choose by task: quality, speed, cost and privacy.

Most bad answers start right here: wrong data goes in, or the wrong model is picked for the job.

The middle: retrieval and orchestration

Find the right facts, then decide the steps.

Retrieval

  • Embeddings turn text into numbers by meaning, so similar sentences end up close together (what an embedding actually is).
  • Those numbers are stored in a vector store, like Chroma or pgvector (vector databases).
  • To search better, add hybrid search and reranking (hybrid search, reranking).

Orchestration

  • Context: what goes into the prompt, and just as important, what stays out.
  • Tools and MCP let the model call your own APIs (tool use).
  • Agents are multi-step flows, built with a framework such as LangGraph.

This middle part is where most of an AI engineer's day-to-day code sits. The RAG pipeline article walks through retrieval and prompt assembly stage by stage.

The top: serving and ops

Put it in front of users, then keep it healthy.

Serving

  • API: FastAPI endpoints.
  • Streaming: the words appear as they are written, instead of after a long wait.
  • Packaging: Docker, so it runs the same on your laptop and on the server.

Ops

  • Tracing: see every step of every request (LLM observability and tracing).
  • Cost: budgets, caching, and smaller models where they are good enough (caching layers).
  • Versions: prompts, models and indexes are all tracked.

Here's the difference in one line: a prototype stops at the model. A product needs these two layers as well.

One request, through all six

Now follow one real request. A user asks:

Can I expense a second monitor for home?

  1. Serving: the request hits our API.
  2. Retrieval: we search the expense policy for "home office equipment".
  3. Data: the matching policy chunks come back, with their page numbers.
  4. Orchestration: build the prompt. The rules, the chunks and the question, in a clear order.
  5. Model: writes the answer and cites the page it came from.
  6. Ops: log the trace, the tokens and the cost.
One request touches all six layers 1 Serving request hits the API 2 Retrieval search expense policy 3 Data chunks + page numbers 4 Orchestration rules, chunks, question 5 Model answer, cites the page 6 Ops trace, tokens, cost
The order of a request is not the order of the stack picture. Serving comes first, ops comes last, and the model sits near the end.

One small question touched all six layers. And the model only showed up at step five.

What the AI engineer does all day

Think of a bridge going up across a river. The physicist discovers how steel behaves. The structural engineer doesn't invent steel: they know its limits well, design around them, test the load and sign the bridge off as safe. AI research invents the material, the model. The AI engineer is the structural engineer, who builds things that stand up in that material.

The model call is one step out of five

Take an assistant that answers questions from a company's policy documents. An employee asks: how many days of parental leave do I get?

  1. Find: search the right policy pages first, because the model has never seen this company's handbook.
  2. Prompt: put those pages and the question in front of the model, clearly.
  3. Check: is the answer grounded in those pages, and does it cite them? Or did the model just guess?
  4. Serve: wrap it in an API so the HR portal can call it.
  5. Watch: once it runs, keep an eye on cost, speed and bad answers.

The model call is in there somewhere. The other four steps are the job.

What the job is, and is not

AreaThe AI engineer doesLeft to someone else
ModelsPicks a model, calls it well, swaps it when a better one shipsTraining a foundation model from scratch
KnowledgeEmbeddings, vector search and RAG over company dataDesigning new embedding architectures
BehaviourPrompts, context, tools, MCP and agentsProofs about attention
QualityGolden datasets, evals, regression tests in CIChasing a leaderboard
ProductionFastAPI, Docker, tracing, cost guards, securityGPU kernel work

The job is wide, but it's all engineering.

Know the material: four weak spots

Steel bends and concrete cracks, and a good engineer designs around that. An LLM has its own weak spots:

  • It makes things up. So ground it in real documents, and check the answer.
  • It varies from run to run. Same question, slightly different answer. So test with evals, not with one lucky try.
  • It has a limited window. Only so much text fits in one call, so choose carefully what goes into the context.
  • It costs money per token. So cache, trim and track the bill.

For the full list of gaps and their fixes, see What an LLM Can and Cannot Do. For the window and the bill, see LLM Tokens, Context Windows and Cost.

Common mistakes

  • Treating the model as the product. A prototype stops at the model. Users need serving, and you need ops to keep it healthy.
  • Leaving evals and security for the end. They are not a seventh box. Test and protect each layer as you build it.
  • Blaming the model first. Most bad answers start with wrong data going in, or the wrong model for the job.
  • Trusting one good run. The model varies, so one lucky answer proves nothing.

Quick recap

LayerJobIn the second-monitor request
DataWhat you know: sources, cleaned and chunkedPolicy chunks with page numbers
ModelWhat thinks about it: closed API or open weightsWrites the answer, cites the page
RetrievalFind the right facts for this questionSearch for "home office equipment"
OrchestrationDecide the steps and the contextRules, chunks, question in order
ServingPut it in front of usersThe request hits the API
OpsKeep it healthy and affordableLogs trace, tokens and cost
Evals and securityAcross every layerRun at every step, not only at the end

Try it yourself

Pick an AI app you use, like a support chat or a coding assistant. Guess its layers: where does its data come from, and what does it retrieve? Then find the gap: which layer would you not know how to build yet? That's the layer to study next.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 1 of 79

Next post
Tokenization: What an LLM Actually Sees When You Type

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

Tokenization: What an LLM Actually Sees When You Type

A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.

LLM Tokens, Context Windows and Cost: What One Question Really Costs

Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.

What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps

A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.

Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply

An LLM replies with a string. Pydantic turns that string into a typed object or a clear error. Validate a User, generate its JSON Schema, then follow one customer e-mail through a Ticket model where the first reply says refund, fails the check, and the retry fits.

On this page

  • Think of a restaurant
  • The stack in one picture
  • The bottom: data and model
  • Data
  • Model
  • The middle: retrieval and orchestration
  • Retrieval
  • Orchestration
  • The top: serving and ops
  • Serving
  • Ops
  • One request, through all six
  • What the AI engineer does all day
  • The model call is one step out of five
  • What the job is, and is not
  • Know the material: four weak spots
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.