Module 0 · 10 lessons
AI basics, in plain English
How a model learns, then what a prompt, a token, an embedding and RAG are, for someone who has never used an AI API.
Before you start
Nothing else on the platform. This module starts from zero.
Later, to go deeper: Search indexes and autocomplete, LLM serving and retrieval (RAG)
1. What a model is: learned from examples
The picture
A model learns from examples
Training adjusts a model's numbers using marked examples, also called labelled data, and a test on new examples shows whether it learned.
Scene 1 of 5 · Examples, not rules
A spam filter starts from 10,000 emails, each one marked spam or not spam by a person.
- Marked examples — healthy — 10,000 marked emails
- Training — healthy
- The model — healthy
- Your app — healthy
- Examples, not rules. A spam filter starts from 10,000 emails, each one marked spam or not spam by a person.
- Nudge the numbers. Training compares each guess with its mark and shifts the model's numbers towards the right answer.
- Test on new emails. Scored on fresh emails, it is right 96 times in 100, close to its 99 on old ones.
- Memorising is not learning. A model that memorised its examples scores 100 on them but 71 on new ones.
- Inference: use it. Your app sends a new email and gets a label back, and the numbers no longer change.
- Now you try. Pick a task, and see whether it suits plain code or a trained model. For example: Plain code. The rule is known and must be exact every time, so a guess that is usually right is not good enough.
Scene 1 of 5: Examples, not rules. A spam filter starts from 10,000 emails, each one marked spam or not spam by a person.
Key points
- A model's rules come from examples, not from a person writing them.
- Training nudges its numbers until its guesses match the marked answers.
- Only a score on unseen examples shows that it learned.
- Your app runs the finished model; its numbers stay fixed while it answers.
Most software follows rules a person wrote, such as "orders over $50 ship free". A (Building software that learns patterns from examples, instead of following rules a person wrote.) model is different: nobody writes its rules. It learns patterns from many examples.
(The long, costly process in which a model learns from data. It happens before the model is used, not during each request.) shows the model examples, such as emails a person marked as spam or not spam. Examples marked like this are called labelled data. It compares its guesses with the marked answers, and adjusts its internal numbers, called (One of the numbers inside a model that training adjusts. Large language models have billions of them.), so the next guesses are a little better.
Training is slow and costly, and it happens before anyone uses the model. Using the finished model to get an answer is called (Running a trained model to get an answer, as opposed to training it.). Most AI features call a model someone else trained, so they run inference only.
A model is judged on examples it never saw. One that memorised its training examples does well on them and badly on new ones, which is called (When a model memorises its training examples instead of learning the pattern, so it does well on them and badly on new ones.). Where the rules are known and must be exact, such as tax or permissions, plain code is the better tool.
In system design: Treat a model as a part that is usually right, not always. Keep exact rules, such as prices and permissions, in plain code.
Where it goes wrong
- A model trained on old examples drifts as the world changes. A spam filter from last year misses this year's tricks, so test it again on fresh data.
- A model can learn a shortcut instead of the real pattern, such as flagging every email from one domain. Test it on varied examples it never saw.
In an interview
- Say which parts of the design use a model and which stay in plain code, such as prices, tax and permissions. Then say how you measure the model and what happens when it is wrong.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsIntroduction to Machine LearningGoogle for DevelopersWhat it means for a model to learn from examples instead of rules a person wrote.
- Official docsMachine Learning Crash CourseGoogle for DevelopersA free course from Google: training, loss, and checking a model on data it has not seen.
2. What a large language model is
The picture
A model guesses the next piece
A language model scores every piece of text that could come next, then picks one, usually one of the highest scores.
Scene 1 of 5 · Send some words
Send "The capital of France is": the model gives a score to each piece that could come next.
- You — healthy
- Language model — healthy
- Send some words. Send "The capital of France is": the model gives a score to each piece that could come next.
- One piece stands out. "Paris" gets 92 chances in 100, since that pattern filled its training text again and again.
- A fact it never read. Now send "Our shop's refund window, in days, is", a fact about your shop that was never in its training.
- Only a guess. Here "90" leads with only 36 in 100, so another run could as easily write "30".
- It sounds equally confident. Both answers come back in the same confident voice, so a reader cannot spot the guess.
- Now you try. Send different words, and see whether one next piece stands out. For example: Top piece: "blue", with 86 chances in 100. This pattern was common in its training text, so one piece stands far above the rest.
Scene 1 of 5: Send some words. Send "The capital of France is": the model gives a score to each piece that could come next.
Key points
- For any words you send, the model scores what could come next.
- A pattern it read many times in training gets one clear winner.
- A fact it never read gets a likely-sounding guess, with no evidence behind it.
- A guess comes out in the same sure voice as a known fact.
A (A program trained on a huge amount of text to guess the next piece of text. It writes answers one piece at a time.), or LLM, is a program trained on a huge amount of text: books, websites and code. From all that text it learned one skill very well. Given some words, it guesses which piece of text most likely comes next. It picks with a little randomness, so the same question can get different answers.
A chat model then gets a second round of training, on examples of requests paired with good replies, often with people rating its answers. That is why it answers a question instead of only continuing your text.
To write an answer, it makes that guess again and again. It adds one small piece, then guesses the next one, until the answer is complete. That is why answers appear a few words at a time, when the app shows them as they are written.
A model on its own does not look anything up while it writes. It works from what it learned in training and the text you send. It can sometimes work out a fact it was never told. It cannot reliably know your private data or recent news: send that text, or give it a tool to look it up.
In system design: Your backend treats the model as a slow, costly function: text goes in, text comes out. Most of the design work is everything around that call.
Where it goes wrong
- A model learned only from text up to a cut-off date. Ask about anything newer, such as this week's prices, and it guesses unless you send the facts.
- The same (Everything sent to a language model in one request: instructions, context and the question.) can give different answers. A feature that needs one fixed result must check or limit the output.
In an interview
- Treat the model as a slow, costly function that is sometimes wrong. Then name what wraps it: timeouts, checks and a (A simpler answer sent instead of the real one, used when a call is skipped or fails.).
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperLanguage Models are Few-Shot Learners (2020)Brown et al., NeurIPSShows that one model trained to guess the next token can do many tasks from a few examples in the prompt.
- Official docsLLM Course: Transformer modelsHugging FaceWhat a language model is, how it is trained, and what it can and cannot do.
3. What a prompt is
The picture
Three parts, one request
Your backend builds each prompt from instructions, context and a question, then sends it all in one request.
Scene 1 of 5 · The instructions
First come the instructions, which say how to behave: "Answer only from the policy below."
- Instructions — healthy
- Policy — healthy
- Question — healthy
- Your backend — healthy
- Language model — healthy
| Part | Text |
|---|---|
| Instructions (highlighted) | Answer only from the policy below. |
- The instructions. First come the instructions, which say how to behave: "Answer only from the policy below."
- The context. Next comes the context: the shop's refund policy, which allows returns for 30 days.
- The question. Last comes what the customer asked: may they return shoes after 40 days?
- One request. Your backend joins the three parts into one prompt and sends it as a single request.
- Answer from the policy. The model answers from the policy: no, since 40 days is past the 30-day limit.
- Now you try. Choose which parts go into the prompt, and see what the model can answer. For example, tapping "Instructions" and "Question" gives this: A guess: "Yes, returns are fine for 90 days". With no policy in the prompt, the model never saw your rule, so it guesses a common number.
Scene 1 of 5: The instructions. First come the instructions, which say how to behave: "Answer only from the policy below."
Key points
- Instructions say how to behave, such as "use only the policy".
- Context is the material to answer from, such as a document.
- The model sees only what is in this one prompt.
- Leave out the context, and the answer becomes a guess.
A prompt is everything you send to the model in one request. It usually has three parts: instructions that say how to behave, context such as documents or earlier messages, and the question itself.
The model sees only what is in the prompt. It does not remember earlier requests by itself. A chat app that seems to remember is sending the earlier messages again, inside each new prompt. Some provider APIs can store a conversation and add the earlier messages for you: the same work, done on their side.
Better context gives better answers. That is why much of the work in an AI feature is choosing what goes into the prompt, and what stays out.
In system design: Your backend builds the prompt. It decides which documents, user details and limits go in, and it pays for all the text it adds.
Where it goes wrong
- Instructions that pull against each other, such as "be brief" and "explain fully", make answers swing from one to the other. Keep one clear rule for each choice.
- Text pasted into the prompt from users or documents can hold instructions, and the model may follow them. The security module covers this.
In an interview
- Say what goes into the prompt, where each part comes from, and how many (A piece of text that a language model reads or writes, often part of a word. Prices and limits are counted in tokens.) each part may use.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsPrompt engineering overviewAnthropic docs (one provider)What goes in a prompt, and which techniques to try first.
- Official docsMessages APIAnthropic docs (one provider)The exact shape of one request: the system prompt, the earlier turns, and the new message.
4. Tokens: the pieces a model reads
The picture
7 words · 10 tokens · 1.43 tokens per word
At $1 per million input tokens, 1,000 questions like this cost $0.01. Prices vary by model and change often.
What this simplifies. This splitter is written for teaching, with fixed rules for where to cut. Real models learn about 100,000 pieces from data, so they cut in different places. Their counts differ, sometimes a lot for code, numbers or other languages. The rule of thumb still holds: in English, a token is roughly three quarters of a word. The cost counts only the text you typed. A real request also pays for the instructions and documents in the prompt, and for the answer, whose tokens often cost more. A dot (·) marks a space that belongs to the token.
A model reads and writes small pieces of text called tokens. It reads in pieces, not whole words, and a common word is often only one piece. A rare or long word is split into two or more tokens.
Every request counts tokens, and the prompt you send and the answer you get are counted apart. Limits and prices are set per token, so a longer prompt or a longer answer costs and counts for more.
English text averages roughly three-quarters of a word per token, close to 1.33 tokens for every word. This ratio is rough: it shifts with the language, the words used and the model itself.
In system design: Token counts set your prompt budget, your answer length limit and your bill. A backend estimates tokens before sending a request, to avoid errors or surprise costs.
Where it goes wrong
- Many languages need more tokens than English for the same meaning. The same message can then cost more and fill the window sooner.
- Counting words instead of tokens leads to requests that are refused as too long. Use the provider's token counter for exact counts.
In an interview
- Turn users and messages a day into tokens, then into cost and context use, and show the sum.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsSummary of the tokenizersHugging Face Transformers docsHow text is split into tokens, and why a rare word becomes several pieces.
- Official docstiktokenOpenAI on GitHubA real tokenizer you can run to count the tokens in any text.
5. Inside the model: how it picks the next token
The picture
- Tokens — prompt in pieces — healthy — NOW — 5 tokens
- Vectors — numbers per token — healthy
- Attention — weighs past tokens — healthy
- Layers — repeat many times — healthy
- Scores — every known token — healthy
- Tokens
- Vectors
- Weighed mix
- Scores
Step 1 of 6 · Tokens
Done: The prompt is split into 5 tokens
- What happens
- "The cat sat on the" becomes "The", "cat", "sat", "on", "the".
- Why
- A model works on tokens, and each token has its own number in the list of tokens the model knows.
- What changes
- Next, each token becomes a list of numbers.
- Next
- Each token becomes a vector
Event log
5 more to go. Press a line to go back to that step.
Tokens: The·cat·sat·on·the
Step 1 of 6: Tokens. The prompt is split into 5 tokens. "The cat sat on the" becomes "The", "cat", "sat", "on", "the".
What this simplifies. This is a small made-up example. The weights and chances are round values chosen to add up as real ones do, not output from a real model. Real models use thousands of numbers per token and run many attention heads side by side in each layer.
A language model writes one token at a time. For each one, the prompt so far goes through the same parts in order. The model ends with a score for every token it could write next.
First, each token becomes a (A list of numbers. An embedding is a vector.): a list of numbers the model learned in training. Then attention compares the tokens. Each token makes a query, a key and a value. The query of the newest token is matched against the key of every token so far, and the best matches get the most weight.
A layer is one round of attention, plus a network that works on each token alone. A large model stacks dozens of layers. At the end, the vector of the last token becomes a score for every token the model knows. The scores become chances that add up to 100%.
One token is then picked. At (A request setting that controls how much chance goes into picking each next token. Low gives repeatable answers; high gives varied ones.) 0 the top score wins. At a higher temperature the token is drawn by chance, so answers vary. The picked token joins the prompt, and the whole run starts again for the next token.
In system design: Each new token is one more run, so a longer answer takes longer. The (The memory where a model keeps its work on every token so far, so each new token does not redo it. It grows by one token per step.) saves earlier keys and values, which spares work but takes (A graphics processing unit: a chip that does many simple sums at the same time. Language models run on GPUs because they need huge numbers of sums.) memory.
Where it goes wrong
- Attention compares each token with every earlier one, so the work grows faster than the prompt does. Very long prompts are slow to read.
- At temperature 0 the top token wins, but small differences in the server's sums can still change a word now and then.
In an interview
- Explain why a long answer takes longer than a long prompt. The prompt is read in one pass, but each answer token needs its own run.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperAttention Is All You Need (2017)Vaswani et al., NeurIPSThe paper that introduced the transformer: embeddings, attention and the layers a token passes through.
- Official docsLLM Course: How do Transformers work?Hugging FaceThe parts of a transformer in plain terms, with pictures of how attention links tokens.
6. The context window
The picture
One window for prompt and answer
The prompt and the answer share one fixed space, so a long prompt leaves little room to answer.
Scene 1 of 4 · A fixed limit
This example model reads at most 128,000 tokens per request, counting the prompt and the answer together.
- Pages that fit
- about 300
- A fixed limit. This example model reads at most 128,000 tokens per request, counting the prompt and the answer together.
- A long prompt. A prompt of 120,000 tokens leaves room for only 8,000 tokens of answer.
- A whole manual. A 400-page manual is about 170,667 tokens, more than the whole window, so it cannot go in.
- Send what matters. Send only the 20 pages that matter, about 8,533 tokens, and most of the window is free.
- Now you try. Set the prompt size, and see how much room is left for the answer. For example: Room left for the answer: 8,000 tokens. The prompt and the answer share one window, so a shorter prompt leaves more room to answer.
Scene 1 of 4: A fixed limit. This example model reads at most 128,000 tokens per request, counting the prompt and the answer together.
Key points
- A model reads only so many tokens per request.
- The prompt and the answer count against the same limit.
- A document bigger than the window has to be cut down.
- Send only the parts that matter, and room is left over.
A model cannot read an unlimited amount of text in one request. The (The most tokens a model can read at once, counting both the prompt and the answer.) is the most tokens it can read at once, counting the prompt you send and the answer it writes together.
If a document is longer than the context window, it will not fit. It must be shortened, split into pieces, or chosen from carefully, so only the most relevant part is sent.
The size of the window depends on the model. It ranges from a few thousand tokens to a million or more, and many models also set a smaller limit on the answer alone. Check the limits of the model you use.
A bigger context window lets you send more background at once. Sending more text costs more, since you pay for every token the model reads, and a long request can also take longer to answer.
In system design: Your backend keeps the prompt, and any documents it adds, under the model's context window. Going over it means shortening text or sending fewer documents.
Where it goes wrong
- A model may not use every part of a long prompt equally well. Facts in the middle are missed more often, so put key facts near the start or the end.
- Filling the window costs money and time on every call, even when a short passage would have answered the question.
In an interview
- Say how you would handle a document too big for the window. Search for the parts that matter, summarise, or split the job into several calls.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsContext windowsAnthropic docs (one provider)How the prompt and the answer share one token limit, and what happens when a chat outgrows it.
- Research paperLost in the Middle: How Language Models Use Long Contexts (2023)Liu et al., TACLModels use facts at the start or end of a long prompt better than facts in the middle.
7. Why models make things up
The picture
A wrong guess, said with confidence
With no source in the prompt, a model fills the gap with a likely guess that sounds every bit as sure as a fact.
Scene 1 of 5 · Only the question
The bot sends the model only the customer's question, with no refund policy in the prompt.
- Customer — healthy
- Support bot — healthy
- Language model — healthy
- Refund policy — healthy
| What the prompt held | Answer |
|---|---|
| The question only (highlighted) | not yet |
- Only the question. The bot sends the model only the customer's question, with no refund policy in the prompt.
- A likely number. The model writes "90 days", because that is a common refund window in its training text.
- Fluent but false. This is a hallucination: the answer sounds sure, but the real policy says 30 days.
- Add the policy. Now the bot puts the real policy in the prompt, with a rule to answer only from it.
- The true answer. The model answers 30 days and names the policy as its source, so anyone can check it.
- Now you try. Choose what the bot sends, and see what the model answers. For example: The bot answers "60 days", but the real policy says 30 days. Sources stop guessing only when they are right: an out-of-date policy gives a sure but wrong answer.
Scene 1 of 5: Only the question. The bot sends the model only the customer's question, with no refund policy in the prompt.
Key points
- The model judges what sounds likely, not what is true.
- A missing fact gets filled with a common guess.
- Real sources in the prompt, plus a rule to use them, cut this down.
- The source must be current, or the answer is wrong in a new way.
A model writes by guessing the next likely piece of text, one piece at a time. It has no built-in way to check whether a sentence is true; it only judges whether the words sound likely.
Without the right information in the prompt, the model can still write a fluent, confident sentence that is false. This is called a (A false statement a model writes as if it were true. It happens because the model guesses likely text and has no built-in fact check.): a false statement written as if it were true.
A hallucination is not a lie, since lying needs intent, and the model has none. It is a wrong guess, stated in the same confident voice the model uses for a correct answer.
Four habits cut this down. Give the model real sources in the prompt, and tell it to answer only from them. Ask it to cite which source each claim came from, and check its answers before a user sees them.
In system design: Any feature that answers from company data needs sources in the prompt and an instruction to use only them. It also needs citations and answer checks.
Where it goes wrong
- An out-of-date source in the prompt gives a sure but wrong answer, so keep sources current.
- A model can cite a source that does not say what it claims. Check that each quoted line really appears in the passage it cites.
In an interview
- Do not claim made-up answers can be removed. Say how you make them rarer and how you catch the rest: sources, citations and checks.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperWhy Language Models Hallucinate (2025)Kalai et al., OpenAIArgues that training and grading reward a guess over saying “I don’t know”.
- Official docsReduce hallucinationsAnthropic docs (one provider)Steps that lower the risk: allow “I don’t know”, ask for quotes, check the answer against them.
8. Embeddings: meaning as numbers
The picture
Search by meaning (closest 3)
- I was charged twice for the same order this month.closeness 0.90 out of 1, an example score
- My package arrived damaged and I need a refund for it.closeness 0.86 out of 1, an example score
- The item does not match the listing, so I'd like a reimbursement.closeness 0.84 out of 1, an example score
Search for the same words
No sentence shares a word with "I want my money back".
Closest by meaning: I was charged twice for the same order this month.; My package arrived damaged and I need a refund for it.; The item does not match the listing, so I'd like a reimbursement..
- Signing in
- Refunds
- Delivery
- Closing an account
What this simplifies. Real embeddings have hundreds of numbers, not two, and a model computes them; this map was placed by hand to show the idea. Real systems usually compare two lists of numbers by the angle between them, but the idea is the same: close means similar in meaning. "Search for the same words" is also a crude stand-in. It matches exact word forms of four or more letters, with no ranking, so "refund" does not match "refunds".
Step through one search
The map above shows the result. This shows the work behind it: the text becomes a vector, and the vector is compared with every stored ticket.
Every ticket the index returns is shown.
Predict first: how many tickets come back with these settings? Step through to check.
- User — healthy
- Application — runs each step — healthy — NOW — has the question
- Embedding model — text to vector — healthy
- Vector index — 24 ticket vectors — healthy
- Text
- Answer
- Search by vector
Step 1 of 8 · Application
Done: The user asks a question
- What happens
- The user types a question: "I want my money back"
- Why
- The application holds 24 old support tickets. It wants the ones that mean the same as this question.
- What changes
- The application has the question as text. Text cannot be compared by meaning yet.
- Next
- The embedding model turns the text into a vector
Event log
7 more to go. Press a line to go back to that step.
The map: each ticket's vector as a place
- Signing in
- Refunds
- Delivery
- Closing an account
Closest tickets
The question has no vector yet, so nothing can be compared.
Step 1 of 8: Application. The user asks a question. The user types a question: "I want my money back"
Things to try
- Pick "Can you check on my delivery and process my refund?". It asks about two things. See which one the search finds.
- Pick "How do I close the delivery window?" and ask for 5 tickets. One of them is about something else.
- Keep that question and set the minimum closeness to 0.85. Count how many tickets are left.
- Set the minimum to 0.90 and try each question. Find one where nothing is shown.
What this simplifies. A real embedding model works out hundreds of numbers for a text. Here each place was set by hand and has two numbers. The score is an example made from the distance on this map; real systems often use the angle between two vectors. This index scores all 24 tickets. A real index holds millions of vectors and skips most of them, so it can miss a close one now and then. A good minimum score depends on the embedding model and has to be found by testing.
An (A list of numbers that stands for the meaning of a piece of text. Texts with similar meanings get similar lists.) model turns a piece of text into a list of numbers called an embedding. It does not write answers. Many apps call a separate embedding model for search, apart from the model that writes answers. The exact set-up depends on the system.
Texts with a similar meaning get embeddings that land close together, even when they share no words at all. Texts with different meanings get embeddings that land far apart.
This lets software compare meaning with plain arithmetic: measuring the distance between two lists of numbers, instead of matching exact words. It says nothing about whether either text is true. Close also means the same topic, not the same claim: "refunds are allowed" and "refunds are not allowed" can land close together.
In system design: Your backend calls an embedding model once per (A short passage cut from a longer document, so it can be turned into an embedding and found on its own.), a short passage cut from a document. It calls it again for each question, then compares the numbers.
Where it goes wrong
- Embeddings from two different models cannot be compared. Mixing them in one (An extra structure, kept sorted or grouped, that lets a database find matching items without reading all of them.) gives matches that make no sense.
- Close in meaning is not the same claim. A question about refunds may match a page that says refunds are not allowed.
In an interview
- Say which embedding model embeds both the documents and the questions, and how you would test a switch to a new one.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsEmbeddingsGoogle Machine Learning Crash CourseHow items become lists of numbers, so similar items end up close together.
- Research paperSentence-BERT: Sentence Embeddings using Siamese BERT-Networks (2019)Reimers and Gurevych, EMNLPA model built to turn a whole sentence into one vector for search by meaning.
9. Vector databases: search by meaning
The picture
Search by meaning, fast
A vector database skips most of the work: one common kind of index sorts meanings into groups, then checks only nearby groups.
Scene 1 of 5 · Meanings stored
The database holds 2,000,000 help articles, each stored as an embedding of its meaning.
- Help app — healthy
- Vector database — healthy — 2,000,000 articles
- True closest article found?
- not shown yet
- Meanings stored. The database holds 2,000,000 help articles, each stored as an embedding of its meaning.
- Check every one. Comparing the question with every article finds the true closest one, but takes 2,000,000 checks.
- Sort into groups. Ahead of time, one common kind of index sorts the articles into 1,000 groups of similar meaning.
- Check nearby groups. It finds the 2 nearest groups, then checks their articles: 5,000 checks in all, 400 times fewer.
- Now and then, a miss. Checking only the single nearest group is faster still, but here the closest article sat in the next one.
- Now you try. Choose how much to check, and see the work and whether the closest article is found. For example: 17,000 checks; the true closest article was found. That is 118 times less work than checking everything, and it still finds the closest one here.
Scene 1 of 5: Meanings stored. The database holds 2,000,000 help articles, each stored as an embedding of its meaning.
Key points
- Each stored item is an embedding: a list of numbers for its meaning.
- Checking every item is exact, but slow with millions of them.
- An index checks only a few nearby groups, far faster.
- Now and then the closest item sits in a group it skipped.
A (A database that stores vectors and finds the ones closest to a given vector, so you can search by meaning.) stores embeddings, the lists of numbers that stand for meaning, and finds the ones closest to a given embedding. A list like this is also called a vector. This lets an app search by meaning instead of by exact words.
Comparing a question's embedding against every stored item works, but it turns slow once there are millions of them. Checking each one, one at a time, does not scale.
Most vector databases use (Finding the stored vectors closest to a question's vector. The approximate kind checks only part of the data. It is much faster, but now and then it misses a close match.) instead: it checks only part of the data, so it runs much faster. Now and then, it misses a match that was truly closest.
In system design: A vector database sits beside your normal database. Your backend embeds the question, asks the vector database for the closest matches, then fetches the full text for each one.
Where it goes wrong
- Approximate search can miss the true closest match. Measure how many of the right matches it finds on real questions, and tune the index.
- Filtering after the search, such as by customer, can leave too few results. Filter inside the search where the database allows it.
In an interview
- Give the number of vectors, how fast a search must be, and how the index trades finding every match for speed.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperEfficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (2016)Malkov and Yashunin, IEEE TPAMIThe graph index most vector databases use to find close vectors without comparing every one.
- Official docspgvectorpgvector on GitHubVector search inside PostgreSQL: storing embeddings, distance types, and exact versus fast search.
10. RAG: look it up, then answer
The picture
- FindSearch your own documents by meaning for passages that match the question.
- Build the promptPut the instructions, those passages and the question together.
- AnswerThe model writes its answer, told to use only those passages.
Runs for every question a user asks.
On: the search returns 5 chunks, and a second check picks which to keep.
- User — healthy — NOW
- Application — runs each step — healthy
- Language model — writes the answer — healthy
- Embedding model — text to vector — healthy
- Vector index — chunks and vectors — healthy
- Reranker — turned off — IDLE
- Request
- Search
- Response
Step 1 of 6 · User
Done: The user asks a question
- What happens
- The user sends a question to the application.
- Why
- The model was not trained on this shop's help pages. The application has to look the answer up first.
- What changes
- The application now holds the question: "Can I return a sale item after 20 days?"
- Next
- Turn the question into a vector
Event log
5 more to go. Press a line to go back to that step.
The chunks found, the prompt and the answer show here as the run reaches them.
Step 1 of 6: User. The user asks a question. The user sends a question to the application.
Things to try
- Keep 1 passage for the sale question. The closest chunk is the 30-day rule, so the answer is wrong.
- Now turn the reranker on. The 14-day chunk moves to place 1 and the answer is right again.
- Ask about price matching. The pages do not cover it, yet the search still returns its closest chunks.
- Set the chunk size to 4 sentences. Whole pages go into the prompt, and its size grows.
- Ask about Canada with chunks of 2 sentences and keep 1. The Canada sentence shares a chunk with the address rule, which pulls that chunk away. The chunk that says 3 to 5 days wins, so the answer is wrong.
- Now keep 2 chunks, or turn the reranker on. The Canada chunk reaches the prompt and the answer is right.
What this simplifies. The help pages, the map places and the answers are made up for teaching. A real embedding has hundreds of numbers, worked out by a model. Here a chunk's place is the average of its sentences' places, which were set by hand. The reranker uses grades set by hand, where a real one is a second model. The answer follows a fixed rule: it is right when the passage with the answer is in the prompt. A real model usually follows its passages, but not always. Token counts come from this track's teaching splitter.
(Looking up relevant documents first and putting them in the prompt, so the model answers from them instead of from memory alone.), or RAG, answers questions from your own documents instead of from the model's memory alone. It works in three steps: find, build the prompt, and answer.
First, the app searches your documents by meaning for the passages that match the question, using the embeddings from the last two lessons. Only the closest few are kept.
Second, the app builds a prompt from the instructions, those passages and the question. Third, the model writes its answer, told to use only those passages. It usually does, but not always, so answers still need checks.
RAG is the most common way to give a model your own data. It needs no retraining, and an answer can point back to the real passages it was built from. The answer is only as good as the search: given the wrong passage, the model answers from that.
In system design: RAG adds document search before every model call. Cutting text into chunks (short passages), embeddings, a vector database and prompt limits all become part of your system's design.
Where it goes wrong
- The search returns the wrong passages, and the model answers from them with confidence. Measure the search on its own.
- The index falls behind the documents, so answers quote old prices or pages that were deleted.
In an interview
- Draw two paths: indexing documents ahead of time, and the question path at request time. Then say how each one fails.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)Lewis et al., NeurIPSThe paper that named RAG: fetch passages first, then write the answer from them.
- Engineering guideIntroducing Contextual RetrievalAnthropic engineering blogA real RAG design and measured gains from adding context to each chunk and mixing in word search.