Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions

Bigger is not always better. Four questions decide an embedding model: vector size, how many tokens it reads, your domain and the cost. Then a 12-question test on real help articles: all-MiniLM-L6-v2 puts the right article first 10 times out of 12 (MRR 0.896), the larger bge-small-en-v1.5 9 times (MRR 0.861).

Chaand Sheikh

·27 November 2026Retrieval and RAG

What you will learn

  • Name the four things that decide an embedding model: dimension, context length, domain and cost
  • Estimate the storage a vector size needs for a million chunks
  • Compare two local models on your own questions with top-1 hits and MRR
  • Pick the smallest model that is good enough, and know the cost of switching later

Before you start

  • What an Embedding Actually Is
  • Basic Python and pip

There are many embedding models out there, and it's tempting to grab the biggest one on a leaderboard. Four things actually decide the choice: the vector size, how much text the model reads, your domain, and the cost. And bigger is not always better.

In this article we go through those four, then test two small local models on our own help-centre questions and let the numbers pick.

Picking a delivery vehicle

A shop delivers small parcels in a busy city. Which vehicle should it buy? A lorry has more capacity, but most parcels are small, so that space is wasted. Then there's range, how far it goes before it has to stop. Then the terrain: narrow city streets, not motorways. And the running cost, fuel and parking, every single day. So the cargo bike wins.

Choosing an embedding model is the same. Capacity is the dimension, range is the context length, terrain is your domain, and running cost is the cost.

Four questions for any embedding model capacity↓ Dimensionnumbers per vector range↓ Context lengthmax tokens read terrain↓ Domainyour words, your docs running cost↓ Costlocal or per token Pick the smallest model that passes your own test.
The four questions to ask before you pick a model.

Dimension: the size of each vector

Every chunk you store becomes one vector, and bigger vectors cost memory and search time. Stored as 4-byte floats:

DimensionBytes per vector1 million chunks
384about 1,500about 1.5 GB
768about 3,000about 3 GB
1,536about 6,000about 6 GB

That's just the vectors. More numbers can hold more detail, but they are not automatically better. Both models we test today use 384.

Context length: how much it reads

Each model reads up to a fixed number of tokens, and the rest is simply cut off. Your search results won't warn you. all-MiniLM-L6-v2 reads 256 tokens per input; bge-small-en-v1.5 reads 512. A longer limit helps with long chunks, but you still split your documents into chunks: one vector can't hold a whole manual. (More on cutting in Chunking Strategies for RAG.)

Domain: your words, not the web's

These models learn from general text, but your customers write in their own words, with your product's jargon. A customer writes my money still has not come back to my card. The help article says Refund timing. Refunds go back to the original card 5 to 7 working days after the parcel is scanned by the carrier. Not many shared words, so the model has to understand the meaning. The only benchmark that really counts is your own questions against your own documents.

Cost: where it runs

Local modelHosted embedding API
Fee per callNone, runs on your CPU or GPUPer token, check the provider's pricing page
SetupOne-time download (our two: about 91 MB and 133 MB)An API key
Your dataStays on your machineText is sent to the provider

The catch: switching models later means re-embedding every document, because vectors from two different models can't be mixed. Choose carefully the first time.

Our test: twelve questions

The project has 12 short help articles (data/help_docs.json) and 12 questions in customers' own words, each with the right article (data/queries.json). The question: does the right article come first? compare.py embeds every article and every question with each model, scores them all at once, and records where the right article lands (an excerpt of the function; the full file also records sizes and timings):

MODELS = {
    "all-MiniLM-L6-v2": {"name": "sentence-transformers/all-MiniLM-L6-v2", "query_prefix": ""},
    "bge-small-en-v1.5": {"name": "BAAI/bge-small-en-v1.5",
                          "query_prefix": "Represent this sentence for searching relevant passages: "},
}


def evaluate(short: str) -> dict:
    cfg = MODELS[short]
    model = SentenceTransformer(cfg["name"], device="cpu")
    texts = [d["title"] + ". " + d["text"] for d in DOCS]
    model.encode(texts[:2])  # warm-up
    t0 = time.perf_counter()
    doc_vecs = model.encode(texts, normalize_embeddings=True)
    ms = (time.perf_counter() - t0) * 1000
    q_vecs = model.encode([cfg["query_prefix"] + q["query"] for q in QUERIES], normalize_embeddings=True)
    sims = q_vecs @ doc_vecs.T
    rows, hits, rr = [], 0, 0.0
    for q, row in zip(QUERIES, sims):
        order = row.argsort()[::-1]
        ranked = [DOCS[i]["id"] for i in order]
        rank = ranked.index(q["answer"]) + 1
        hits += rank == 1
        rr += 1 / rank
        ...

Two details matter. The bge model expects a query prefix in front of questions (its instruction), and MiniLM doesn't. And rr += 1 / rank builds the MRR, mean reciprocal rank: 1 when the right article is always first, 0.5 when it's always second, and so on.

The results

python compare.py
ModelDimsMax tokensWeightsRight article firstMRR
all-MiniLM-L6-v238425690.9 MB10 / 120.896
bge-small-en-v1.5384512133.5 MB9 / 120.861

The smaller model came out slightly ahead on this data. Embedding the 12 articles also took 767 ms for MiniLM against 2,195 ms for bge on the lecture machine (your timings will differ). On your data the order may flip, and that's exactly why you test.

The misses are worth reading, because they tell you what each model confuses:

QuestionRight articleMiniLMbge-small
the headphones crackle and stopped working after a weekfaultywarranty first (rank 2)first
can I send something back that I just don't likereturnsaddress first (rank 4)faulty first (rank 3)
how fast will my package get hereshippingfirstreturns first (rank 2)
what does the guarantee coverwarrantyfirstfaulty first (rank 2)

Neither model is better everywhere. bge gets the broken-headphones question that MiniLM misses, and misses two that MiniLM gets.

How to choose

  1. Collect 20 to 50 real questions, each with the right document.
  2. Try two or three models. Start with small local ones.
  3. Measure how often the right document comes first, and the MRR.
  4. Pick the smallest model that is good enough, then check its input limit and its cost.

Good enough on your data, and cheap to run, beats bigger.

Common mistakes

  • Choosing from a public leaderboard alone. General benchmarks don't use your customers' words or your documents.
  • Forgetting the query prefix for models that expect one, such as bge. Without it the model is not used the way it was trained.
  • Chunks longer than the model's limit. Text past 256 or 512 tokens is silently dropped and never searched.
  • Mixing vectors from two models in one index. A new model means re-embedding everything.
  • Testing on three questions. With so few, one lucky hit decides the winner. Use 20 or more.

Quick recap

QuestionWhat to check
DimensionStorage and search time: 384 numbers is about 1.5 GB per million chunks
Context lengthMax tokens: 256 for MiniLM, 512 for bge-small; the rest is cut
DomainYour own questions against your own documents
CostLocal download vs per-token API, and where your data goes
The testTop-1 hits and MRR: 10/12 and 0.896 vs 9/12 and 0.861 here

Try it yourself

Run python compare.py and look at both models on the twelve questions. Then add five questions of your own to data/queries.json, and finally add a third sentence-transformers model to MODELS and compare again. To see what you can build once the model is chosen, read Real Embedding Models: an Open Model or a Provider API.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 31 of 66

Previous
Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
Next post
Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

On this page

  • Picking a delivery vehicle
  • Dimension: the size of each vector
  • Context length: how much it reads
  • Domain: your words, not the web's
  • Cost: where it runs
  • Our test: twelve questions
  • The results
  • How to choose
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.