The Building Blocks of LLM Systems
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โฆ
- Explain what an LLM is (and is not) to a friend
- Estimate how tokens affect speed and cost
- Explain embeddings and "search by meaning"
- Write well-structured prompts
- Explain how RAG cuts down wrong answers
- Know when to use a knowledge graph
- Describe how an AI agent loops through tasks
- Name the key speed and quality metrics
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.
A calculator, a bank balance check, a sorting function.
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.
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.
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.
| Term | What it means in plain words | Everyday 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 Learning | A 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 AI | Models 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 |
def is_spam(email):
if "lottery" in email: return True
if "free money" in email: return True
return False
# Spammers write "l0ttery" โ rule fails# 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)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).
๐งฉ 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.
| Text | Tokens (roughly) | Token IDs (illustrative) |
|---|---|---|
| The cat sat on the mat. | The cat sat on the mat . | [791, 8415, 7731, 389, 279, 5634, 13] |
| unbelievable | un believ able | [359, 32927, 481] |
| Bengaluru | Beng 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.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).
| Step | Calculation | Result |
|---|---|---|
| Input tokens per day | 10,000 ร 1,500 | 15 million |
| Output tokens per day | 10,000 ร 300 | 3 million |
| Daily cost | 15 ร $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.
๐ฎ Try it: the window can hold only 2 messages. Press "Send next message" and compare the two strategies
๐ 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().
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?]
| Word | Vector |
|---|---|
| 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.
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.
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.
๐ซ 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
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.
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.
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:
| Part | What it does | Example |
|---|---|---|
| Instruction | The actual command | "Summarize the following meeting notesโฆ" |
| Context | Background the model needs to do the task well | "โฆThese are notes from a sprint planning meeting. Focus only on action items and owners." |
| Persona | Who the model should act as; this changes tone and depth | "You are a senior engineering manager writing for new joiners." |
| Format | The exact shape of the output, so your code can use it | "Return a JSON list of {owner, task, due_date}." |
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.
๐ง 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:
- your system instructions (persona, rules, format)
- the conversation history (earlier questions and answers)
- any documents or data you attach
- the user's latest question
- the model's reply (yes, the answer uses up the window too)
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.
๐ค 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.
Prompt: "Plan a 2-day Jaipur trip for a family of 4 under โน20,000."
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
โ Strong
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
โ Strong
3. Show examples ("few-shot" prompting)
โ Weak
โ Strong
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
โ Strong
5. Ask for step-by-step thinking (chain-of-thought)
โ Weak
โ Strong
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:
- 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).
- At question time: the developer's question is turned into an embedding using the same embedding model.
- The database compares the question vector with all stored vectors using cosine similarity or the dot product (both measure closeness).
- The closest matches ("top-k", e.g. the best 5) are returned.
- Those code pieces are added to the prompt so the LLM can answer using your code.
Developer asks: "Where do we check if an email address is valid?"
| Function in codebase | Similarity 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.
โ๏ธ 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.
๐ณ 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.
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)
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
โ AST-based chunks
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:
- Project: FoodApp
- Folder: api
- File: main.py
- Func: start_server
- File: main.py
- Folder: orders
- File: cart.py
- Class: Cart
- File: billing.py
- Class: Bill
- File: cart.py
- Folder: utils
- File: helpers.py
- Func: format_rupees
- Func: validate_pincode
- File: helpers.py
- Folder: api
- Project level: the root node is the whole project; its children are folders and files.
- File level: each file has its own AST with imports, classes, functions and global code.
- Class / function level: classes contain methods; functions contain statements and expressions.
๐ธ 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)| From | Relationship (edge) | To |
|---|---|---|
| FoodApp | hasFolder | orders |
| orders | hasFile | billing.py |
| billing.py | containsClass | Bill |
| Bill | hasMethod | calculate_gst |
| Cart.checkout | calls | Bill.calculate_gst |
| Bill.print | calls | format_rupees |
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.
โ๏ธ 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.
| Dimension | The question to ask | Example need |
|---|---|---|
| ๐ Context window | How much text must the model read at once? | Summarising a 300-page contract needs a very large window. |
| โฑ Latency | How fast must the answer appear? | Code suggestions while typing must appear in under 0.2 seconds. |
| ๐ Security & privacy | Can the data leave our servers? | Hospital records may require a self-hosted model. |
| ๐ธ Cost | How 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.๐ฒ 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.)
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 pakoraWhat this means for system design:
- Testing: you cannot write
assert reply == "Onion pakoda"for LLM output. Tests must accept variation (for example, check that the reply is valid JSON, or have another model grade it), or force temperature to 0 for regression tests. - Retries: if the model returns broken JSON at temperature 0, retrying with the exact same request will likely fail in exactly the same way. A slightly higher temperature on retry gives it a chance to produce something different (and correct).
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.
- Retrieval: find the relevant information (from documents, a database, an APIโฆ)
- Augmented: add that information into the prompt
- Generation: let the LLM write the answer using that information
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.๐ข 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.
Question: "My refund hasn't come yet"LLM writes the answer
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.
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.
๐ฌ 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.๐ธ 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".
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 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.0 = precise
1 = creative
| Section | Budget | What goes in | If it doesn't fitโฆ |
|---|---|---|---|
| System instructions | 800 | Persona, tone, rules, output format | Never cut: rewrite shorter instead |
| User profile | 200 | Name, plan, city, language | Keep only fields this question needs |
| Conversation summary | 500 | Short summary of older turns | Re-summarise more aggressively |
| Last 6 messages | 2,000 | Recent turns, word for word | Keep the last 4 instead |
| Retrieved help articles | 6,000 | Top 5 re-ranked chunks | Keep top 3 |
| Tool results | 1,500 | e.g. order status JSON | Keep only relevant fields |
| Reserved for the answer | 1,000 | The model's reply | โ |
| Safety margin | 4,000 | Unused buffer | โ |
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):
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.
Written language: translation, summaries, chatbots.
Recognising objects, reading a photo of a bill, checking a damaged-product photo for a refund.
Speech to text, voice assistants, call-centre analytics, music generation.
Moving images plus audio: summarising a lecture recording, content moderation.
Understanding depth and 3D space: self-driving cars, robots, AR apps.
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.
๐ 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.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:
- Define the goal. What exactly must the model do well? "Summarise customer support tickets accurately, with the right sentiment and topic."
- 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"}
- Run the models. Run every model you want to compare (say
gpt-6.1-terravs a self-hosted Llama 3.1 8B) on all inputs in the golden set. - 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
| Metric | What it means | Why users feel it |
|---|---|---|
| TTFT (time to first token) | Time from sending the prompt to seeing the first word | The "is it working?" wait. Long TTFT feels broken. |
| TPS (tokens per second) | How fast tokens come after the first one | How quickly the answer "types itself out" |
| Total latency | Time from prompt to the very last token | When the full answer is ready to use |
| Throughput (requests/sec) | How many requests the system handles at the same time | Whether the app stays fast at 9 pm peak |
| Resource usage | GPU memory (VRAM) and compute used | Decides which hardware to buy or rent |
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.
1.13 Summary: LLMs are not magic
LLMs are probabilistic engines with hard limits. Every design decision you make trades off three things:
| Dimension | Mainly decided by |
|---|---|
| ๐ธ Cost | How many input tokens you send + how big the model is |
| โฑ Latency | How many output tokens you ask for + time spent retrieving data |
| ๐ฏ Quality | What 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. ๐งฑ
- LLMs are probabilistic; we build systems around them to make them dependable.
- Tokens drive speed, cost and limits. Output tokens are slow and expensive; keep answers short.
- Embeddings turn meaning into numbers so we can search by meaning.
- Facts โ RAG. Style and behaviour โ fine-tuning.
- Good prompts have persona, context, instruction and format, plus guardrails and examples.
- ASTs give code structure; knowledge graphs give relationships; vectors give similarity.
- Context engineering = choosing what goes into the limited context window.
- Agents loop through plan โ act โ observe โ reason, and need limits and approvals.
- Measure both quality (golden sets, judges) and speed (TTFT, TPS, total latency).
๐ 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
| Term | Meaning in one line |
|---|---|
| LLM | Large Language Model: an AI trained on huge text to read and write language. |
| Prompt | The text you send to the model. |
| Token | A small piece of text (โ 4 characters) that the model reads and writes. |
| Context window | The most tokens a model can handle in one request (input + output). |
| Embedding / vector | A list of numbers that represents meaning. |
| Vector database | A database that stores vectors and finds the closest ones fast. |
| Cosine similarity | A score from โ1 to 1 of how closely two vectors point in the same direction. |
| ANN / HNSW | Fast "approximately nearest" search methods for vectors. |
| Pre-training / fine-tuning | General learning from huge data / extra focused learning on small data. |
| RAG | Retrieve facts, add them to the prompt, then generate the answer. |
| Re-ranking | A second, careful scoring step that keeps only the best retrieved chunks. |
| AST | Abstract Syntax Tree: the nested structure of code. |
| Knowledge graph | Data stored as things (nodes) and relationships (edges). |
| Temperature | A setting that controls how random the model's word choices are. |
| Hallucination | A confident but false answer. |
| Agent / ReAct | A model that loops through reasoning and tool actions to reach a goal. |
| TTFT / TPS | Time to first token / tokens per second. |
| PII | Personally identifiable information: phone, email, ID numbers, etc. |