LLM System Design ยท Chapter 1

The Building Blocks of LLM Systems

SA
Shivank AgarwalFuture with Shivank

Before we design big AI products like coding assistants or learning apps, we need to understand the small pieces they are made of: tokens, embeddings, prompts, context windows, RAG, agents and a few more. Think of this chapter as learning the alphabet before writing sentences.

You do not need any AI background to read this. If you can write a little Python and know what an API is, you are ready. Every idea comes with an everyday analogy, a real product where you have already seen it, and a worked example.

By the end of this chapter you will be able toโ€ฆ

๐Ÿง  Think of it likeโ€ฆ an everyday analogy
๐ŸŒ Real-world example where you have already seen this
๐Ÿ” Worked example step by step, with real values
โš ๏ธ Watch out a common mistake beginners make
๐ŸŽฏ Interview tip a line you can say in an interview
๐Ÿš€ Going deeper optional, for the curious
๐ŸŽฎ Try it an interactive demo you can click
About the code in these notesCode examples use the OpenAI Python SDK with real model names that are current at the time of writing (November 2026): gpt-6-astra (most capable), gpt-6.1-terra (fast and balanced), gpt-6-luna (cheapest, for high volume) and text-embedding-3-small for embeddings. Each example shows the output you would see, so you can follow along just by reading. Model names change every few months; the ideas do not.

Chapter 1 ยท The Building Blocks of LLM SystemsTokens ยท embeddings ยท prompts ยท context ยท RAG ยท agents ยท metrics ยท failure modes

1.1 A new way of thinking: from "always the same" to "probably right"

Almost all the software you have written so far is deterministic. That is a fancy word for a simple idea: the same input always gives the same output. If add(2, 2) returns 4 today, it will return 4 tomorrow and a million times after that. A unit test that passes once will pass forever.

Large Language Models (LLMs) break this rule. They are probabilistic: give the same input twice and you may get two different answers. Usually both are fine. Sometimes one is wrong. Our job as engineers is to build a system around the model that turns this "probably right" behaviour into something users can depend on. That is what this whole series is about.

Same input, different outputs
Traditional software (deterministic)
Input: 2 + 2
Always 4 โœ…

A calculator, a bank balance check, a sorting function.

LLM (probabilistic)
Input: "Write a tagline for a chai shop"
"Sip the moment.""Your daily dose of warmth.""Best coffee in town!" ๐Ÿค”

Each run can differ, and one run can even be wrong.

So what exactly is an LLM?

A Large Language Model is an AI model that has read an enormous amount of text and code (books, websites, documentation, code repositories) and learned the patterns of language from it. Because of that, it can write, summarise, translate, answer questions, reason through problems and write code. Popular examples are GPT (by OpenAI), Claude (by Anthropic), Gemini (by Google), Llama (by Meta), DeepSeek and Grok. Each has its own strengths, such as reasoning, creativity, speed or price.

You talk to an LLM by sending it text called a prompt. It replies with text. Good prompts include clear instructions and guardrails (rules about what not to do) so the reply is what you expect.

๐Ÿ” Worked example: your first LLM call

Here is the smallest useful program. We send one prompt and print the answer.

from openai import OpenAI
client = OpenAI()   # reads your OPENAI_API_KEY from the environment

reply = client.chat.completions.create(
    model="gpt-6.1-terra",
    messages=[{"role": "user", "content": "Write a 5-word tagline for a chai shop."}],
)
print(reply.choices[0].message.content)

Output (run 1): Sip slowly. Smile widely. Repeat.
Output (run 2): Fresh chai, warm conversations daily.

Same code, same prompt, two different answers. That is the probabilistic nature in action.

๐Ÿง  Think of it likeโ€ฆA calculator is like a government form: fixed rules, fixed result. An LLM is like a very well-read friend. Ask them the same question twice and they will phrase the answer differently, and once in a while they will confidently say something wrong. You would not fire such a useful friend; you would build habits around them: give them the right notes, double-check important facts, and keep a backup plan. That is exactly what LLM system design is.
๐ŸŒ Real-world exampleWhen you chat with a food-delivery app's support bot and it says "Your refund of โ‚น249 has been processed", that answer did not come from the LLM's memory. The system looked up your order in a database, gave those facts to the LLM, and asked it to write a friendly reply. The LLM is only one part of a bigger system. You will see this pattern again and again.

1.2 Where LLMs fit: the AI family tree

People use words like AI, ML, deep learning and GenAI as if they mean the same thing. They don't. The picture below shows how they nest inside each other, like Russian dolls.

The AI family (each circle sits inside the bigger one)
Artificial Intelligence (AI) Any machine that does "smart" things Machine Learning (ML) Learns patterns from data instead of hand-written rules Deep Learning (DL) Many-layered neural networks; great with images, audio, text Generative AI Creates new text, images, audio NLP Understanding human language (older field) LLMs & SLMs where GenAI meets NLP
LLMs sit where "generating new content" overlaps with "understanding human language".
TermWhat it means in plain wordsEveryday example
AI (Artificial Intelligence)The big umbrella: any computer system that does tasks we think need intelligence: learning, reasoning, understanding language, seeing.Google Maps choosing the fastest route
ML (Machine Learning)A part of AI where we don't write the rules ourselves. We show the system many examples and it learns the rules.Gmail's spam filter learned from millions of emails marked "spam" / "not spam"
Deep LearningA part of ML that uses neural networks with many layers. It can learn directly from messy, raw data like photos, sound and text.Face unlock on your phone; voice typing
Generative AIModels that don't just analyse data but create new content (text, images, music, video) that never existed before.ChatGPT writing an essay; an app turning your selfie into a cartoon
NLP (Natural Language Processing)The field focused on making computers understand and produce human language. It existed for decades before LLMs.Google Translate; autocorrect
LLM (Large Language Model)A huge, general-purpose language model trained on a big part of the internet. A jack-of-all-trades.Ask it for a poem, a legal summary, Python code or history facts
SLM (Small Language Model)A compact model trained on smaller, focused, high-quality data (support chats, medical notes). It has millions to a few billion "parameters" (learned numbers) instead of hundreds of billions. Cheaper, faster, and small enough to run on a phone, laptop or car.Smart reply suggestions on your phone that work even offline
๐Ÿ” Worked example: rules vs learning (the heart of ML)
Old way: you write the rules
def is_spam(email):
    if "lottery" in email: return True
    if "free money" in email: return True
    return False
# Spammers write "l0ttery" โ†’ rule fails
ML way: the model learns the rules
# Show 1 million labelled examples:
#  "You won a l0ttery!!"   โ†’ spam
#  "Meeting moved to 3pm"  โ†’ not spam
model.fit(emails, labels)
model.predict("Claim your fr33 prize")
# โ†’ spam (it learned the pattern itself)
๐Ÿง  Think of it likeโ€ฆAn LLM is like the senior general physician at a big multi-speciality hospital: knows a bit about everything, but the consultation is expensive and you may wait in a queue. An SLM is like the dentist in your neighbourhood: only handles teeth, but is quick, cheap and right next door.

1.3 The big picture: the parts of an LLM system

Here is a map of every concept in this section. Don't try to memorise it now; we will walk through each box one by one. Notice the three layers: first the language the model speaks (tokens and embeddings), then how the brain is built (training), and finally how you use it (prompts, context, reasoning, search).

Concept map of an LLM system
โ‘  The language of AI
Tokensthe smallest pieces of text
turned into
Embeddingsnumbers that capture meaning
โ‘ก Building the brain (done once, by the model company)
Pre-traininggeneral knowledge
then
Fine-tuningspecialist knowledge
โ‘ข Using the brain (done every time a user asks something)
Promptyour input
improved by
Prompt engineeringwriting better input
fits into
Vector searchfinds helpful facts
adds facts into
Context windowshort-term memory
used for
Reasoninglogic โ†’ answer
Language โ†’ building the brain โ†’ using the brain.

๐Ÿงฉ Tokens: the Lego bricks of text

An LLM does not read words the way you do. It reads tokens: small chunks of text, often a whole short word, sometimes part of a long word, sometimes a single punctuation mark. Splitting text into tokens is called tokenization. Each token is then turned into a number (its token ID), because computers only work with numbers.

๐Ÿ” Worked example: how a sentence becomes tokens
TextTokens (roughly)Token IDs (illustrative)
The cat sat on the mat.The cat sat on the mat .[791, 8415, 7731, 389, 279, 5634, 13]
unbelievableun believ able[359, 32927, 481]
BengaluruBeng al uru[33, 1286, 5797]

Notice three things: (1) common words are usually one token; (2) long or rare words get split into pieces; (3) the space before a word is often part of the token. A handy rule of thumb for English: 1 token โ‰ˆ 4 characters โ‰ˆ ยพ of a word. So 1,000 words โ‰ˆ 1,300 tokens. Languages like Hindi or Tamil usually need more tokens for the same sentence, which makes them a bit slower and costlier to process.

๐ŸŽฎ Try it: tokenize your own sentence

Type anything. This is a simplified tokenizer for learning. Real tokenizers (called BPE, Byte-Pair Encoding) use a learned vocabulary, but the idea is the same.

Why should a system designer care about tokens? Because tokens decide three very practical things: how fast the answer comes, how much you pay, and how much you can send at once.

โฑ Speed (latency)
The model reads all your input tokens together, in parallel, which is fast. But it writes its output one token at a time, because each new token depends on the ones before it. Generating 500 tokens takes much longer than reading 500 tokens. Want faster answers? Ask for shorter answers.
๐Ÿ’ธ Cost
LLM companies charge per million tokens, with output tokens usually costing several times more than input tokens. Sending a 2,000-token prompt just to answer "yes or no" is like hiring a taxi to cross the road. Keep prompts lean, and reuse (cache) anything you send repeatedly.
๐Ÿ“ Size limit
Every model has a maximum number of tokens it can handle at once, called its context window (for example 128K or 400K tokens). You cannot paste a user's entire year of chat history into every request, so you need strategies like the two in the demo below.
๐Ÿง  Think of it likeโ€ฆIn an exam you read the whole question paper in a minute (input, parallel), but you write the answer word by word (output, one at a time). That is why a short answer finishes the exam faster. And like an auto-rickshaw that charges per kilometre, an LLM charges per token. A long detour costs real money. ๐Ÿ›บ
๐Ÿ” Worked example: what does a support bot cost per month?

Say your app's support bot handles 10,000 chats a day. Each chat sends about 1,500 input tokens (instructions + history + question) and gets back 300 output tokens. Assume an illustrative price of $1 per million input tokens and $4 per million output tokens (real prices vary by model).

StepCalculationResult
Input tokens per day10,000 ร— 1,50015 million
Output tokens per day10,000 ร— 3003 million
Daily cost15 ร— $1 + 3 ร— $4$27 / day
Monthly cost$27 ร— 30โ‰ˆ $810 / month

Now imagine someone adds a 3,000-token "company policy" document to every prompt. Input jumps to 4,500 tokens per chat and the monthly bill nearly triples on the input side. This is why engineers watch tokens closely.

Two ways to handle a long conversation
๐ŸŽฎ Try it: the window can hold only 2 messages. Press "Send next message" and compare the two strategies
Strategy A: Sliding window
Keep only the newest messages; drop the oldest.
Strategy B: Summarization
Squeeze older messages into a short summary.
Sliding window is free but forgets. Summarization remembers the gist but costs one extra (cheap) LLM call to write the summary.
๐ŸŒ Real-world exampleChat assistants quietly do this. When a conversation gets very long, older turns are summarised ("User is planning a Manali trip for 4 people in December, budget โ‚น60K, wants a hotel near Mall Road") so the model still "remembers" the important parts without paying for every old message again.

๐Ÿ“ Embeddings: a GPS address for meaning

Tokens tell the model what text it has. Embeddings capture what the text means. An embedding is a list of numbers (called a vector) that represents the meaning of a piece of text, an image or code. The magic property: texts with similar meaning get vectors that are close to each other, even if they share no words at all.

This is very different from normal search. A normal search (like a dictionary lookup or SQL WHERE name = 'x') needs an exact match. With embeddings we can find the nearest neighbours: things that are conceptually related. Search "how to combine numbers" and you can find a function called sum().

Similar meanings live close together
Neighbourhood: maths Neighbourhood: login & security calculate sum add password auth login User question: "How to combine numbers?" Very close โ†’ returned โœ… Far away โ†’ ignored โŒ
"combine numbers" shares no words with "add" or "sum", yet its meaning lands in the maths neighbourhood.
๐Ÿ” Worked example: measuring "closeness" with cosine similarity

Real embeddings have hundreds or thousands of numbers. Let's use tiny 3-number vectors so we can do the maths by hand. Imagine each number measures one "feature": [is it food?, is it sweet?, is it a vehicle?]

WordVector
gulab jamun[0.9, 0.9, 0.0]
rasgulla[0.9, 0.8, 0.1]
scooter[0.0, 0.1, 0.9]

Cosine similarity measures the angle between two vectors. 1 means "pointing the same way" (same meaning), 0 means "unrelated". The formula is: multiply matching numbers and add them up (the dot product), then divide by the lengths of both vectors.

gulab jamun vs rasgulla: dot = 0.9ร—0.9 + 0.9ร—0.8 + 0ร—0.1 = 1.53. Lengths โ‰ˆ 1.273 and 1.208. Similarity = 1.53 รท (1.273 ร— 1.208) โ‰ˆ 0.99 โ†’ almost the same meaning โœ…
gulab jamun vs scooter: dot = 0 + 0.09 + 0 = 0.09. Similarity โ‰ˆ 0.09 รท (1.273 ร— 0.906) โ‰ˆ 0.08 โ†’ unrelated โŒ

A vector database does exactly this, just with 1,536 numbers per vector and millions of vectors, using clever shortcuts to stay fast.

๐Ÿ” Worked example: getting a real embedding
emb = client.embeddings.create(
    model="text-embedding-3-small",
    input="How do I reset my UPI PIN?",
)
vector = emb.data[0].embedding
print(len(vector))      # how many numbers?
print(vector[:5])       # first five numbers

Output:

1536
[0.0183, -0.0421, 0.0067, 0.0294, -0.0110]

Each sentence becomes 1,536 numbers. You will never read these numbers yourself. You store them and let the database compare them.

๐Ÿง  Think of it likeโ€ฆEvery word has an address in a "city of meaning". Samosa, kachori and pakora all live on the same street (Snacks Lane). Password, login and OTP live in a different colony (Security Nagar). When someone asks "what goes well with evening chai?", the system walks to Snacks Lane, even though the word "samosa" never appeared in the question. ๐Ÿ˜๏ธ
๐ŸŒ Real-world example"Customers who viewed this also viewedโ€ฆ" on shopping sites, "songs like this" on music apps, and searching your phone's photo gallery for "beach" all use embeddings. None of those photos are labelled "beach"; the meaning is in the vectors.

How many numbers should a vector have? More numbers (say 3,072 instead of 1,536) can capture finer shades of meaning, but they also take more storage and make search slower. The rule: pick the smallest size that meets your accuracy needs.

๐Ÿš€ Going deeper: storage mathsEach number is usually stored as a 4-byte float. One 1,536-number vector = 1,536 ร— 4 โ‰ˆ 6 KB. Ten million document chunks โ‰ˆ 61 GB of raw vectors, before any index overhead. Double the dimensions and you double that. So "how many dimensions?" is really a question about RAM, cost and speed, not only accuracy.

๐Ÿซ Pre-training and ๐ŸŽ“ fine-tuning: how the brain is built

Pre-training = going to school
The first and most expensive stage. The model reads a massive snapshot of the internet: books, articles, websites, code. It is not trained for any one job. Instead it learns the basics of language and the world:
  • how grammar works
  • what words mean
  • how words and ideas connect
  • common facts about the world
  • the usual patterns of sentences
This costs tens of millions of dollars and months of computing, so only a few companies do it.
Fine-tuning = specialist coaching
Take the pre-trained model and train it a little more on a small, focused dataset so it becomes an expert in one area: your company's jargon, a particular writing style, or rules of a field like medicine or law.

Fine-tuning is thousands of times cheaper and faster than pre-training from scratch, because the model already knows the language; you are only adjusting it slightly.
How fine-tuning works
1. Pre-trained modelGeneral modelknows language & world facts
2. Your special dataFocused datasete.g. 2,000 example support replies
both go into
3. Training runSmall adjustmentsupdates the model's weights slightly
4. ResultFine-tuned specialistspeaks in your style
A general doctor + cardiology training = a cardiologist.
๐Ÿ” Worked example: what fine-tuning data actually looks like

Fine-tuning data is just many examples of "when the user says this, reply like that". Each line is one example in JSON:

{"messages": [
  {"role": "system", "content": "You are BankBuddy. Be polite, brief, never promise timelines."},
  {"role": "user", "content": "my card got blocked why"},
  {"role": "assistant", "content": "Sorry about that! Cards are usually blocked after 3 wrong PIN attempts. You can unblock it in the app under Cards โ†’ Manage."}
]}

Give the model a few thousand of these and it learns BankBuddy's tone and format.

โš ๏ธ Watch out: fine-tuning is not the best way to teach new factsBeginners often think "my model doesn't know our 2026 price list, so let's fine-tune it". Fine-tuning can add knowledge, but facts change often and the model may still mix up old and new. For fresh or changing facts, it is more reliable to fetch them at question time and give them to the model (this is called RAG, section 1.6). Use fine-tuning for style, format, tone and jargon.
Easy rule: Facts โ†’ RAG. Behaviour โ†’ fine-tuning.

1.4 Prompts: how we talk to the model

A prompt is everything you send to the model: the instruction, question, background text and examples. The quality of the answer depends heavily on the quality of the prompt. A simple prompt is just a question ("What is compound interest?"). A well-built prompt has four parts:

Anatomy of a structured prompt
1. PersonaWHO should the model be?
"You are a friendly personal-finance teacher."
2. ContextWHY / background
"The user is a 22-year-old who just got their first salary. Focus on safe options."
3. InstructionWHAT to do
"Explain compound interest using a โ‚น5,000 monthly SIP example."
4. FormatHOW the answer should look
"Reply as JSON with a 'summary' and exactly 3 'tips'."
PartWhat it doesExample
InstructionThe actual command"Summarize the following meeting notesโ€ฆ"
ContextBackground the model needs to do the task well"โ€ฆThese are notes from a sprint planning meeting. Focus only on action items and owners."
PersonaWho the model should act as; this changes tone and depth"You are a senior engineering manager writing for new joiners."
FormatThe exact shape of the output, so your code can use it"Return a JSON list of {owner, task, due_date}."
๐Ÿ” Worked example: the four parts in real code

In code, the persona and rules usually go in the system message (instructions from you, the developer), and the user's request goes in the user message.

reply = client.chat.completions.create(
    model="gpt-6.1-terra",
    messages=[
        {"role": "system", "content":
            "You are a friendly personal-finance teacher. "          # persona
            "The user just got their first salary; suggest only safe options. "  # context
            "Reply ONLY as JSON: {\"summary\": str, \"tips\": [3 strings]}"},  # format
        {"role": "user", "content":
            "Explain compound interest with a โ‚น5,000 monthly SIP example."},  # instruction
    ],
)
print(reply.choices[0].message.content)

Output:

{"summary": "Compound interest means you earn returns on your returns. If you invest โ‚น5,000 every month at 12% a year, after 10 years you will have put in โ‚น6 lakh but could have about โ‚น11.6 lakh.",
 "tips": ["Start early: time matters more than amount.",
          "Don't stop the SIP when markets fall.",
          "Increase the SIP amount when your salary rises."]}

Because we asked for JSON, our app can read tips directly and show them as a neat list. No messy text parsing.

๐Ÿง  Think of it likeโ€ฆOrdering on a food app with "anything is fine" gets you anything. Ordering with "I'm vegetarian (context), I want something North Indian (persona of the cuisine), one paneer dish (instruction), half portion, less spicy, no onion (format)" gets you exactly what you want. ๐Ÿฒ

๐Ÿง  The context window: the model's short-term memory

The context window is the maximum number of tokens the model can "see" in one go. Think of it as its working memory. Everything you send AND everything it writes back must fit inside this window. That includes:

The model has no memory between requests. Every single call, you must send everything it needs to know again. If the conversation grows beyond the window, the oldest parts are simply cut off, and the model "forgets" them.

How a 128K-token window gets used in one request (example budget)
Sys
Chat history 28K
Retrieved documents 60K
Reply
Free space
๐ŸŸช System prompt ~5K๐ŸŸจ History ~28K๐ŸŸฉ Documents ~60K๐ŸŸฅ User question ~1K๐ŸŸข Space kept for the reply ~8Kโฌœ Unused ~26K
Engineers plan this budget like a monthly salary: every section gets a limit.
๐Ÿง  Think of it likeโ€ฆIn the film Ghajini, the hero can only remember the last 15 minutes. To get anything done he keeps photos, notes and tattoos in front of him. An LLM is the same: each request, you must put the important notes in front of it. Or think of an exam where you may bring one A4 cheat sheet but not the whole textbook. Choosing what goes on that sheet is a real skill.

๐Ÿค” Reasoning: how the model "thinks"

Reasoning means taking information, working through it logically, and reaching a new conclusion. In an LLM, reasoning is an emergent ability: nobody programmed it directly. The model is trained only to predict the most likely next token, but after seeing billions of examples of explanations, proofs and step-by-step solutions, it learned to imitate how people reason.

One powerful trick is chain-of-thought: the model writes out its thinking step by step before giving the final answer. Modern "reasoning models" do this automatically and can also decide to use tools (like web search) in the middle of thinking.

๐Ÿ” Worked example: a model planning before it answers

Prompt: "Plan a 2-day Jaipur trip for a family of 4 under โ‚น20,000."

Thought: The user wants a budget plan. I should break it into travel, stay, food and sightseeing. Thought: I don't know current hotel prices. I should search instead of guessing. Action: web_search("family hotels Jaipur price per night") Observation: Mid-range family rooms cost about โ‚น2,500โ€“3,500 per night. Thought: 2 nights โ‰ˆ โ‚น6,000. That leaves โ‚น14,000 for food, local travel and tickets. Thought: Day 1 Amber Fort + Hawa Mahal; Day 2 City Palace + Johari Bazaar. Final answer: (a day-by-day plan with a cost table)

Look at what happened: the model planned, noticed it lacked information, chose a tool, used the result, and continued. This "think โ†’ act โ†’ observe" pattern is the seed of AI agents, which we cover in section 1.8. ๐ŸŒฑ

๐Ÿ›  Five prompting techniques that work (bad vs good)

Prompt engineering means adjusting your prompt (instructions, examples, constraints) until the model reliably gives what you need. Here are five techniques you will use every day.

1. Give context: share the surrounding information

โŒ Weak
Why is my code failing?
โœ… Strong
Here is the error: "KeyError: 'price' at line 32 in cart.py". Here is the function that reads the order JSON (pasted below). Here is one sample order JSON (pasted below). Using only this, explain why 'price' is missing and suggest a fix.

The model cannot see your screen. Without the error, the code and the data, it can only guess.

2. Assign a role: tell the model who to be

โŒ Weak
Review this login function.
โœ… Strong
You are a senior security engineer reviewing code before release. Review this login function for a junior developer. Focus on SQL injection, password storage and missing input validation. List each risk with a one-line fix.

3. Show examples ("few-shot" prompting)

โŒ Weak
Extract the order details from this WhatsApp message.
โœ… Strong
Extract order details as JSON. Examples: Message: "bhaiya 2 kg aloo aur 1 dozen eggs bhej do" Output: {"items":[{"name":"potato","qty":"2 kg"},{"name":"eggs","qty":"12"}]} Message: "send 500g paneer pls" Output: {"items":[{"name":"paneer","qty":"500 g"}]} Message: "1 litre milk and 2 bread" Output:

Two or three examples teach the exact format far better than a paragraph of explanation. That's "few-shot". With zero examples it's called "zero-shot".

4. Add guardrails: say clearly what NOT to do

โŒ Weak
Write a script to delete old files in my Downloads folder.
โœ… Strong
Write a Python script that finds files older than 30 days in ~/Downloads. RULES: - Do NOT delete anything by default. - First print a "DRY RUN" list of files that would be deleted. - Delete only if the user types YES to confirm.

5. Ask for step-by-step thinking (chain-of-thought)

โŒ Weak
How many unique customers ordered last week?
โœ… Strong
Find the number of unique customers in these order logs. Think step by step: 1. Find where the customer ID appears in each line. 2. Extract every customer ID into a list. 3. Remove duplicates. 4. Count what's left. Show each step, then give the final number.
๐ŸŽฏ Interview tip"I treat prompts like code: they live in version control as templates, they ask for structured output (a JSON schema), they include explicit guardrails, and every prompt change is tested against a fixed set of example questions before it ships."

1.5 How AI understands code

Let's apply these ideas to a real use case: AI coding assistants (tools like GitHub Copilot or Cursor). Understanding the meaning of code is not enough here. The tool must also understand the code's structure (what is inside what) and relationships (what calls what). Two ideas help with that: syntax trees (ASTs) and knowledge graphs. First, a quick look at vector search.

๐Ÿ”Ž Vector search: finding code by meaning

Vector search finds information by meaning instead of exact keywords. When a developer asks a question, the system finds the most relevant pieces of code to send to the LLM as context. Here's the flow:

  1. Ahead of time: every function in the codebase is turned into an embedding and stored in a vector database (for example pgvector, an add-on for PostgreSQL, or Pinecone).
  2. At question time: the developer's question is turned into an embedding using the same embedding model.
  3. The database compares the question vector with all stored vectors using cosine similarity or the dot product (both measure closeness).
  4. The closest matches ("top-k", e.g. the best 5) are returned.
  5. Those code pieces are added to the prompt so the LLM can answer using your code.
๐Ÿ” Worked example

Developer asks: "Where do we check if an email address is valid?"

Function in codebaseSimilarity to the question
def is_valid_email(addr): โ€ฆ (uses a regex)0.89 โœ… top match
def send_welcome_mail(user): โ€ฆ0.61
def calculate_gst(amount): โ€ฆ0.12

Notice the word "check" never appears in is_valid_email, but the meaning matches.

๐Ÿš€ Going deeper: cosine vs dot productCosine similarity = (A ยท B) รท (|A| ร— |B|). It only cares about direction, not length. If all vectors are first "normalised" to length 1, the denominator becomes 1, so cosine similarity and the plain dot product give the same ranking. That's why many systems normalise once and then use the cheaper dot product.

โœ๏ธ Text autocomplete vs code completion

Text autocomplete (like your phone keyboard) only looks at the last few words and guesses the next one. It doesn't really understand meaning or structure. Code completion is harder: the suggestion must be valid syntax and must fit where you are in the code: inside which class, which function, with which variables available.

Text autocomplete looks back in a line; code completion looks at structure
Code completion (structure-aware)
class Cartdef total(self, items):
Knows the class, the function, the variables
return sum(i.price * i.qty for i in items)
Text autocomplete (just the previous words)
See
you
Prediction: "soon"

๐ŸŒณ Abstract Syntax Trees (ASTs): the skeleton of code

Embeddings give us the meaning of code. An Abstract Syntax Tree (AST) gives us its structure. An AST is a tree that shows how every part of the code sits inside another part: a project contains files, a file contains classes, a class contains methods, a method contains statements. Compilers and IDEs build ASTs all the time to highlight errors, rename variables safely and refactor code.

๐Ÿ” Worked example: see a real AST with Python's built-in ast module
import ast
code = """
class Cart:
    def add(self, item):
        self.items.append(item)

    def total(self):
        return sum(i.price for i in self.items)
"""
tree = ast.parse(code)
for node in ast.walk(tree):
    if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
        print(type(node).__name__, node.name,
              "lines", node.lineno, "to", node.end_lineno)
Output:
ClassDef Cart lines 2 to 7
FunctionDef add lines 3 to 4
FunctionDef total lines 6 to 7
As a tree:
ClassDef (Cart)
โ”œโ”€โ”€ FunctionDef (add)
โ”‚   โ”œโ”€โ”€ args: self, item
โ”‚   โ””โ”€โ”€ Call: self.items.append(item)
โ””โ”€โ”€ FunctionDef (total)
    โ”œโ”€โ”€ args: self
    โ””โ”€โ”€ Return: sum(...)

Why does an AI tool care? Because of chunking. Before code can be embedded, it must be cut into pieces (chunks). If you cut blindly every 500 characters, you might slice a function in half, and each half makes no sense alone. With an AST, you cut along natural boundaries: one whole function = one chunk, or one whole class = one chunk.

โŒ Fixed-size chunks
Chunk 1: "...def total(self): return sum(i.pri" Chunk 2: "ce for i in self.items) def apply_coupon(..."
A function split in two. Neither chunk is useful on its own.
โœ… AST-based chunks
Chunk 1: def add(self, item): โ€ฆ (complete) Chunk 2: def total(self): โ€ฆ (complete) Chunk 3: def apply_coupon(self, code): โ€ฆ (complete)
Each chunk is a complete, meaningful unit.

In a large project the AST extends upward too: folders are parents, files are their children, classes inside files, methods inside classes. Here's an example food-delivery app:

A codebase seen as a tree
  • Project: FoodApp
    • Folder: api
      • File: main.py
        • Func: start_server
    • Folder: orders
      • File: cart.py
        • Class: Cart
      • File: billing.py
        • Class: Bill
    • Folder: utils
      • File: helpers.py
        • Func: format_rupees
        • Func: validate_pincode
๐Ÿง  Think of it likeโ€ฆAn AST is a book's table of contents. Instead of tearing random 500-word strips out of a book, you take "Chapter 3, Section 2" as one piece. The meaning stays intact. โœ‚๏ธ๐Ÿ“˜

๐Ÿ•ธ Knowledge graphs: who is connected to whom

A knowledge graph stores information as nodes (things) and edges (relationships between things). On Instagram, nodes could be users, posts and hashtags, and edges could be follows, liked and tagged in. A graph easily answers questions like "which of my friends liked this post?" or "which hashtags are often used together?".

For code, nodes are projects, folders, files, classes and functions, and edges are relationships like contains, calls and imports. The graph can answer questions embeddings cannot, such as "which functions call calculate_gst()?".

Nodes (things) in FoodApp
FoodApp (project) ยท api, orders, utils (folders) ยท main.py, cart.py, billing.py, helpers.py (files) ยท Cart, Bill (classes) ยท calculate_gst, format_rupees, validate_pincode (functions)
FromRelationship (edge)To
FoodApphasFolderorders
ordershasFilebilling.py
billing.pycontainsClassBill
BillhasMethodcalculate_gst
Cart.checkoutcallsBill.calculate_gst
Bill.printcallsformat_rupees
The same codebase as a knowledge graph
hasFolder hasFolder hasFolder hasFile hasFile containsClass hasMethod calls (checkout) FoodApp api orders utils cart.py โ†’ Cart billing.py Bill calculate_gst
The dashed edge says Cart.checkout calls Bill.calculate_gst: a fact you can only find by following relationships.
๐Ÿ” Worked example: asking a graph database a question

Graph databases such as Neo4j use a query language called Cypher, where you literally draw the pattern with arrows:

// "Which functions call calculate_gst?"
MATCH (caller:Function)-[:CALLS]->(f:Function {name: "calculate_gst"})
RETURN caller.name, caller.file

Output:

caller.name     | caller.file
----------------+-------------
Cart.checkout   | cart.py
Invoice.render  | invoice.py

Vector search could not answer this reliably, because Invoice.render may look nothing like calculate_gst in meaning.

๐Ÿง  Think of it likeโ€ฆAt a big Indian wedding, someone asks "how is the groom's uncle related to the bride's cousin?". You can't answer by finding people who look similar. You have to follow the relationships: uncle โ†’ brother of groom's father โ†’ whose wife's sister is โ†’ โ€ฆ That's a graph. Embeddings answer "what looks alike?"; graphs answer "what is connected?". ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง

โš–๏ธ Choosing a model: there is no "one model to rule them all"

Every model is a trade-off between four things. You pick based on what your product needs most.

DimensionThe question to askExample need
๐Ÿ“ Context windowHow much text must the model read at once?Summarising a 300-page contract needs a very large window.
โฑ LatencyHow fast must the answer appear?Code suggestions while typing must appear in under 0.2 seconds.
๐Ÿ” Security & privacyCan the data leave our servers?Hospital records may require a self-hosted model.
๐Ÿ’ธ CostHow much can we spend per request?A free app with 10 million users needs a very cheap model.
Big frontier model
e.g. gpt-6-astra, Claude Opus 5.5. Best reasoning and long-context understanding, but slower and the most expensive.
Small fast model
e.g. gpt-6-luna, Claude Haiku 5.5. Quick and cheap; great for simple tasks like classification and short replies; weaker on hard reasoning.
Open model you host
e.g. Llama 3.1 8B on your own GPUs. Data never leaves you; you control cost, but you also manage the servers. Smaller models can be fine-tuned for speed, sometimes at a cost in accuracy.
โš ๏ธ Watch outModel names and rankings change every few months. In interviews and design docs, talk about the dimensions (context, latency, privacy, cost) rather than a favourite brand.

๐ŸŽฒ Temperature: the creativity knob

We said LLMs are probabilistic. Here is where that randomness comes from, and how to control it. When the model picks the next token, it first gives every possible token a score. Those scores are converted into probabilities, and then one token is sampled (picked randomly, weighted by probability). Temperature controls how "sharp" or "flat" those probabilities are.

โ„๏ธ Low temperature (0 โ€“ 0.2)
The most likely token almost always wins. Output is consistent and focused. Use for code generation, extracting data, classification, JSON output: anywhere you want the same answer every time.
๐Ÿ”ฅ High temperature (0.7 โ€“ 1.0)
Less likely tokens get a real chance. Output is varied and creative. Use for brainstorming, marketing copy, stories, or generating varied practice questions.
๐ŸŽฎ Try it: "The chai was ___" โ€” move the temperature slider

Bars show the probability of each next word. Press "Pick a word" a few times at low and high temperature and see how often the result changes.

Behind the scenes: probability of word i = escorei/T รท (sum over all words of escore/T). Dividing scores by a small T exaggerates the gaps, so the top word dominates. A large T shrinks the gaps, so all words become more equally likely. (The scores here are a toy example.)

๐Ÿ” Worked example: same prompt, two temperatures
for t in [0, 1.0]:
    for run in range(2):
        r = client.chat.completions.create(model="gpt-6.1-terra", temperature=t,
              messages=[{"role": "user", "content": "Name a monsoon snack in 2 words."}])
        print(t, r.choices[0].message.content)

Output:

0    Onion pakoda
0    Onion pakoda
1.0  Masala corn
1.0  Bread pakora

What this means for system design:

โš ๏ธ Watch outEven at temperature 0, outputs are not guaranteed to be 100% identical every time (tiny numeric differences on GPUs, batching, or model updates on the provider's side). So build tests that check meaning and structure, not exact strings.
๐Ÿง  Think of it likeโ€ฆLow temperature is your mother's dal recipe: tastes exactly the same every day. High temperature is an experimental chef who might add mango to it today. ๐Ÿฅญ When you're making a bank statement, call your mother. When you need new dish ideas, call the chef.

1.6 RAG: giving the model the right facts at the right time

Here is a common problem. A user asks your app's help bot: "My refund hasn't come yet, what should I do?" Your help centre has an article titled "Money not credited after cancellation". The words are different, but the meaning is the same. How do we find that article and use it to answer? The answer is RAG: Retrieval-Augmented Generation.

RAG has a few steps. The first three prepare your knowledge; the last ones happen every time a user asks something.

๐Ÿงน Step 1: Clean the data

Before you cut documents into chunks and embed them, clean them properly. This is more than removing extra spaces.

De-noising
Remove HTML tags, repeated headers and footers, cookie banners and navigation links. They add tokens but no meaning, and they "dilute" the useful text.
PII scrubbing
Remove personally identifiable information (PII) like phone numbers, emails, Aadhaar or PAN numbers and API keys before the data is sent to any external model.
Normalisation
Make formats consistent: one date format, one currency style, standard characters. "05/11/26", "Nov 5, 2026" and "2026-11-05" should all become one form.
๐Ÿ” Worked example: before and after cleaning
Before
<div class="nav">Home | Help | Login</div> <h2>Refund not received?</h2> Call Priya at 98450 12345 or mail priya@shop.in. Refunds take 5-7 days from 05/11/26. ยฉ 2026 Shop Pvt Ltd. All rights reserved.
After
Refund not received? Call [PHONE] or mail [EMAIL]. Refunds take 5-7 days from 2026-11-05.

๐Ÿ”ข Step 2: Turn knowledge into vectors

Split the cleaned documents (help articles, past resolved tickets) into chunks and convert each chunk into an embedding using an embedding model such as text-embedding-3-small. Store each chunk's text, its vector and some labels (called metadata: source, date, category) in a vector database.

๐Ÿ” Step 3: Search by meaning

When the user asks a question, embed the question too, and ask the vector database for the closest chunks. Comparing against millions of vectors one by one would be slow, so databases use ANN (Approximate Nearest Neighbour) algorithms, such as HNSW, that find "very close" results extremely fast without checking every single vector.

๐Ÿง  Think of it likeโ€ฆANN search is like finding a book in a well-organised library. You don't check all 1 lakh books one by one. You go to the right floor โ†’ the right section โ†’ the right shelf, and look at a few dozen books. You might occasionally miss the perfect book on the next shelf (that's the "approximate" part), but you find a great one in seconds.
The RAG flow at question time
The questionUser asks"My refund hasn't come yet"
Retrieval
Embed the questiontext โ†’ 1,536 numbers
Vector searchfind the closest chunks
Top 3 chunks
Augmentation + generation
Augmented promptContext: [the 3 chunks]
Question: "My refund hasn't come yet"
LLM writes the answer
๐Ÿ” Worked example: what the final prompt actually looks like
SYSTEM: You are ShopKart's help assistant. Answer ONLY using the context below. If the answer is not in the context, say "Let me connect you to an agent." CONTEXT: [1] Refunds for cancelled orders reach the original payment method in 5-7 working days. [2] UPI refunds are usually faster: 1-3 working days. [3] If 7 working days have passed, raise a ticket from Orders โ†’ Help. QUESTION: My refund hasn't come yet. I paid by UPI 2 days ago.

Model's answer: "UPI refunds usually take 1โ€“3 working days, so yours should arrive within a day. If it's still not there after 7 working days, you can raise a ticket from Orders โ†’ Help."

The model didn't need to "know" ShopKart's policy. We handed it the answer, and it explained it nicely.

๐Ÿ” Worked example: a minimal RAG in about 20 lines
import numpy as np
from openai import OpenAI
client = OpenAI()

docs = ["Refunds for cancelled orders take 5-7 working days.",
        "UPI refunds are usually faster: 1-3 working days.",
        "Delivery partners can't accept cash above โ‚น2,000."]

def embed(texts):
    out = client.embeddings.create(model="text-embedding-3-small", input=texts)
    return np.array([d.embedding for d in out.data])

doc_vecs = embed(docs)                                 # 1. index once
question = "I paid by UPI, when will my refund come?"
q_vec = embed([question])[0]                           # 2. embed the question
scores = doc_vecs @ q_vec                              # 3. similarity (vectors are normalised)
top = [docs[i] for i in scores.argsort()[::-1][:2]]   # 4. best 2 chunks
print("Retrieved:", top)

answer = client.chat.completions.create(model="gpt-6.1-terra", messages=[
    {"role": "system", "content": "Answer only from this context:\n" + "\n".join(top)},
    {"role": "user", "content": question}])           # 5. augment + generate
print(answer.choices[0].message.content)

Output:

Retrieved: ['UPI refunds are usually faster: 1-3 working days.', 'Refunds for cancelled orders take 5-7 working days.']
Since you paid by UPI, your refund should usually arrive within 1-3 working days.

Notice the cash-delivery chunk was not retrieved: its meaning is far from the question.

RAG is the most important technique for higher accuracy and fewer made-up answers, because the model's answer is grounded in real, verified information from your own sources.

๐Ÿง  Think of it likeโ€ฆRAG turns a closed-book exam into an open-book exam ๐Ÿ“–. Without RAG, the student writes from memory and may confidently write something wrong. With RAG, they open the textbook to the right page first, then write.

๐Ÿ˜ฌ Why basic RAG is not always enough

Problem 1: "Similar" is not the same as "relevant"
Vector search is great at finding similar text, but similar is not always useful. If your help centre has five versions of the refund policy (2022, 2023, 2024โ€ฆ), all five look almost identical, so all five come back. The model gets repetitive, confusing context and may quote the outdated one.
Problem 2: Bad chunking hides the answer
Documents have structure: title โ†’ section โ†’ sub-section. A question may match the document's title strongly, so the system returns the general introduction, while the actual answer sits five sections deeper and scores low on its own. The connection between "this section" and "that document" is lost.
The buried-answer problem
Question: "How do I change the API timeout?"
strong match on the title โœ…
weak match, missed โŒ
One document: "API General Settings"
Introduction / overview(high match score) Section 1: AuthenticationSection 2: Rate limits
The real answer
Section 5: Advanced config"Set timeout_ms to 5000"
What the LLM receivesonly the overview โ€” the real answer never arrives ๐Ÿ˜ข

๐Ÿ•ธ Why knowledge graphs help retrieval

To fix these limits, we add a knowledge graph, stored in a graph database such as Neo4j or Amazon Neptune. Instead of matching similar words, it records relationships explicitly:

Section 5          -[part_of]->      "API General Settings"
Ticket #402        -[resolved_by]->  Commit a1b2c3
Commit a1b2c3      -[written_by]->   Ananya

Now retrieval can follow a path through these links to reach a precise answer, even across several hops.

๐Ÿš€ GraphRAG: RAG + knowledge graphs

Combining a knowledge graph with an LLM is called GraphRAG. The system follows chains of relationships to collect connected facts, then gives them to the LLM. It shines with structured, domain-specific data where questions involve "who / why / what caused what".

GraphRAG answering a multi-step question
Question:"Who fixed the payment-timeout bug mentioned in the Checkout Guide?"
Path through the graph
1. Find the starting node: Checkout Guide
2. Follow "has_section" โ†’ Section 4: Payment errors
3. Follow "mentions" โ†’ Ticket #402 (payment timeout)
4. Follow "resolved_by" โ†’ Commit a1b2c3
5. Follow "written_by" โ†’ Ananya
Answer: Ananya fixed it in commit a1b2c3
๐ŸŽฏ Interview tip"Vector search tells me what is similar; a graph tells me what is connected. For multi-hop questions like root cause or 'who changed this', I'd use hybrid retrieval: vector search to find the starting point, then graph traversal to follow the links."

1.7 Context engineering: packing the perfect suitcase

Here is a mindset shift that experienced AI engineers share: building with LLMs is mostly a data-pipeline problem, not a prompt-writing problem. The clever wording of a prompt matters far less than which information you put in front of the model at the moment it answers.

Your knowledge lives in long-term memory (a vector database with millions of chunks). The model can only see its short-term memory (the context window, a few thousand to a few hundred thousand tokens). Context engineering is the practice of designing, building and managing everything the model sees before it answers: the instructions, the right facts, the tools, and the rules.

The funnel: from millions of tokens to the few that matter
Vector DBlong-term memory ยท millions of tokens
raw chunks (e.g. top 50)
Retrieve + re-rankthe filter
best few chunks (e.g. top 5)
Context windowshort-term memory ยท e.g. 128K tokens
final prompt
LLM answers
Lots in โ†’ a careful filter โ†’ only the best reaches the model.
What is "re-ranking"?Vector search is fast but rough: it might return 50 "kind of related" chunks. A re-ranker is a second, more careful model that reads the question and each of those 50 chunks together and scores how well each one actually answers the question. We keep only the top 5. Fast-and-rough first, slow-and-careful second.

The four jobs of context engineering

1. Assemble information dynamically
Build the context fresh for every turn:
  • System instructions: role and behaviour ("You are a helpful support agent")
  • Conversation history (memory): so the chat feels continuous
  • External knowledge (RAG): up-to-date facts from your database or the web
2. Manage the window
  • Prioritise: what matters most for this step?
  • Compress: summarise or filter big data into fewer tokens
3. Orchestrate tools
Connect external tools and APIs (Application Programming Interfaces). The model needs clear descriptions to decide when to use a tool, how to call it, and how to blend the result into its answer.
4. Keep it consistent and reliable
Control what the model sees in a systematic way so that answers stay accurate, consistent and within policy across different users and sessions.
One request, end to end, with context engineering
1. Input
User
Promptinput text
Tokenizationwords โ†’ numbers
2. Retrieval (RAG)
Embedding modeltext โ†’ vectorVector DBlong-term memory
Vector searchnearest neighbours
Retrieved contextrelevant docs / code
+ the original question
3. Context engineering
Fit everything in the windowprioritise ยท compress ยท order
Assemble the final prompt
4. The model
Temperature?
0 = precise
1 = creative
temp 0.2
LLMfocused mode
temp 0.8
LLMcreative mode
5. Output
Stream tokensone at a time
Final response
๐Ÿ” Worked example: a context budget for a support bot (16K-token window)
SectionBudgetWhat goes inIf it doesn't fitโ€ฆ
System instructions800Persona, tone, rules, output formatNever cut: rewrite shorter instead
User profile200Name, plan, city, languageKeep only fields this question needs
Conversation summary500Short summary of older turnsRe-summarise more aggressively
Last 6 messages2,000Recent turns, word for wordKeep the last 4 instead
Retrieved help articles6,000Top 5 re-ranked chunksKeep top 3
Tool results1,500e.g. order status JSONKeep only relevant fields
Reserved for the answer1,000The model's replyโ€”
Safety margin4,000Unused bufferโ€”
๐Ÿง  Think of it likeโ€ฆPacking for a flight with a 15 kg baggage limit. Your wardrobe (vector DB) has 200 items; the suitcase (context window) fits 20. A good packer chooses what this specific trip needs, folds things smartly (compression), and leaves a little room for shopping (the answer). Context engineering is that packing skill. ๐Ÿงณ

1.8 AI agents: from answering to doing

In a simple AI app, the LLM is called once (or a few times in a fixed order) and the code decides every step. That works well for routine tasks. But some goals are open-ended: "find out why last night's deployment failed and open a fix". Nobody can write the steps in advance. That's where agents come in.

An AI agent is a system where an AI model reasons, plans and takes a series of actions on its own to reach a goal. The key difference: the path is decided at run time by the model, not hard-coded by you. You give the goal; the agent figures out the steps. It works in a loop often called ReAct (Reason + Act):

The agent loop (repeat until the goal is done)
๐Ÿ—บ 1. Planbreak the goal into steps
๐Ÿ›  2. Actpick a tool: search, run code, query a DB, read a file
๐Ÿค” 4. Reasoncompare goal + plan + new info โ†’ next step, or "done"
๐Ÿ‘€ 3. Observeadd the tool's result to the context
Goal: "Is my Chennai โ†’ Bengaluru train tomorrow running on time? If it's late by more than an hour, tell my family on WhatsApp."
๐Ÿง  Think of it likeโ€ฆA plain LLM is like asking a friend a question and getting an answer. An agent is like a personal assistant you tell "plan our Kerala trip". They check flights (act), see they're expensive (observe), think a train might be better (reason), change the plan (plan), and keep going until the booking is done. โœˆ๏ธ๐Ÿš†
๐Ÿš€ Going deeper: agents need seatbeltsAgents can get stuck in loops, burn money calling the model again and again, or call the wrong tool. Good designs always include: a maximum number of steps and a token budget, only the tools this task needs (with the smallest permissions), and human approval before any high-impact action like sending money or deleting data. Chapter 2 covers this as "excessive agency".

1.9 Modalities: more than just text

People understand the world through sight, sound and touch, not only text. Modern AI is similar. Each type of data is called a modality, and models that handle several at once are called multimodal.

๐Ÿ“ Text
Written language: translation, summaries, chatbots.
๐Ÿ–ผ Images
Recognising objects, reading a photo of a bill, checking a damaged-product photo for a refund.
๐ŸŽง Audio
Speech to text, voice assistants, call-centre analytics, music generation.
๐ŸŽฌ Video
Moving images plus audio: summarising a lecture recording, content moderation.
๐ŸงŠ Spatial / 3D
Understanding depth and 3D space: self-driving cars, robots, AR apps.
๐Ÿ— System-design impact
Images and video use far more tokens than text, so they cost more and are slower. Plan upload size limits, compress media, and process big files in the background.

1.10 Where does your data live? Data residency and compliance

Speed and cost aren't the only concerns. Big companies, banks and hospitals also ask: where is our data stored and processed, and who can see it? This is called data residency, and it is often the first filter when choosing how to run an LLM. In India, for example, payment data must be stored in the country, and the Digital Personal Data Protection (DPDP) Act sets rules for handling personal data.

Three ways to run an LLM: more control means more work
๐ŸŒ Public API
e.g. calling OpenAI or Anthropic directly over the internet. Easiest to start. But your data leaves your private network (your VPC, Virtual Private Cloud). For health records (PHI), card data (PCI) or other personal data (PII), this is often not allowed unless the provider signs a zero-retention agreement (they promise not to store your data).
โ˜๏ธ Private cloud
e.g. Amazon Bedrock or Azure OpenAI inside your cloud account. Data stays inside your cloud boundary and region. You still depend on the cloud provider's availability and model list.
๐Ÿ  Self-hosted open model
e.g. running Llama 3.1 or Mistral on your own GPUs. Full control: data never leaves. Needed for strict or offline ("air-gapped") environments. The price: you manage GPUs, scaling, updates and on-call.
Control over data โ†’
Operational effort โ†’
๐Ÿง  Think of it likeโ€ฆGetting clothes washed. Public API = giving them to a laundry shop across town. Private cloud = the laundry person comes and washes them inside your building. Self-hosted = buying your own washing machine: total control, but repairs are your problem. ๐Ÿงบ

1.11 Measuring performance: how good and how fast?

A simple engineering rule: you can't improve what you don't measure. For AI, "smart" and "fast" are different things, so we measure them separately.

๐ŸŽ“ Quality benchmarking
How smart and accurate is the model for my task? Does it summarise our tickets well? Does it pick the right category? You run it on a fixed set of test examples and score the results.
โšก Speed benchmarking
How fast and efficient is it? How long until the first word appears, how many tokens per second, how many users at once? This answers the business question: how fast and how expensive is it to run?

Building your own quality benchmark in 4 steps

Public leaderboards tell you which model is good at general tests. But you care about your task. So build a custom benchmark:

  1. Define the goal. What exactly must the model do well? "Summarise customer support tickets accurately, with the right sentiment and topic."
  2. Create a "golden set". Hand-write 50โ€“100 high-quality examples, each with an input and the ideal output.
    Input: "This is the 3rd time I'm writing! I was charged twice for order #1234 and nobody replies!!" Ideal output: {"summary": "Customer charged twice for order #1234, no response to earlier messages.", "sentiment": "negative", "topic": "billing"}
  3. Run the models. Run every model you want to compare (say gpt-6.1-terra vs a self-hosted Llama 3.1 8B) on all inputs in the golden set.
  4. Evaluate. Two options: human evaluation (an expert scores each answer 1โ€“5; the most reliable, but slow) or LLM-as-a-judge (a strong model grades the answers; fast and scalable). A judge prompt might be:
    You are an expert reviewer. Here is an INPUT, the IDEAL answer, and a MODEL answer. Score the MODEL answer from 1 to 5 for accuracy compared to the IDEAL. Reply as JSON: {"score": n, "reason": "..."}
    Example judge output: {"score": 4, "reason": "Correct issue and sentiment; missed that earlier messages went unanswered."}

The speed metrics everyone talks about

One request on a timeline
๐Ÿ“ค Prompt sent
โšก First token
๐Ÿ Last token
TTFT (waiting)
TPS = tokens produced per second
โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Total latency โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ
MetricWhat it meansWhy users feel it
TTFT (time to first token)Time from sending the prompt to seeing the first wordThe "is it working?" wait. Long TTFT feels broken.
TPS (tokens per second)How fast tokens come after the first oneHow quickly the answer "types itself out"
Total latencyTime from prompt to the very last tokenWhen the full answer is ready to use
Throughput (requests/sec)How many requests the system handles at the same timeWhether the app stays fast at 9 pm peak
Resource usageGPU memory (VRAM) and compute usedDecides which hardware to buy or rent
๐Ÿ” Worked example: estimating total latencyA simple formula: Total latency โ‰ˆ TTFT + (output tokens รท TPS).
If TTFT = 0.5 s, the answer is 300 tokens, and the model produces 60 tokens per second: 0.5 + 300 รท 60 = 0.5 + 5 = 5.5 seconds.
Ask for a 100-token answer instead: 0.5 + 100 รท 60 โ‰ˆ 2.2 seconds. Shorter output is the biggest speed lever you have, which is exactly the token lesson from section 1.3.

1.12 When things go wrong: the three classic failures

๐Ÿคฅ Hallucination
The model confidently makes up something false, because it sounds statistically plausible. Example: inventing a refund policy, a court case, or a Python function that doesn't exist.
Fix: ground it with real data (RAG), ask it to say "I don't know" when unsure, and verify important outputs.
๐Ÿ“… Knowledge cut-off
A model's knowledge is frozen at the time its training data was collected. Ask about last week's news or today's prices and it simply doesn't know (or worse, guesses).
Fix: provide fresh information at question time via RAG, tools or web search.
โš–๏ธ Bias
The hardest one. Models learn from huge amounts of human writing, and human writing contains biases (about gender, region, caste, languageโ€ฆ).
Manage it: filter training data, add guardrails in prompts, test with diverse examples, and collect human feedback.
๐Ÿง  Think of it likeโ€ฆHallucination is like that uncle who never says "I don't know" when you ask for directions: "Haan haan, go straight, then second left!" ๐Ÿ˜… Confident, and wrong. RAG is handing him Google Maps before he answers.

1.13 Summary: LLMs are not magic

LLMs are probabilistic engines with hard limits. Every design decision you make trades off three things:

The qualityโ€“costโ€“latency triangle: you can usually pick two
Quality Low cost Low latency Quality + speedโ†’ pay for big GPUs andspare capacity Quality + low costโ†’ accept waiting: run inbackground queues Low cost + speed โ†’ accept less depth: smaller models, aggressive summarising
DimensionMainly decided by
๐Ÿ’ธ CostHow many input tokens you send + how big the model is
โฑ LatencyHow many output tokens you ask for + time spent retrieving data
๐ŸŽฏ QualityWhat you put in the context window + how strong the model's reasoning is

The real skill of AI engineering is not writing magic prompts; it is managing these constraints. The rest of this series is about patterns for exactly that: RAG to work around limited context, caching for speed, routing for cost, and much more. Now that you know the atoms, let's start building molecules. ๐Ÿงฑ

โœ… Key takeaways

๐Ÿ“ Quick quiz (click to reveal the answer)

Q1. Why is generating output tokens slower than reading input tokens?Input tokens are processed together in parallel. Output tokens are generated one at a time, because each new token depends on all the previous ones. So to reduce latency, limit the output length.
Q2. What's the difference between the sliding-window and summarization strategies?Sliding window simply drops the oldest messages (free, but the model forgets them). Summarization compresses old messages into a short summary (keeps the gist, but costs one extra LLM call).
Q3. Two sentences share no words at all. Can their embeddings still be close?Yes. Embeddings capture meaning, not exact words. "How do I get my money back?" and "refund process" will be close together.
Q4. Your bot doesn't know this month's prices. Fine-tune or RAG?RAG. Prices change often; fetch them at question time. Fine-tuning is better for teaching style, tone and format.
Q5. Why might a retry at temperature 0 be pointless?At temperature 0 the model gives (nearly) the same output for the same input. If the first output was broken JSON, the retry will likely be broken in the same way. A slightly higher temperature gives a chance of a different, correct output.
Q6. Name two reasons basic RAG can fail.(1) Similar is not always relevant: many near-duplicate chunks crowd the context. (2) Poor chunking: the question matches a document's title, but the real answer is buried deep in a section that wasn't retrieved.
Q7. When would you use GraphRAG instead of plain vector search?When the question is about relationships across several steps ("who fixed the bug mentioned in this guide?", root-cause questions), especially with structured, connected data.
Q8. What are the three data-cleaning steps before embedding?De-noising (remove HTML and boilerplate), PII scrubbing (remove phone numbers, emails, IDs, keys before data goes to an external API), and normalisation (consistent dates, currency and characters).
Q9. TTFT is 0.4 s, the answer is 240 tokens, and TPS is 80. Roughly how long is the total latency?0.4 + 240 รท 80 = 0.4 + 3 = 3.4 seconds.
Q10. Why do agents need a maximum step count?Without it, an agent can loop forever, burning tokens and money, or keep calling tools wrongly. A step limit (and token budget) is a safety stop.

๐Ÿ“– Glossary

TermMeaning in one line
LLMLarge Language Model: an AI trained on huge text to read and write language.
PromptThe text you send to the model.
TokenA small piece of text (โ‰ˆ 4 characters) that the model reads and writes.
Context windowThe most tokens a model can handle in one request (input + output).
Embedding / vectorA list of numbers that represents meaning.
Vector databaseA database that stores vectors and finds the closest ones fast.
Cosine similarityA score from โˆ’1 to 1 of how closely two vectors point in the same direction.
ANN / HNSWFast "approximately nearest" search methods for vectors.
Pre-training / fine-tuningGeneral learning from huge data / extra focused learning on small data.
RAGRetrieve facts, add them to the prompt, then generate the answer.
Re-rankingA second, careful scoring step that keeps only the best retrieved chunks.
ASTAbstract Syntax Tree: the nested structure of code.
Knowledge graphData stored as things (nodes) and relationships (edges).
TemperatureA setting that controls how random the model's word choices are.
HallucinationA confident but false answer.
Agent / ReActA model that loops through reasoning and tool actions to reach a goal.
TTFT / TPSTime to first token / tokens per second.
PIIPersonally identifiable information: phone, email, ID numbers, etc.