RAG pipelines: retrieve, rerank and ground
Trace how a retrieval-augmented agent turns documents into an answer, tune chunk size, top-k and reranking, diagnose a grounded but wrong answer, and choose between Agent Search, RAG Engine, and Agent Retrieval or Vector Search.
Chapter 4Custom agentsLesson 4 of 8ShowHide
Chapter 4 of 7 in Google Cloud Professional Agentic Architect
- RAG pipelines: retrieve, rerank and groundYou're here
Prerequisites: Building agents with ADK
Why retrieval decides the answer
gives a model content it was never trained on: before the model answers, the system finds the most relevant passages in your documents (the corpus) and places them in the model's context. In an agent, retrieval is usually one tool (the ADK lesson): the model proposes a search, the runtime runs it, and the passages come back as the tool result.
The model can only be as right as what it reads. If retrieval misses the passage that holds the answer, the best model in the world answers "I don't know" or guesses. If retrieval delivers an outdated passage, the model faithfully repeats it. Retrieval quality caps answer quality, so most RAG problems are fixed in the pipeline, not in the prompt.
The six stages, and the decision at each
Retrieval finds passages by meaning, not by keywords. Each chunk and each question is turned into a vector, and closeness between two vectors is a similarity score: chunks that mean nearly the same thing as the question score high, even when they share no words with it.
| Stage | What happens | The decision you make |
|---|---|---|
| Ingest | Load the documents and extract their text, including from scans and tables | Which sources, how to parse them, how often to refresh |
| Chunk | Split each document into passages | Chunk size and overlap |
| Embed | Turn each chunk into an , a vector that represents its meaning | Which embedding model |
| Index | Store the vectors, with metadata such as source and date, so they can be searched fast | Which vector database, which metadata |
| Retrieve | Embed the question, find the chunks whose vectors are closest, optionally rerank them, keep the | How many to keep, whether to rerank, what to filter on |
| Generate | The model answers from the retrieved chunks, ideally citing them | How to instruct and cite |
The first four stages run ahead of time, when documents are added or change. The last two run on every question.
Three knobs that decide what the model sees
Chunk size. Small chunks match a question precisely but can cut a rule off from its exception. Large chunks keep context together but mix in unrelated text, which weakens the match and spends tokens. RAG Engine, for example, defaults to 1,024-token chunks with a 256-token overlap, so neighbouring chunks share text across the cut.
What do small and large chunks each risk?
Top-k. How many retrieved chunks reach the model. Too few and the answer can miss a second relevant chunk. Too many and near-misses crowd the context, compete with the right chunk and cost tokens on every call.
Reranking. Vector similarity is fast but rough. A takes a wider set of candidates (say, the top 20) and rescores each one against the question with a stronger relevance model, so the few chunks that reach the model are the most relevant ones. RAG Engine offers two: the ranking API, a dedicated reranker that responds in under 100 ms, and an LLM reranker that asks Gemini to judge relevance and takes one to two seconds. Reranking measures relevance, not truth: an outdated passage that answers the question exactly still ranks first.
Hybrid search. Vector similarity matches meaning, so it can miss an exact
token such as a product code, an error number or a rare name; keyword search
finds those tokens but misses paraphrases. runs both and merges the two ranked lists. Agent Retrieval
(formerly Vector Search 2.0) merges them with (RRF): each result scores by its rank in
each list rather than by its raw score, so the scores of two different methods
never have to be compared, and weights lean the blend toward one side. In
the console's try-it page that is one slider, an alpha from 1.0 (purely
semantic) to 0.0 (purely keyword); in the API, the RRF ranker takes a list of
weights, one per search ("rrf": {"weights": [1.0, 1.0]} weighs both
equally). The fused list can
then go to the Agent Platform ranking API, the dedicated reranker described
above, for reranking.
When does hybrid search help, and how does Agent Retrieval merge its two result lists?
Try it: a stale policy in the corpus
Two numbers tell you whether retrieval found the right material. Call the chunks a correct answer needs the relevant ones. Then, for the top-k chunks that reach the model:
- Precision@k is the share of those k chunks that are relevant: how clean the catch is.
- Recall@k is the share of all relevant chunks that made the top k: how complete it is.
Both are standard information-retrieval measures, and they pull against each other: a bigger k can only keep or raise recall, and usually lowers precision.
In Grounded but wrong: the right catch, the corpus is a pond and every chunk is a fish, ranked by how similar its meaning is to one question: "How many days do I have to return an item?" Two versions of the same policy swim there: a 2024 FAQ (60 days, now superseded) and the current 2026 policy (30 days, with a final-sale exception). The net is your top-k, the bucket is what the model reads, and the precision and recall meters are drawn as the fish you caught. An answer drawn from the retrieved chunks is called grounded; the question is whether grounded also means right.
Before you cast, predict: the default net catches the top 3 medium chunks, and the current 30-day policy is among them. What will the agent answer?
What you should see:
- The default answer is grounded but wrong. Recall is 1 of 1: the 2026 policy is in the bucket. But precision is 1 of 3, and the 2024 FAQ ranks first, because it is about exactly this question and similarity measures meaning, not which version is current. The model reads it first, cites it faithfully and says 60 days.
- Reranking does not save you. The old FAQ answers the question just as directly as the new policy, so a reranker keeps it on top.
- A bigger net does not save you either. Raising top-k adds chunks and tokens to every call, but the old FAQ still ranks first.
- The metadata filter fixes it. Throw superseded documents back before the search and the 2026 policy is the first one the model reads: 30 days, except final-sale items. Precision can stay low; in this exercise the off-topic chunks left in the net only cost tokens.
- Chunk size moves recall. With small chunks, the final-sale rule sits in its own chunk, so there are two relevant chunks. At top 3 without reranking it misses the net: recall is 1 of 2 and the answer is right but incomplete. Reranking lifts it back in.
Explain it: at the default setting recall was perfect, so why was the answer wrong, and why did the filter fix it when a bigger net did not?
Put it together
See high recall ground a wrong answer
In Grounded but wrong: the right catch, keep medium chunks and a net of top 3, choose a prediction and cast. Read the two meters and name the fish the model reads first.
Try a bigger net and a reranker
Raise the net to top 6, then turn on Rerank the catch. Check whether the answer changes and which fish stays first.
Fix it at the source, then complete it
Turn on Throw back superseded fish, then switch to small chunks and watch recall drop to 1 of 2. Use Rerank the catch to bring the final-sale rule back into the net.
A voice agent must reply within a second, and its retrieval often ranks a near-miss above the right chunk. Which change fits?
Grounded but wrong
A grounded answer is one the model drew from retrieved sources rather than from its training. Grounded is not the same as correct. When the source is stale, superseded or simply wrong, a faithful model repeats it, often with a citation that makes the error look trustworthy.
Recognise it by the pattern: the answer quotes a passage that really exists in your corpus, and that passage is out of date. An answer with facts that appear in no document is a different failure, a model inventing content.
Fix it where it starts, in the data:
- Remove or archive superseded documents, and make re-ingestion part of publishing a new version.
- Add metadata such as
status(current or superseded),effective_dateorregionwhen documents are ingested, and store it with each vector when they are indexed. - Filter retrieval on that metadata, so only current documents are searched. RAG Engine's metadata filter is in Preview at the time of writing: v1beta1 API only, not in serverless mode, and it needs a metadata schema on the corpus.
An instruction such as "prefer the newest document" is a weak patch: the model can only follow it if both versions are retrieved and each chunk shows its date, and it does nothing to stop retrieval from feeding the old one.
Choosing a backend
Google Cloud offers three backends, from most managed to most control.
Each lane below is one backend, and each step runs one lane through every pipeline stage. Before you step, predict which lane lets you chunk the documents yourself while Google runs the index.
- Agent Search (formerly Vertex AI Search) is an out-of-the-box RAG system. It handles parsing, chunking, embedding and indexing over your websites and documents, and its generated summaries come with citations and links. Start here.
- is 's managed RAG pipeline, built around a corpus you import files into. You configure the pipeline: chunk size and overlap, the embedding model, the vector database (its managed default, Vector Search, Feature Store, or third-party vector databases such as Pinecone or Weaviate), top-k and reranking.
- Vector Search is a vector database you query directly. You supply the
embeddings and build ingestion, chunking and ranking yourself. Agent
Retrieval (formerly Vector Search 2.0) sits a little closer to managed: it
stores your documents with their vectors, can generate the embeddings with
built-in models or take yours, and offers hybrid search and reranking. You
either prepare and chunk the data objects you load and write the query
yourself, or, in Preview, let its managed ingestion pipeline import
documents and videos from a data store, parse, segment, embed and index
them, and search them with the
SearchDocumentsAPI. Choose either when you need direct control of how vectors are stored and queried; custom embeddings alone are not a reason, since Agent Search accepts them too.
Each lane down buys control and costs engineering time. Move down only for a need the lane above it cannot meet.
A retrieval call to RAG Engine with a reranker looks like this (Python, Vertex AI SDK):
from vertexai import rag
config = rag.RagRetrievalConfig(
top_k=10, # candidates to rerank; all ten come back in reranked order
ranking=rag.Ranking(
rank_service=rag.RankService(model_name="semantic-ranker-default@latest"),
),
)
response = rag.retrieval_query(
rag_resources=[rag.RagResource(rag_corpus=corpus_name)], # your corpus's resource name
text="How many days do I have to return an item?",
rag_retrieval_config=config,
)Pass only the first few reranked chunks to the model.
In an agent, the same retrieval sits behind a tool, so the model decides when to search and the runtime runs it.
Sources
Show 12 sourcesHide sources
| Source | Publisher | What it supports |
|---|---|---|
| RAG Engine overview (opens in a new tab) | Google Cloud | stages: ingestion, transformation, embedding, indexing, retrieval, generation |
| Fine-tune RAG transformations (opens in a new tab) | Google Cloud | chunk_size default 1,024 tokens; chunk_overlap default 256 tokens |
| Retrieval and ranking (opens in a new tab) | Google Cloud | ranking API under 100 ms; LLM reranker, one to two seconds, Gemini models; RagRetrievalConfig with top_k and Ranking |
| Use metadata search (opens in a new tab) | Google Cloud | metadata_filter on retrieval |
| Vector database choices in RAG Engine (opens in a new tab) | Google Cloud | RagManagedDb default, Vector Search, Feature Store, Weaviate, Pinecone |
| Agent Search (opens in a new tab) | Google Cloud | formerly Vertex AI Search; out-of-the-box RAG system; citations and links; Vector Search for direct control of a vector database |
| Agent Retrieval (formerly Vector Search 2.0) overview (opens in a new tab) | Google Cloud | documents stored with vectors; embeddings generated by built-in models or supplied |
| Search documents in a data store (opens in a new tab) | Google Cloud | retrieved 2026-12-02: Preview; the managed ingestion pipeline imports document and video files from data stores into Agent Retrieval as Data Objects and Collections and handles parsing, segmentation, embedding and indexing; the SearchDocuments API searches the result |
| Agent Retrieval reranking (opens in a new tab) | Google Cloud | semantic reranking powered by the ranking API; RRF as the primary ranker that fuses semantic and text results; rechecked 2026-12-02: the RRF ranker takes a weights array for the fusion of the underlying searches, for example equal weights of 1.0 for the semantic and the text search |
| Try Agent Retrieval (opens in a new tab) | Google Cloud | semantic, text or both for hybrid search, merged with Reciprocal Rank Fusion; RRF alpha from 1.0, pure semantic, to 0.0, pure keyword; the Gemini Enterprise Agent Platform Ranking API |
| Evaluation of unranked retrieval sets (opens in a new tab) | Manning, Raghavan and Schütze, Introduction to Information Retrieval (Cambridge University Press, 2008) | retrieved 2026-11-18: precision is "the fraction of retrieved documents that are relevant"; recall is "the fraction of relevant documents that are retrieved"; precision measured at a fixed number of retrieved results is "Precision at k" |
| About hybrid search (opens in a new tab) | Google Cloud | RRF sums the reciprocal ranks of each item across the ranked lists |
Suggested videos
Show 2 videosHide videos
Advanced RAG techniques for developers (opens YouTube in a new tab)
Covers the exact pipeline the lesson traces: chunking, retrieval, reranking, then grounding the LLM call.
Note: Older (2024), and doesn't name precision or recall.
Give your app search superpowers: Agent Retrieval (Vector Search 2.0) (opens YouTube in a new tab)
Current Agent Retrieval (Vector Search 2.0) demo of the managed retrieval step.
Note: A product demo: no chunk-size or top-k tuning.
Review
Name the six stages of a RAG pipeline in order.
Check yourself
An HR agent tells employees the daily travel allowance from the 2023 policy, quoting it word for word. The 2025 policy is in the same corpus. What is the best fix?