AI · Concepts

Retrieval-Augmented Generation (RAG) Explained

By CertSharp Team~17 min readLast updated

Free practice quiz

Practice RAG and generative AI exam questions

Check what you just learned with exam-style Google Generative AI Leader questions. 30 free questions, no signup. Browse all Google Cloud certifications.

Take the free quiz

Quick Facts

RAG = retrieve relevant facts, add them to the prompt, then generate. It uses embeddings and vector search to find the right passages, reduces (but does not eliminate) hallucinations, and keeps answers current without retraining the model. It is an explicitly listed topic on both the Google Generative AI Leader and AWS AI Practitioner (AIF-C01) exam guides.

What is retrieval-augmented generation (RAG)?

Retrieval-augmented generation (RAG) is a technique that makes a large language model look things up before it answers. The system searches a trusted source — your documents, a database, or the web — for passages relevant to the question, adds them to the prompt, and the model generates an answer grounded in those passages. The model itself is not retrained. If the underlying model is new to you, start with what is an LLM.

The term comes from a 2020 research paper by Lewis and colleagues at Facebook AI Research, but the idea is now the default pattern for enterprise chatbots, internal knowledge assistants and AI search. If you are preparing for the Google Generative AI Leader or the AWS AI Practitioner exam, RAG is one of the concepts you are most likely to meet in scenario questions.

Why RAG exists: the problems it solves

A foundation model on its own has three limitations that matter in business settings:

  • Knowledge cutoff. It only knows what was in its training data, which stops at a point in time.
  • No private knowledge. It has never seen your HR policies, contracts, product specs or support tickets.
  • Hallucinations. When it lacks a fact, it can produce a fluent, confident and wrong answer.

Google's Generative AI Leader exam guide lists exactly these limitations — data dependency, the knowledge cutoff, bias, hallucinations — and names grounding and RAG among the recommended practices to address them. A useful way to remember it: fine-tuning changes what the model is; RAG changes what the model can see.

How RAG works, step by step: embeddings, vector search, grounding

1. Chunk and embed your documents (done ahead of time)

Source content — policies, manuals, product pages, tickets — is split into chunks of a few paragraphs. Each chunk is passed through an embedding model, which turns text into a vector: a long list of numbers that represents its meaning. Chunks about similar ideas end up with vectors that are close together, even when they use different words.

2. Store the vectors in a vector index

The vectors, plus a pointer back to the original text, go into a vector database or search index built for fast similarity lookups. This is the "library" the model will consult. When documents change, you re-embed and update the index — no model retraining involved.

3. Retrieve relevant chunks at question time

When a user asks a question, the question is embedded with the same model, and the index returns the chunks whose vectors are nearest to it (vector or semantic search). Many systems combine this with keyword search and a re-ranking step to push the most relevant passages to the top.

4. Ground the prompt

The retrieved chunks are inserted into the prompt alongside the user’s question, usually with an instruction such as "answer only from the sources below and cite them." This is the "augmented" part: the model now has the facts it needs in its context window.

5. Generate the answer

The foundation model writes a response based on the supplied context. Well-built RAG systems return citations or links to the source chunks so users can check the answer — one of the main reasons enterprises prefer RAG for factual Q&A.

A concrete example: an employee asks an HR assistant, “How many days of parental leave do I get?” Retrieval finds the two most relevant paragraphs of the current leave policy, the prompt becomes “Using only these policy excerpts, answer the question and cite the section,” and the model answers with the number and a link to the policy. When HR updates the policy next quarter, only the index changes.

RAG vs fine-tuning vs prompt engineering

These are the three customization levers you will be asked to choose between on both exams. They are complementary, not mutually exclusive, but each has a clear sweet spot.

 Prompt engineeringRAGFine-tuning
What changesThe instructions and examples you sendThe facts supplied in the prompt at query timeThe model's weights, via further training
Adds new knowledge?Only what fits in the prompt you writeYes, from an external source you controlPartly, but it is baked in and goes stale
Keeping data currentManualUpdate the index; no retrainingRequires another training run
Relative cost and effortLowestModerate (embeddings, index, retrieval)Higher (labeled data, training compute, evaluation)
Citations / traceabilityNoYes, can point to source passagesNo
Best forTask framing, format, tone; first thing to tryQ&A over private, large or changing dataConsistent style, specialized tasks or domain language

Exam shortcut: if a scenario stresses “up-to-date,” “internal documents,” “cite sources” or “without retraining,” think RAG. If it stresses “lowest cost” and “quickest” with no new data, think prompt engineering. If it stresses a consistent specialized style or behavior that prompting cannot achieve, think fine-tuning. Training a model from scratch is almost never the right answer at the foundational level.

Grounding with Google Search and your own data on Google Cloud

Google frames RAG under the broader idea of grounding: connecting model output to verifiable sources. The current GAIL exam guide asks you to differentiate grounding with first-party enterprise data (your own documents and databases), third-party data, and world data (public information), and it names three Google Cloud grounding offerings:

OfferingGrounds the model inTypical fit
Grounding with Google SearchPublic web information via Google SearchQuestions about recent events or public facts beyond the model's knowledge cutoff
Pre-built RAG with Agent SearchYour enterprise content, indexed for youFastest route to search and Q&A over company documents with little engineering
RAG APIsYour data, through a pipeline you assembleTeams that want control over chunking, embeddings and retrieval

A naming note: in April 2026 Google rebranded Vertex AI as the Gemini Enterprise Agent Platform, and the current exam guide uses the new product names (Agent Platform, Agent Search, Agent Studio). Much existing study material still says Vertex AI and Vertex AI Search, so expect to see both. The exam is about choosing the right kind of grounding for the scenario, not configuration details.

The key decision: public, fast-changing facts point to grounding with Google Search; private company data points to RAG over enterprise data. Getting that distinction right is a recurring theme in the Generative AI Leader exam guide and the GAIL cheat sheet.

Where RAG shows up on GAIL and AIF-C01

ExamWhere RAG appears in the official guideWhat you need to know
Google Generative AI LeaderSection 2 (Google Cloud's gen AI offerings, ~35%): Google Cloud's RAG offerings. Section 3 (Techniques to improve model output, ~20%): limitations, grounding techniques, how RAG affects outputWhen to recommend RAG or grounding vs prompting or fine-tuning; enterprise vs world-data grounding; Google's grounding offerings
AWS AI Practitioner (AIF-C01)Domain 3 (Applications of Foundation Models, 28%): define RAG and its business applications, vector database services, cost trade-offs of customizationAmazon Bedrock Knowledge Bases; vector stores such as OpenSearch Service, Aurora, Neptune, RDS for PostgreSQL; RAG vs fine-tuning vs in-context learning costs

The angle differs. GAIL asks what a leader should recommend and which Google offering fits. AIF-C01 asks which AWS service implements the pattern. If you are deciding between the two certifications, see GAIL vs AWS AI Practitioner.

Sample question: choosing the right grounding

Sample Question (GAIL — Techniques to improve model output)

A travel company's gen AI assistant must answer two kinds of questions: details of the company's own cancellation and refund policies, and current public information such as airport disruptions reported today. Which combination best reduces hallucinations for both?

  1. Fine-tune the model on the policies and on last year's news archive
  2. Use RAG over the policy documents, and grounding with Google Search for current public information
  3. Use grounding with Google Search for both types of question
  4. Use few-shot prompting with examples of good answers for both types of question

Answer: B. Private policies are first-party enterprise data, best served by RAG over the company's documents. Today's disruptions are fresh world data, best served by grounding with Google Search. A goes stale immediately and cannot know today's events. C cannot see private policies. D improves format and tone but supplies no new facts.

Notice the pattern: identify where the facts live (private vs public, static vs changing) before picking a technique. For more items like this, try the GAIL practice questions.

RAG limitations: what it does not fix

  • Garbage in, garbage out. If retrieval returns the wrong or outdated passage, the model will confidently answer from it. Data quality and freshness of the index matter as much as the model.
  • It can still hallucinate. The model may misread or over-generalize from retrieved text, or fill gaps when nothing relevant is found. Instructions to answer only from sources, citations and evaluation help.
  • Chunking and context limits. Answers that span many documents may not fit in the retrieved chunks or the context window, and poor chunking can split key facts apart.
  • Latency and cost. Every query adds an embedding call, a search and a longer prompt. That is usually cheaper than fine-tuning, but not free.
  • Access control. Retrieval must respect who is allowed to see which documents, or the assistant can leak restricted content to the wrong user.
  • Untrusted content. Retrieved documents or web pages can contain instructions that try to manipulate the model (indirect prompt injection), so sources need vetting.
  • It does not change behavior. RAG supplies facts, not a new writing style or skill. If you need consistent specialized behavior, combine it with prompting or fine-tuning.

These limitations are exactly why both exams pair RAG with responsible AI, human-in-the-loop review and ongoing evaluation. To build all of this into a study schedule, see the GAIL study plan.

What is chunking, and how do you choose a chunking strategy?

Chunking is how you split source documents before embedding them. It is the single most underrated lever in RAG quality: a chunk that is too small loses context, one that is too large dilutes the match and wastes prompt space.

StrategyHow it worksGood forWatch out for
Fixed-sizeSplit every N tokens or charactersQuick prototypes, uniform textCuts sentences and tables in half
Fixed-size with overlapSame, but consecutive chunks share some textProse where a fact can straddle a boundaryDuplicate content in results
Structure-awareSplit on headings, paragraphs, sections or code blocksManuals, policies, documentationVery uneven chunk sizes
Parent-childSearch small chunks, but hand the model the larger parent sectionLong documents needing surrounding contextMore complex indexing
Metadata-enrichedAttach title, section, date and permissions to each chunkFiltering by product, version or access rightsMetadata must be maintained

A few hundred tokens per chunk with modest overlap is a common starting point, but the right value depends on your documents and your questions, so test it instead of assuming.

How does vector similarity search actually work?

An embedding model turns text into a vector with hundreds or thousands of dimensions. Retrieval ranks stored chunks by how close their vectors are to the question's vector, most often using cosine similarity (the angle between vectors), though dot product and Euclidean distance are also used. Here is a toy version with three dimensions so you can follow the math:

TextVectorCosine similarity to the query
Query: "How much parental leave do I get?"[0.90, 0.10, 0.00]1.00 (itself)
Chunk A: "Employees receive 16 weeks of parental leave."[0.80, 0.20, 0.10]about 0.98 (very close)
Chunk B: "The cafeteria closes at 3 pm on Fridays."[0.00, 0.10, 0.90]about 0.01 (unrelated)

Chunk A points in almost the same direction as the query, so it is retrieved; chunk B points somewhere else entirely, so it is not. Real systems return the top few matches (top-k), often after combining vector search with keyword search and re-ranking.

What are dense, sparse and hybrid retrieval?

MethodMatches onStrengthWeakness
Dense (vector) searchMeaning, via embeddingsFinds paraphrases and synonymsMay miss exact identifiers like part numbers or error codes
Sparse (keyword) searchExact terms, for example BM25Precise on names, codes and rare termsMisses answers worded differently
Hybrid searchBoth, combinedBest coverage in practiceMore components to tune
Re-rankingA second model reorders the top candidatesImproves precision at the topAdds latency and cost

If a RAG assistant works for conceptual questions but fails on questions that contain a product code, the usual fix is to add keyword search (hybrid retrieval), not to change the language model.

What does a RAG prompt look like?

You are a support assistant. Answer using ONLY the sources below.
If the sources do not contain the answer, reply "I don't know."
Cite the source number for every claim.

Sources:
[1] {chunk_1_text}
[2] {chunk_2_text}
[3] {chunk_3_text}

Question: {user_question}

Three details matter here: the instruction to use only the sources (reduces invented answers), the explicit fallback (so the model can decline), and the citation requirement (so users can verify). This is what the exam means by a grounded prompt.

How do you evaluate and debug a RAG system?

Evaluate retrieval and generation separately, because they fail for different reasons.

StageQuestion to askTypical metric or check
RetrievalDid the right chunk come back at all?Recall at k: for a set of test questions, how often the correct passage is in the top k results
RetrievalIs the right chunk ranked high?Precision at k, or mean reciprocal rank
GenerationIs the answer supported by the retrieved text?Faithfulness or groundedness: every claim traceable to a source
GenerationDoes the answer address the question?Answer relevance, judged by humans or a reviewing model
SystemIs it fast and affordable enough?Latency, tokens per query, cost per answer

Debugging rule of thumb: when an answer is wrong, first read the retrieved chunks. If the right text was not retrieved, fix chunking, embeddings, filters or add hybrid search. If it was retrieved but the model ignored or misused it, fix the prompt or the model choice.

Why do RAG systems fail? Common failure modes and fixes

SymptomLikely causeFix
Confident answer that is outdatedIndex not refreshed after documents changedAutomate re-ingestion; store document versions and dates
Answer misses a fact that is clearly in the documentsPoor chunking or the fact is split across chunksUse overlap or structure-aware chunking; increase top-k; add re-ranking
Fails on exact codes or namesDense-only retrievalAdd keyword or hybrid retrieval
Answers from the wrong product or versionNo metadata filteringTag chunks with product and version; filter at query time
Reveals restricted informationRetrieval ignores user permissionsEnforce access control on the index or at query time
Invents an answer when nothing matchesNo fallback instructionRequire "I don't know" when sources lack the answer; set a relevance threshold

Do long context windows make RAG obsolete?

Not in most enterprise cases. Pasting an entire document set into a long prompt works for small, static collections and quick experiments. RAG still wins when the corpus is too large to fit, when you pay per token and need to send only relevant passages, when documents change daily, when you need citations to specific passages, and when different users may see different documents. Many production systems combine both: retrieve broadly, then place the best passages into a generous context window.

Should you use prompting, RAG or fine-tuning? A checklist

  1. Start with prompt engineering. Clear instructions, examples and output format solve a surprising share of problems at the lowest cost.
  2. Add RAG if the model lacks facts. Private, large, fast-changing or citation-required knowledge calls for retrieval.
  3. Add fine-tuning if behavior is the gap. Consistent tone, structured output or a specialized task that prompting cannot reach calls for further training.
  4. Combine them when needed. A fine-tuned model that retrieves current facts is common in production.

RAG practice questions

1. A company wants its support chatbot to answer from product manuals that change monthly, without retraining the model. What approach fits best?

RAG over the manuals. Updating the index refreshes the knowledge without retraining.

2. A RAG assistant answers conceptual questions well but fails when users type exact error codes. What is the most likely improvement?

Add keyword search to create hybrid retrieval, because dense vector search can miss exact identifiers.

3. Which component converts text into numeric vectors that capture meaning?

An embedding model.

4. A team wants the model to answer in a strict legal-brief style regardless of the question. Which lever is the best fit?

Fine-tuning (or detailed prompting first). RAG supplies facts, not a new style.

5. Users from one department can see answers sourced from another department's confidential files. What is the root problem?

Retrieval does not enforce access control. Permissions must be applied to the index or at query time.

6. What does adding citations to a RAG answer primarily improve?

Traceability: users can verify the answer against the source passages.

Drill more questions like these in the Generative AI Leader practice exam or see the pricing page for the full question bank. If you are not yet sure the credential is worth your time, read is Google Generative AI Leader worth it.

Frequently asked questions

What is retrieval-augmented generation in simple terms?

Retrieval-augmented generation (RAG) is a technique where an AI system looks up relevant information from a trusted source — such as your company documents or a search engine — and gives it to a large language model along with the question, so the answer is based on those facts instead of only on what the model memorized during training.

Is RAG better than fine-tuning?

Neither is better in general; they solve different problems. RAG is the usual choice when the model needs access to specific, changing or private facts, and when you want citations. Fine-tuning is the usual choice when you need the model to adopt a consistent style, format or specialized behavior that prompting cannot achieve. Many production systems use both. On certification exams, scenarios that mention frequently updated data and avoiding retraining almost always point to RAG.

Does RAG eliminate hallucinations?

No. RAG reduces hallucinations by giving the model relevant facts, but a model can still misread the retrieved text, blend sources incorrectly, or answer confidently when retrieval returned nothing useful. Mitigations include instructing the model to answer only from sources, returning citations, evaluating retrieval quality, and keeping a human in the loop for high-stakes outputs.

What is the difference between RAG and grounding?

Grounding is the broader goal: connecting a model’s output to verifiable sources of information. RAG is one common way to achieve it, by retrieving documents and adding them to the prompt. Google’s Generative AI Leader exam guide treats grounding as the umbrella and distinguishes grounding with first-party enterprise data, third-party data, and world data such as Google Search.

Do I need to know how to build a RAG pipeline for GAIL or AIF-C01?

No. Neither exam asks you to write code. GAIL expects you to know what RAG and grounding are, when to recommend them, and which Google Cloud offerings provide them. AIF-C01 expects you to define RAG, recognize Amazon Bedrock Knowledge Bases, identify AWS services that can store embeddings in vector databases, and understand the cost trade-offs between RAG, fine-tuning and other customization approaches.

What is a vector database?

A vector database stores embeddings — numeric representations of text, images or other data — and finds the stored items most similar to a query vector. In a RAG system it is the index that retrieval searches. Examples include managed services from cloud providers and open-source options; on AWS, the AIF-C01 guide names Amazon OpenSearch Service, Amazon Aurora, Amazon Neptune and Amazon RDS for PostgreSQL.

What is chunking in RAG?

Chunking is splitting source documents into smaller passages before embedding them so retrieval can return focused, relevant pieces. Chunks that are too small lose context, and chunks that are too large dilute relevance, so strategies such as overlap, structure-aware splitting and parent-child retrieval are used.

How do you evaluate a RAG system?

Evaluate retrieval and generation separately. For retrieval, measure whether the correct passage appears in the top results (recall at k) and how high it ranks. For generation, check faithfulness to the retrieved sources and relevance to the question, and monitor latency and cost.

Does a long context window replace RAG?

Usually not. Long context helps with small, static document sets, but RAG remains useful when the corpus is large, changes often, needs citations, must respect per-user permissions, or when sending only relevant passages reduces cost and latency.

Test Your RAG Reasoning

500 Generative AI Leader practice questions on grounding, RAG, prompting and fine-tuning trade-offs. Start with 30 free questions per session with a free account — no card needed.