RAG: retrieval-augmented generation
A model doesn't know your company's documents. RAG finds the right passages at question time and puts them in the prompt. Watch the index get built, a question get matched, and an answer get grounded.
10 minFree
- Index
- Retrieve
- Generate
Press Play to watch it run, or step through with ← →. Then switch to Practice and run it yourself.
import numpy as np
from google import genai
from google.genai import types
client = genai.Client()
# 1. Index (once): split your documents into chunks and embed each chunk.
chunks = [
"Refunds for failed UPI payments go back to the source account within 5 working days.",
"Cash on delivery orders are refunded as store credit or by bank transfer.",
"You can cancel an order free of charge until it has been shipped.",
]
doc_vectors = np.array([
e.values
for e in client.models.embed_content(
model="gemini-embedding-001",
contents=chunks,
config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT"),
).embeddings
])
def answer(question: str, top_k: int = 2) -> str:
# 2. Retrieve: embed the question, rank chunks by cosine similarity.
q = np.array(client.models.embed_content(
model="gemini-embedding-001",
contents=question,
config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY"),
).embeddings[0].values)
scores = doc_vectors @ q / (np.linalg.norm(doc_vectors, axis=1) * np.linalg.norm(q))
best = [chunks[i] for i in np.argsort(scores)[::-1][:top_k]]
# 3. Generate: answer from the retrieved text, and only from it.
context = "\n".join(f"- {c}" for c in best)
interaction = client.interactions.create(
model="gemini-3.8-flash",
system_instruction=(
"Answer only from the context. If the answer is not in the context, "
"say that the information is not available."
),
input=f"<context>\n{context}\n</context>\n\nBased on the context above: {question}",
)
return interaction.output_text
print(answer("My UPI payment failed. When do I get my money back?"))Pipeline log
Nothing yet. Press Play.
Background: the idea in plain words
Ask a model about your refund policy and it will give you a confident answer about refund policies in general. It was trained on public text (training is how a model learns, long before you use it). Your policy PDF wasn't part of it, and you can't retrain the model every time the policy changes.
Retrieval-augmented generation (RAG) fixes this without touching the model. Before it answers, your app searches your own documents and adds the most relevant passages to the prompt (the text sent to the model). The model then answers from those passages. Google's RAG Engine docs describe the steps like this:
- Ingest and transform: load your documents and split them into chunks (small pieces of text).
- Embed and index: turn each chunk into an embedding (a vector of numbers that captures its meaning) and store them in an index, which is a store you can search quickly.
- Retrieve: when a question arrives, find the chunks closest in meaning to it.
- Generate: add those chunks to the prompt so the answer is grounded in them (based on them).
The first two steps happen once, before any question arrives. The last two happen every time someone asks something.
A tiny example. A customer asks "My UPI payment failed. When do I get my money back?" Search finds the chunk about refunds for failed UPI payments, even though the customer never typed the word "refund". The model reads that chunk and answers "within 5 working days", as the policy says.
Sometimes your documents have no answer. Then the right reply is "I don't know", not a guess.
The running example is a shop's help chat (the policy text is made up). Press Play to see what happens with no retrieval, then switch the Try it selector to the full RAG pipeline, and to a question your documents can't answer.
What to notice
- Two separate phases. Indexing runs once (and again when documents change). Retrieval and generation run on every question. Only the question is embedded at query time.
- Search is by meaning, not keywords. The customer said “money back” and the chunk says “refunds”. Their embeddings are still close. Use the same embedding model for chunks and questions, with the matching task types (
RETRIEVAL_DOCUMENTandRETRIEVAL_QUERY). - Retrieval always returns something. Top-k search hands back the k best chunks even when none is relevant. The instruction “answer only from the context, otherwise say it's not available” is what stops the model from filling the gap with a guess.
- The prompt is just a prompt. Retrieved chunks are context, so the usual rules apply: context first, the question last. See prompt engineering patterns.
- Chunking is a design choice. Chunks that are too big bury the answer in noise. Chunks that are too small lose the sentence that explains it. Expect to tune this.
Go deeperYou don't have to build it all yourself
The code beside the animation keeps every step visible, with a plain list as the index. In production you would normally use a managed service:
| Option | What it handles |
|---|---|
| File Search tool (Gemini API) | Imports, chunks and indexes your files, then retrieves them when you add it as a tool, with citations back to the source file |
| RAG Engine (Gemini Enterprise Agent Platform) | Ingestion from local files, Cloud Storage or Google Drive, chunking, embedding, an index called a corpus, and retrieval. See RAG Engine |
Go deeperWords to know
| Word | Meaning in simple words |
|---|---|
| RAG | Retrieval-augmented generation: search your documents first, then let the model answer from what was found |
| Chunk | A small piece of a document, sized so search can return just the useful part |
| Embedding | A list of numbers that captures the meaning of a piece of text |
| Index | The store of chunks and their embeddings that your app searches |
| Retrieve | To find the chunks closest in meaning to the question |
| Grounded | Based on the retrieved text, not on what the model happens to remember |
Check your understanding
Sources: the official documentation
This lesson is based on the official documentation. Check it for the latest details.
Something wrong or unclear in this lesson? Tell us, it gets fixed.