Skip to content

How RAG Works in AI Search and What It Means for AEO

Documents being searched and fed into a glowing network that returns an answer, illustrating RAG in AI search

Understanding RAG in AI search is as important as understanding the models themselves. Retrieval-Augmented Generation is the process that lets an AI assistant look up current information, read a few sources and write an answer grounded in them. If your content is not retrieved, it cannot be cited, no matter how good it is.

This guide explains how RAG works step by step, from ingestion to answer generation, and what it means for AEO. It includes a small working retrieval experiment you can run on your own documents, plus a clear note on what such experiments can and cannot prove.

What is Retrieval-Augmented Generation (RAG)?

Short answer: RAG combines a search step with a language model. The system first retrieves relevant documents for a question, then gives them to the model as context, so the answer is based on those sources rather than only on what the model learned during training.

The idea was formalized in a 2020 research paper on retrieval-augmented generation. Today, many AI search products follow a similar pattern when they browse the web, although each company builds and tunes its own system.

What is the difference between parametric knowledge and retrieved information?

Short answer: Parametric knowledge is what a model learned during training and stores in its weights. Retrieved information is fetched at question time from an index or the live web. Retrieval keeps answers current and lets the system cite sources.

Topic Parametric knowledge Retrieved information
Source Training data Search index or live web
Freshness Fixed at training time Current
Citations Usually none Can link to sources
What you can influence Slowly, through your public footprint Directly, through crawlable, clear content

How are documents ingested and indexed?

Short answer: Crawlers fetch pages, systems extract the main text, split it into chunks and store those chunks with metadata such as URL, title and date. Content that cannot be fetched or extracted never enters the index.

This is why technical access matters so much for RAG in AI search. Blocked crawlers, JavaScript-only content and cluttered layouts all reduce what gets ingested. Our guide to JavaScript rendering for AI search covers one of the most common gaps.

How do embeddings and vector search work?

Short answer: An embedding model turns each chunk and each question into a list of numbers that captures meaning. Vector search then finds chunks whose numbers are closest to the question, even when they use different words.

For example, a question about “connecting to Salesforce” can match a chunk that says “integrates with Salesforce”, because their meanings are close. Many systems combine this with keyword search, since exact terms such as product names still matter.

How do semantic retrieval and reranking work in RAG for AI search?

Short answer: Semantic retrieval gathers a broad set of candidate chunks. A reranker then scores each candidate against the question more carefully and keeps only the best few for the model.

Reranking explains why clear, self-contained passages tend to win in RAG in AI search. A chunk that answers the question directly in its first sentence scores better than one where the answer is buried under an introduction.

How do context windows shape source selection in RAG for AI search?

Short answer: The model can only read a limited amount of text per answer, so the system selects a handful of chunks. Pages that are not among those few cannot influence the answer or appear as a citation.

In RAG in AI search, selection usually balances relevance, diversity of sources and trust signals. As a result, a site might be retrieved but still dropped at this stage if other sources answer the same point more clearly or carry more authority.

How does retrieved information support answer generation?

Short answer: The selected chunks are placed in the prompt with instructions to answer from them. The model writes the answer, and systems that support citations link back to the sources it used.

Here is a simplified view of the full flow:

  1. User query: a natural language question.
  2. Retriever: search and relevance scoring across the index.
  3. Knowledge sources: indexed documents and web pages.
  4. Context assembly: the most relevant retrieved passages.
  5. Large language model: grounded answer generation.
  6. Generated answer: a response with source references where supported.

How do you build a local experiment to study RAG in AI search?

Short answer: Put a few text documents in a folder, split them into chunks, rank the chunks for a question and look at which ones would be sent to the model. The script below does this with scikit-learn, without any paid API.

#!/usr/bin/env python3
"""A tiny retrieval experiment: chunk documents, rank chunks for a question,
and assemble the context an LLM would receive.

Install: pip install scikit-learn
Usage:   python mini_rag.py docs_folder "your question"
"""
import pathlib
import sys

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


def chunk(text, size=80, overlap=20):
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]


def load(folder):
    chunks = []
    for path in sorted(pathlib.Path(folder).glob("*.txt")):
        for i, piece in enumerate(chunk(path.read_text(encoding="utf-8"))):
            chunks.append({"source": f"{path.name}#{i}", "text": piece})
    return chunks


def retrieve(chunks, question, k=3):
    vectorizer = TfidfVectorizer(stop_words="english")
    matrix = vectorizer.fit_transform([c["text"] for c in chunks] + [question])
    scores = cosine_similarity(matrix[-1], matrix[:-1]).ravel()
    ranked = sorted(zip(scores, chunks), key=lambda x: x[0], reverse=True)
    return [(round(float(s), 3), c) for s, c in ranked[:k]]


def build_prompt(question, hits):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for _, c in hits)
    return (
        "Answer the question using only the sources below. "
        "Cite sources in brackets.\n\n"
        f"Sources:\n{context}\n\nQuestion: {question}"
    )


if __name__ == "__main__":
    chunks = load(sys.argv[1])
    hits = retrieve(chunks, sys.argv[2])
    for score, c in hits:
        print(f"{score:.3f}  {c['source']}")
    print("\n--- Prompt sent to the model ---\n")
    print(build_prompt(sys.argv[2], hits))
    # To generate an answer, send this prompt to any LLM API you are licensed to use.

We tested it with three short documents about a fictional company. For the question “Does Acme work with Salesforce?”, the integrations document ranked first by a wide margin, while the company history page scored zero. You can then send the printed prompt to any language model you are licensed to use.

Try rewriting one document so the answer sits in its first sentence, and run the test again. You will see how clarity and specific wording change retrieval scores.

Why can local experiments not establish ranking factors?

Short answer: A local experiment shows how retrieval works in principle, not how ChatGPT, Google or Perplexity rank sources. Their systems use proprietary models, indexes, trust signals and tuning that no outside test can reproduce.

So use experiments on RAG in AI search to build intuition, not to claim ranking factors. The lessons that do transfer are general: content must be accessible, passages should answer questions clearly and specific terms help matching. For a broader view of why some brands win, see our article on why AI recommends your competitors.

Frequently asked questions about RAG in AI search

Do all AI assistants use RAG?

Most AI search products retrieve web content for current questions, but implementations differ and companies do not publish full details. Some answers still come only from training data.

What does RAG in AI search mean for content teams?

Write passages that answer one question clearly and make sure crawlers can reach them. Retrieval favors content that is accessible, specific and easy to extract.

Does chunk size matter for my website?

You cannot control how each system chunks your pages, but short, well-headed sections make it more likely that a chunk contains a complete answer.

Can I optimize for embeddings directly?

Not reliably. Clear language, specific terms and complete answers help across systems. Tricks aimed at one model rarely generalize.

Is the local RAG script production-ready?

No. It is a teaching tool. Production systems use embedding models, vector databases, rerankers and evaluation pipelines.

Next step

Run the script on five of your own pages saved as text and ask the questions your buyers ask. If the right page does not rank first, rewrite its key section so the answer comes first.

Want more practical guides on RAG in AI search? Browse the latest articles on the Blippu blog.

See all articles