Skip to content
Easy AI How-To

AdvancedGeneralBuilding

Upgrade your RAG from keywords to embeddings

Keyword search finds passages that share words with the question, so it misses the moment someone says "money back" instead of "refund." This guide upgrades the simple RAG pipeline to search by meaning with embeddings, using a free local model or OpenAI's embeddings API. You'll measure the difference on your own documents with a small test and try hybrid search for exact codes and names. Grok still writes the cited answer.

Time
About 35 minutes
Checked
Tools
Sentence Transformers quickstart, all-MiniLM-L6-v2 model card, OpenAI embeddings guide, OpenAI API pricing, xAI models

If a button name on the screen does not match this guide, follow the action. These products rename buttons often. This is an advanced guide: it uses code, and each technical term is explained the first time it appears. Model names and prices change, so check the linked docs before you ship.

Steps

  1. See why keyword search misses

    The simple RAG pipeline finds passages with TF-IDF, which matches words. People don't search with your document's words, though. They ask "Can I get my money back?" when the page says "refund."

    An embedding fixes that. It's a list of numbers (a vector) that an embedding model produces for a piece of text. Texts with similar meanings get similar vectors, even when they share no words. You embed every chunk once, embed each question, and pick the chunks whose vectors point the same way.

    We tested both methods on six short help pages for a made-up kettle company, with 12 questions written in everyday words. Keyword search ranked the right page first for 4 of the 12. Embeddings got all 12. One keyword miss shows the problem: for "What does E4 mean?", TF-IDF ranked the warranty page first, because it also contains the word "does."

  2. Pick where your embeddings come from

    Grok still writes the answer. The embeddings come from a separate, much smaller model. Two good starting points:

    • Local and free: all-MiniLM-L6-v2 through the Sentence Transformers library. It's a 90 MB download, runs on an ordinary laptop CPU, turns text into 384 numbers, and is licensed Apache 2.0. Your documents never leave your machine for this step. It works best in English and reads only the first 256 tokens of each chunk, so keep chunks around 150 words.
    • Hosted: OpenAI's text-embedding-3-small. It returns 1,536 numbers per text, accepts up to 8,192 tokens per input, and cost $0.02 per million tokens when this was checked. That's enough to embed a few thousand pages for well under a dollar.

    The one rule: embed your documents and your questions with the same model. Vectors from different models can't be compared.

  3. Install the libraries

    In the folder with your docs directory:

    python3 -m venv .venv && source .venv/bin/activate
    pip install sentence-transformers scikit-learn numpy openai
    export XAI_API_KEY="your-key-here"
    

    On Linux without an NVIDIA GPU, run pip install torch --index-url https://download.pytorch.org/whl/cpu first. That gets the CPU-only build of PyTorch and skips a download of several gigabytes. A warning about "unauthenticated requests to the HF Hub" the first time you load the model is harmless.

  4. Embed your chunks once and save them

    Embedding is the slow part, so do it once and save the results. Save this as rag.py and run python rag.py. It reuses the chunking from the simple RAG guide.

    import json
    from pathlib import Path
    
    import numpy as np
    from sentence_transformers import SentenceTransformer
    
    EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
    model = SentenceTransformer(EMBED_MODEL)
    
    def load_chunks(folder="docs", size=150, overlap=30):
        chunks = []
        for path in sorted(Path(folder).glob("*.md")):
            words = path.read_text().split()
            for start in range(0, len(words), size - overlap):
                text = " ".join(words[start:start + size])
                chunks.append({"source": f"{path.name}#{start}", "text": text})
        return chunks
    
    def embed_documents(texts):
        return model.encode_document(texts, normalize_embeddings=True)
    
    def embed_query(text):
        return model.encode_query([text], normalize_embeddings=True)[0]
    
    def build_index(folder="docs"):
        chunks = load_chunks(folder)
        vectors = embed_documents([c["text"] for c in chunks])
        np.save("index.npy", vectors)
        Path("index.json").write_text(json.dumps({"model": EMBED_MODEL, "chunks": chunks}))
        print(f"Embedded {len(chunks)} chunks into {vectors.shape[1]} numbers each")
    
    def load_index():
        meta = json.loads(Path("index.json").read_text())
        if meta["model"] != EMBED_MODEL:
            raise SystemExit("Index was built with a different model. Run build_index() again.")
        return meta["chunks"], np.load("index.npy")
    
    if __name__ == "__main__":
        build_index()
    

    index.npy holds the vectors and index.json holds the text and the model name. load_index refuses to mix models, which is the most common embedding bug. Run python rag.py again whenever your documents change. encode_document and encode_query let models that treat questions and passages differently do so. For this model they behave the same.

  5. Search by meaning

    Save this as search.py. normalize_embeddings=True scaled every vector to length 1, so a plain dot product (multiply the vectors number by number and add it up) gives the cosine similarity: 1 means the same meaning and 0 means unrelated.

    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.metrics.pairwise import cosine_similarity
    
    from rag import embed_query, load_index
    
    chunks, vectors = load_index()
    
    def semantic_search(question, k=4, min_score=0.25):
        scores = vectors @ embed_query(question)
        best = scores.argsort()[::-1][:k]
        return [{**chunks[i], "score": float(scores[i])} for i in best if scores[i] >= min_score]
    
    tfidf = TfidfVectorizer(stop_words="english")
    matrix = tfidf.fit_transform([c["text"] for c in chunks])
    
    def keyword_search(question, k=4):
        scores = cosine_similarity(tfidf.transform([question]), matrix)[0]
        best = scores.argsort()[::-1][:k]
        return [{**chunks[i], "score": float(scores[i])} for i in best if scores[i] > 0]
    
    def hybrid_search(question, k=4, pool=20, c=60):
        fused = {}
        for results in (semantic_search(question, pool, min_score=0), keyword_search(question, pool)):
            for rank, hit in enumerate(results):
                fused.setdefault(hit["source"], {**hit, "score": 0.0})
                fused[hit["source"]]["score"] += 1 / (c + rank + 1)
        return sorted(fused.values(), key=lambda h: h["score"], reverse=True)[:k]
    
    if __name__ == "__main__":
        for hit in semantic_search("Can I get my money back?"):
            print(f"{hit['score']:.2f}  {hit['source']}")
    

    Run python search.py. In our test, the refund page scored 0.44 and came first. The old keyword search is still here so you can compare the two. min_score drops chunks that are clearly unrelated: "What is the capital of France?" scored 0.05. Scores depend on the model, so check yours before you trust 0.25. Hybrid search is covered two steps down.

  6. Write questions that use different words than your documents

    A test is only useful if it asks questions the way real people do. Paste one of your documents into any AI chat app with this prompt. It makes the model avoid your document's wording, which is exactly what exposes weak retrieval.

    Prompt to paste

    Below is a page from our help docs. Write 5 questions a real customer might ask that this page answers.
    
    Rules:
    - Use everyday words. Do not reuse the page's key terms. For example, if the page says "refund", say "money back".
    - Make 1 question vague or misspelled, the way people really type.
    - Every question must be fully answered by the page. Do not invent facts that aren't on it.
    - Output CSV with two columns, question and expected, with no header. Put [file name] in the expected column.
    
    Page:
    [paste the document]

  7. Measure before and after

    Collect the questions in evals.csv, with the file that holds each answer:

    question,expected
    Can I get my money back if I change my mind?,refunds.md
    What does E4 mean?,errors.md
    

    Read every question yourself and delete any whose answer isn't really in that file. Then save this as eval_retrieval.py and run it:

    import csv
    
    from search import hybrid_search, keyword_search, semantic_search
    
    rows = list(csv.DictReader(open("evals.csv")))
    for name, search in [("keyword", keyword_search), ("semantic", semantic_search), ("hybrid", hybrid_search)]:
        top1 = top3 = 0
        for row in rows:
            files = [hit["source"].split("#")[0] for hit in search(row["question"], k=3)]
            top1 += files[:1] == [row["expected"]]
            top3 += row["expected"] in files
            if not files or files[0] != row["expected"]:
                print(f"  {name} missed: {row['question']!r} -> {files[:1]}")
        print(f"{name:8}  top-1: {top1}/{len(rows)}  top-3: {top3}/{len(rows)}")
    

    Top-1 means the right file came first. Top-3 means it was somewhere in the first three. Our 12-question run printed:

    keyword   top-1: 4/12  top-3: 6/12
    semantic  top-1: 12/12  top-3: 12/12
    hybrid    top-1: 11/12  top-3: 12/12
    

    Your numbers will differ. That's the point of running it: you find out on your own documents instead of trusting a blog post, including this one.

  8. Try hybrid search for codes and names

    Embeddings can blur exact strings like part numbers, error codes, and people's names. Hybrid search runs both searches and merges the two rankings with reciprocal rank fusion (RRF): each chunk gets 1 / (60 + rank) from each list, and the totals decide the order. That's hybrid_search in search.py. RRF uses only ranks, so you don't have to balance two different score scales.

    Hybrid isn't automatically better. In our test it lost one question that semantic search got right. For "Can I get my money back if I change my mind?", keyword search pushed the account page up because it also says "change." Keep hybrid only if your eval shows a gain, which is most likely when users type exact codes or product names.

  9. Answer with Grok, quoting first

    The answer step is the same as before, with a stronger prompt. Asking the model to copy the supporting sentences before answering makes made-up details easier to catch, because every claim has to point at real text. Save this as answer.py:

    import os
    from openai import OpenAI
    
    from search import semantic_search
    
    grok = OpenAI(api_key=os.environ["XAI_API_KEY"], base_url="https://api.x.ai/v1")
    
    def answer(question):
        hits = semantic_search(question)
        if not hits:
            return "I couldn't find that in the documents."
        context = "\n\n".join(f"[{h['source']}]\n{h['text']}" for h in hits)
        prompt = (
            "Answer the question using ONLY the context below.\n"
            "1. First, copy the exact sentences from the context that answer the question, each with its [source].\n"
            "2. Then write a short answer based only on those sentences, citing sources in square brackets.\n"
            "3. If the sentences don't fully answer the question, say what is missing. "
            "Do not fill gaps from your own knowledge.\n\n"
            f"Context:\n{context}\n\nQuestion: {question}"
        )
        response = grok.responses.create(model="grok-4.7", input=prompt)
        return response.output_text
    
    if __name__ == "__main__":
        print(answer("Can I get my money back if I change my mind?"))
    

    If your eval favored hybrid, import hybrid_search and use it here instead. Hybrid has no score cutoff, so you'll rely on the prompt's "say what is missing" rule for questions your documents don't cover.

  10. Optional: get embeddings from OpenAI instead

    To use the hosted model, export OPENAI_API_KEY. Then, in rag.py, replace the SentenceTransformer import, the EMBED_MODEL and model lines, and the two embed_ functions with:

    from openai import OpenAI
    
    EMBED_MODEL = "text-embedding-3-small"
    client = OpenAI()
    
    def _embed(texts):
        vectors = []
        for start in range(0, len(texts), 500):
            response = client.embeddings.create(model=EMBED_MODEL, input=texts[start:start + 500])
            vectors += [item.embedding for item in response.data]
        return np.array(vectors, dtype="float32")
    
    def embed_documents(texts):
        return _embed(texts)
    
    def embed_query(text):
        return _embed([text])[0]
    

    Run python rag.py again to rebuild the index, then rerun the eval. OpenAI's embeddings already come back at length 1, so the dot product still works. Sending 500 chunks per request keeps you under the API's limit of 300,000 tokens per request. Scores from a different model fall in a different range, so recheck min_score against a few off-topic questions.

  11. Check it before anyone relies on it

    Ask five real questions and open the cited file for each answer. Confirm that the quoted sentences really are in that file and that the answer doesn't add anything. Ask two questions your documents don't cover and make sure the app says so. Rerun eval_retrieval.py after every change to chunk size, model, or min_score, the same way the evals guide reruns tests after prompt changes.

Tips

  • Most RAG failures are retrieval failures. Print the sources and scores for every answer while you build, and look at them before you blame the model.

  • Rebuild the index whenever your documents or your embedding model change. Old vectors don't update themselves.

  • A NumPy file is fine for tens of thousands of chunks. Past that, or when several people need the index at once, look at a vector database or a vector extension for the database you already run.

  • Running the embedding model locally keeps your documents on your machine for the search step, but the chunks you retrieve still go to Grok with the question. Don't index anything you couldn't send to an API provider.

  • Keep model names in one constant. Check xAI's models page for current Grok models; grok-4.7 was the current model when this was checked.

Common questions

Do I need a vector database?

Not to start. A few thousand chunks fit in memory, and a dot product over them takes milliseconds. Add a vector database when the index gets too big for memory, changes constantly, or needs filters like "only HR documents."

Is semantic search always better than keywords?

No. It's better at paraphrases and synonyms, and it can be worse at exact strings like serial numbers. That's why the guide measures all three methods on your own questions instead of picking a winner up front.

Can I use Claude or ChatGPT for the answer step?

Yes. Retrieval doesn't depend on the answer model. Only the final call in answer.py changes. The OpenAI Responses API guide shows that call for OpenAI.

Does xAI have a built-in way to search my files?

xAI offers Collections, which stores your files with an embedding index and lets you search them through the API or the xAI Console. It's a good option when you don't want to run retrieval yourself. Building it by hand first, as here, shows you what to tune when a managed search misses.

Why do my scores look low?

Every model spreads its scores differently, so a 0.3 from one model isn't a 0.3 from another. Compare scores only within one model, and set min_score by checking a few questions you know are off-topic.

Free newsletter

Learn AI by doing, one how-to at a time

New how-tos across all of AI: everyday tools, RAG, agents, local models, and taking a proof of concept to production. Each one is something you can try yourself, because the best way to learn AI is by doing it. Free, and you can unsubscribe in one click.

Subscribe free

Opens our sign-up page on beehiiv. Privacy