06.1 Embedding Models and APIs in Practice
02.3 taught you what an embedding is: a dense vector where similar meaning lands near similar geometry, how cosine, dot product and Euclidean distance compare vectors, how sentence embeddings are pooled out of token vectors, and a provider-by-provider overview of where to get them. This lesson is the engineering manual for the part 02.3 only surveyed: calling embedding APIs and models correctly, at scale, and choosing one with evidence. You will learn every request field that matters on each provider (input shape, task types, dimensions, encoding, limits, errors, batch options and prices), how task-type prefixes and instructions work on open models, how to run embedding models on your own hardware, how to shrink and quantize vectors, what to do about inputs that are too long, how to pick a model on your own data rather than a leaderboard, how to version embeddings so you never silently mix spaces, and how to wrap every provider behind one small interface your code can actually depend on.
What you'll learn
- The common contract every embedding API shares — and the request fields each provider adds on top (task type, instructions, output dimension, output dtype, truncation)
- Every hosted embedding API in detail: OpenAI, Google Gemini, Voyage AI (what Anthropic recommends, since Anthropic has no embeddings API), Cohere, Jina, Mistral, OpenRouter, and the cloud-platform routes — with verified models, limits, errors and prices as of November 2026
- Task types and prefixes in depth: query vs document, classification, clustering, similarity — the instruction conventions of E5, BGE, Nomic, Qwen3-Embedding and friends, and what goes wrong when you forget them
- Running open-weight embedding models locally with
sentence-transformersand the lighterfastembed/ONNX runtime:encodeoptions,max_seq_lengthand truncation, GPU/CPU/MPS, quantized loading, and when self-hosting beats an API, and a dated shortlist of open-weight models with their licences and prefix conventions - Matryoshka truncation and vector-level quantization in code, and how to measure the quality cost on your own data
- Long inputs: truncation vs chunking vs long-context embedding models, and counting tokens before you send
- Multilingual and cross-lingual retrieval, domain-specific models, and multimodal embeddings
- Choosing a model with evidence: reading MTEB honestly, building a small domain test set, a runnable retrieval-evaluation harness (
recall@k, MRR), a selection scorecard, and the real cost of changing models - Versioning embeddings: the metadata every stored vector needs, a worked example of silently mixed models, and a guard that refuses to mix
- A small
Embedderprotocol — full code with OpenAI, Gemini, a localsentence-transformersadapter and a deterministic fake for tests — in the style of the 03.11 provider-agnostic client - The failure gallery and decision table for embedding work in production
What you don't need
- API keys. Every part has something you can run for free: pure-NumPy code on hand-made and synthetic vectors, and a deterministic fake embedder. Provider samples are labelled illustrative. The free local stand-in from 03.1, Part 12 covers chat APIs; for embeddings, the no-key path is the pure-Python parts plus open-weight models you download yourself.
- Vector databases or ANN indexes. Storing and searching millions of vectors is 06.3 and 06.4; the storage side is 06.5. This lesson produces the vectors and tells you what to record alongside them.
- Chunking strategy. How documents become chunks is Module 05; this lesson starts from "you have texts to embed".
- Prompt engineering. Embedding calls take no prompts; the only "prompt" is the task-type prefix or instruction, which this lesson covers in Part 3.
Setup
The provider samples need the official SDKs and python-dotenv. If you haven't set up a project yet, run uv init embeddings-practice --bare --python 3.13 && cd embeddings-practice first (see 03.1, Part 4 for the full setup), then:
uv add openai google-genai voyageai cohere mistralai python-dotenv numpy
# or: pip install openai google-genai voyageai cohere mistralai python-dotenv numpyThese commands install the newest release of each package. The provider samples were checked against openai 3.42.1, google-genai 2.34.0, voyageai 0.5.0, cohere 7.3.1 and mistralai 3.6.0 as of November 2026; a newer major version may rename parameters or response fields, so check the library's changelog if a call does not match. The local-runtime packages are installed in Part 4, which states the versions its samples were checked against. The .env file holds the keys you have:
# .env (never commit this file)
OPENAI_API_KEY=... # https://platform.openai.com
GEMINI_API_KEY=... # https://aistudio.google.com
VOYAGE_API_KEY=... # Voyage AI keys are created in MongoDB's Voyage console (AI Model APIs)
COHERE_API_KEY=... # https://dashboard.cohere.com
JINA_API_KEY=... # https://jina.ai
MISTRAL_API_KEY=... # https://console.mistral.ai
OPENROUTER_API_KEY=... # https://openrouter.aiNone of the runnable code in this lesson needs a key: Parts 5, 8, 9 and the fake embedder in Part 10 are pure Python/NumPy and run anywhere. Provider samples are written against each provider's official documentation as of November 2026 and marked Example output (illustrative — your exact output will differ):.
What you must be able to do after this lesson#
- Call an embedding API and explain the request and response contract
- Choose the right task type or prefix for queries and documents
- Run an open-weight embedding model locally
- Reduce dimensions with Matryoshka truncation and measure the quality cost
- Choose an embedding model using your own test set
- Explain why embeddings need versioning
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Embed the documents with input_type='document' and queries with 'query'." |
Part 3: Task types and prefixes |
| "The embeddings endpoint rejected our batch." | Part 2.1: OpenAI and Part 2.8: limits and errors |
"We need gemini-embedding-2 for image search." |
Part 2.2: Gemini |
| "Anthropic has no embeddings — what do we use?" | Part 2.3: Anthropic and Voyage AI |
| "Why did search break after we 'just' upgraded the model?" | Part 9: Versioning embeddings |
| "Can we run embeddings on-prem for compliance?" | Part 4: Open-weight models locally |
| "Should we self-host or call an API?" | Part 4.5: When self-hosting wins |
| "Our chunks are 10k tokens — the API truncates silently." | Part 6: Long inputs |
| "Which embedding model should we pick?" | Part 8: Choosing with evidence |
| "How do we swap providers without rewriting everything?" | Part 10: The Embedder protocol |
Part 1: The embedding API contract#
1.1 What every embedding API has in common#
Strip away the branding and every embedding API is the same shape:
flowchart LR
REQ["request: model + input texts<br/>+ optional task hint<br/>+ optional dimension/dtype"] --> API["provider's<br/>embedding model"]
API --> RESP["response:<br/>one vector per input<br/>+ usage (tokens)"]
IDX["Index time:<br/>embed every chunk once,<br/>store vector + metadata"] -.-> STORE[("vector store<br/>(Module 06)")]
QRY["Query time:<br/>embed the query<br/>with the SAME model"] -.-> API
STORE --> CMP["similarity search"]
API --> CMP- Input is one string or a list of strings (some providers also accept token arrays or images). One call returns one vector per input, in order.
- Model is a model ID. The model determines the vector's dimension, its language coverage, its maximum input length, its price and — critically — the space the vectors live in (02.3, 7.5).
- Task hint (Voyage
input_type, Geminitask_typeor text prefixes, Cohereinput_type, open-model instructions) tells an asymmetric model whether the text is a query or a document. Part 3 is devoted to it. - Dimension / dtype controls let you ask for shorter or compressed vectors: OpenAI
dimensions, Geminioutput_dimensionality, Voyageoutput_dimension, Cohereoutput_dimension, Voyageoutput_dtype, Cohereembedding_types, Jina's format fields. - Usage reports input tokens, which is what you're billed on. There are no output tokens — embedding is input-only pricing.
1.2 The asymmetry that shapes every embedding call#
Search is asymmetric: a query is short and asks a question; a document is long and states facts. Models trained for retrieval therefore treat the two sides differently — that's what task types, prefixes and instructions are for (02.3, 10.3). The engineering consequence: your embedder code needs two entry points, embed_documents() and embed_query(), even if they call the same model. Forgetting which side you're on is one of the most common silent quality bugs in RAG systems.
1.3 Is the vector normalized?#
Whether the returned vectors have length 1 decides whether the cheap dot product equals cosine similarity (02.3, 4.4). The rules differ per provider and per model:
| Provider / model | Normalized? | Where |
|---|---|---|
OpenAI text-embedding-3-* |
Yes | Documented; verify norms on your own data anyway |
Gemini gemini-embedding-2 |
Yes, including truncated dims | Automatic |
Gemini gemini-embedding-001 |
Only at 3072 dims | Normalize yourself below 3072 |
Voyage voyage-4* |
Yes | Documented; output_dtype variants still compare correctly |
Cohere embed-v5.0-* / embed-v4.0 / embed-*-v3.0 |
Yes (vectors are norm-1) | Mistral docs say the same for mistral-embed |
Mistral mistral-embed |
Yes (norm 1) | Their docs use Euclidean ≈ cosine ≈ dot interchangeably |
Open-weight sentence-transformers |
Depends on the model | normalize_embeddings=True or the model's similarity_fn_name |
| OpenRouter | Depends on the routed model | Check the underlying provider |
1.4 What "correct" means for an embedding call#
Four things can be silently wrong, and none of them raise an error:
- Wrong task hint — documents embedded as queries (or vice versa). Retrieval degrades a little, always silently.
- Mixed models — vectors from model A compared with vectors from model B. Shapes match; results are noise (worked example).
- Silent truncation — input longer than the model's limit gets cut, often without an error (Part 6).
- Un-normalized vectors scored with a dot-product index — ranking is distorted by vector length, not meaning.
This lesson's job is to make each of these impossible to do by accident.
Part 2: Provider embedding APIs, completely#
This part covers every hosted embedding route you are likely to meet, in the path's provider order (OpenAI → Anthropic → Gemini → OpenRouter), then the independent embedding vendors (Voyage, Cohere, Jina, Mistral) and the cloud-platform routes. Every model ID, dimension, limit, price and behaviour below was verified against the provider's official documentation as of November 2026; The official pages are linked under Further resources. Prices and limits change — treat every number here as "check the page", and prefer reading limits from the API where possible.
2.1 OpenAI#
OpenAI's embeddings endpoint is POST /v1/embeddings, called through the openai SDK's client.embeddings.create. The request fields that matter:
| Field | Values | Notes |
|---|---|---|
model |
text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002 (older) |
-3 models are current; ada-002 is the 2022 model still offered |
input |
string, list of strings, or list of token arrays | Cannot be an empty string; each item ≤ 8,192 tokens |
dimensions |
int ≥ 1, up to the model default | Only on text-embedding-3*; 1,536 default for -small, 3,072 for -large |
encoding_format |
"float" (default) or "base64" |
base64 returns each vector as an encoded string — smaller over the wire, you decode it yourself |
user |
string | End-user identifier for abuse monitoring |
Per-request limits (from the API reference): an input array holds at most 2,048 items, each input is capped at 8,192 tokens, and all inputs in one request sum to at most 300,000 tokens. Inputs over the per-input limit are rejected with an error, not truncated — count tokens first (03.7, 02.2). The response carries data (one {embedding, index, object} per input, in input order), model and usage with prompt_tokens/total_tokens — there are no output tokens.
# openai_embed.py — one file, self-contained
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENAI_API_KEY from .env
client = OpenAI()
texts = [
"How do I reset my password?",
"I forgot my login credentials.",
"What is your refund policy?",
]
response = client.embeddings.create(
model="text-embedding-3-small", # 1536 dims by default
input=texts, # list: one request, many vectors
encoding_format="float",
)
vectors = np.array([item.embedding for item in response.data])
print("Shape:", vectors.shape)
print("Norms:", np.linalg.norm(vectors, axis=1).round(4)) # ~1.0: already normalized
print("Billed tokens:", response.usage.total_tokens)
print("password vs forgot-login:", round(float(vectors[0] @ vectors[1]), 3))
print("password vs refund :", round(float(vectors[0] @ vectors[2]), 3))
# Matryoshka shortening: the API truncates AND re-normalizes for you
short = client.embeddings.create(
model="text-embedding-3-small", input=texts, dimensions=256,
)
print("Shortened shape:", (len(short.data), len(short.data[0].embedding)))Shape: (3, 1536)
Norms: [1. 1. 1.]
Billed tokens: 18
password vs forgot-login: 0.612
password vs refund : 0.198
Shortened shape: (3, 256)Points that matter for engineering:
- Batching is your friend but bounded. Send as many texts per request as the 2,048-item / 300k-token limits allow; split bigger jobs into chunks (06.2). One request with 500 texts is far cheaper in latency than 500 requests.
dimensionsis the supported way to shorten. Never sliceembedding[:256]yourself on this API — the API returns re-normalized vectors; manual slicing without re-normalizing breaks cosine comparisons (Part 5).encoding_format="base64"is for bandwidth, not quality: you get the same floats packed as a base64 string; decode withbase64.b64decode+np.frombuffer(..., dtype=np.float32). Use it when vectors cross a slow link or you store them raw.- No task type.
text-embedding-3-*takes no query/document hint; the same model embeds both sides identically. Its training still favours asymmetric retrieval — it's just not controllable. - Price: $0.02 per 1M input tokens for
text-embedding-3-small, $0.13 for-large, $0.10 forada-002(platform.openai.com/docs/pricing, November 2026). Cost =usage.total_tokens / 1e6 × price. - Batch API: OpenAI's Batch API accepts embedding requests at a discount for large offline jobs (03.9 covers the mechanics; the embeddings-specific details are in 06.2).
- Errors: over-length input →
context_length_exceeded-class 400 error; empty string → 400; rate limits → 429 withRetry-Afterhandling as in 03.8. - Knowledge cutoff: OpenAI documents that the v3 embedding models lack knowledge of events after September 2021 — rarely matters, but brand-new terms may embed weakly.
- Rate limits: measured in RPM (requests/minute), TPM (tokens/minute) and RPD (requests/day) per project per model, rising with your usage tier. As of November 2026 the model pages on developers.openai.com list the Free tier at 100 RPM / 40k TPM / 2k RPD on
text-embedding-3-*, and the paid tiers (Build, Launch, Grow) at 5,000–10,000 RPM and 1M–10M TPM. 429s carryRetry-After— 03.8.
2.2 Google Gemini#
Gemini has two current embedding models that behave differently enough to deserve separate treatment:
gemini-embedding-001 |
gemini-embedding-2 |
|
|---|---|---|
| Input | Text only | Text, images (≤6 PNG/JPEG), audio (≤180s), video (≤120s), PDF (≤1 file, ≤6 pages) — one shared space |
| Max input tokens | 2,048 | 8,192 (shared across modalities) |
| Task specification | task_type config parameter |
No task_type — task prefixes go inside the text |
Multiple inputs in contents |
One vector per text | One aggregated vector for the whole list unless each item is wrapped in its own Content |
| Output dims | output_dimensionality 128–3,072 (default 3,072) |
Same range; auto-normalizes truncated dims |
| Normalization | Only the full 3,072-dim output is normalized | Always normalized, including shortened |
| Latest update | June 2025 | April 2026 |
The task_type values for gemini-embedding-001 are RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, QUESTION_ANSWERING, FACT_VERIFICATION, CODE_RETRIEVAL_QUERY, SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING — pair query-side and document-side values as the names suggest.
# gemini_embed.py
import numpy as np
from dotenv import load_dotenv
from google import genai
from google.genai import types
load_dotenv() # reads GEMINI_API_KEY from .env
client = genai.Client()
docs = [
"Refunds are issued within 14 days of receiving the returned item.",
"The mobile app is available for iOS and Android.",
]
query = "can I get my money back"
# --- gemini-embedding-001: task_type parameter, one vector per text ---
doc_result = client.models.embed_content(
model="gemini-embedding-001",
contents=docs,
config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT", output_dimensionality=768),
)
query_result = client.models.embed_content(
model="gemini-embedding-001",
contents=query,
config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY", output_dimensionality=768),
)
D = np.array([e.values for e in doc_result.embeddings])
q = np.array(query_result.embeddings[0].values)
# 001 normalizes ONLY at 3072 dims: normalize truncated vectors yourself
D /= np.linalg.norm(D, axis=1, keepdims=True)
q /= np.linalg.norm(q)
print("001 shape:", D.shape, " scores:", (D @ q).round(3))
# --- gemini-embedding-2: task goes in the text; wrap each item in its own Content ---
# contents=["a", "b"] would return ONE aggregated vector for the pair — a classic bug.
def content(text):
return types.Content(parts=[types.Part.from_text(text=text)])
result = client.models.embed_content(
model="gemini-embedding-2",
contents=[
content(f"task: search result | query: {query}"),
content(f"title: none | text: {docs[0]}"),
content(f"title: none | text: {docs[1]}"),
],
config=types.EmbedContentConfig(output_dimensionality=768), # auto-normalized
)
print("2 vectors:", len(result.embeddings), "x", len(result.embeddings[0].values))001 shape: (2, 768) scores: [0.701 0.412]
2 vectors: 3 x 768For gemini-embedding-2, Google's documented text formats are: queries as task: search result | query: {content} (the question-answering, fact-checking and code-retrieval tasks follow the same query-and-document pattern with their own task names — copy the exact strings from the page), documents as title: {title} | text: {content} with title: none when there is no title, and symmetric tasks as task: classification | query: {content}, task: clustering | query: {content} or task: sentence similarity | query: {content} on both sides. Use one format consistently for everything you compare.
More engineering notes:
- The aggregation gotcha is the biggest trap.
gemini-embedding-2treats a bare list incontentsas one multimodal item and returns a single aggregated vector. Code ported from001or from OpenAI silently produces one vector for a batch of texts. Wrap each text intypes.Content, or use the Batch API. - Multimodal is real, not marketing.
gemini-embedding-2puts text, image, audio, video and PDF pages in one space, so "find the slide that matches this sentence" works. PDFs bill visual tokens (258 per page) against the same 8,192-token cap, and over-limit input is silently truncated. Among OpenAI, Anthropic and Gemini it is the only first-party embedding API that takes images (Voyage, Cohere and Jina also sell multimodal embedding models: 7.3); applications are Module 09. One nuance from the docs: for text-only tasks withgemini-embedding-2, Google recommends the task prefix in the prompt; for a single multimodal embedding it generally recommends not prefixing the text part — prefix per task type, not per request. - Batch API: Gemini's Batch API processes embedding requests at 50% of the standard embedding price — the steepest discount of any provider here.
- Migration: the
001and2spaces are incompatible; Google states existing vectors must be re-embedded. Same-dimension ≠ same space. - Pricing (aistudio.google.com/docs/pricing, November 2026):
gemini-embedding-2bills per input token by modality — text $0.20/1M tokens, image $0.45/1M ($0.00012 per image), audio $6.50/1M ($0.00016/s), video $12.00/1M ($0.00079/frame);gemini-embedding-001is $0.15/1M tokens. The free tier is free of charge but Google may use free-tier content to improve its products; the paid tier does not train on your data. Batch API is 50% off. - Rate limits: RPM / TPM / RPD measured per project, per model (requests-per-day resets at midnight Pacific); free tier vs paid tiers (Tier 1–3), and paid tiers additionally have spend-based limits evaluated over a rolling 10-minute window ($10 on Tier 1, $200 on Tiers 2 and 3). Exceeding any limit returns
429 RESOURCE_EXHAUSTED— aistudio.google.com/docs/rate-limits.
2.3 Anthropic: no embeddings API — Voyage AI#
Anthropic offers no embedding model and the anthropic SDK has no embeddings method. Its documentation says so plainly and recommends Voyage AI (now part of MongoDB), while advising you to evaluate several embedding vendors for your use case. This is the normal architecture: Claude generates answers; a separate embedding model does retrieval. Nothing requires the two to share a vendor.
Voyage keys are created in MongoDB's Voyage console (AI Model APIs) and read from VOYAGE_API_KEY. The voyageai SDK:
# voyage_embed.py
import numpy as np
import voyageai
from dotenv import load_dotenv
load_dotenv() # reads VOYAGE_API_KEY from .env
vo = voyageai.Client()
docs = [
"Refunds are issued within 14 days of receiving the returned item.",
"The mobile app is available for iOS and Android.",
]
query = "can I get my money back"
# input_type is Voyage's task hint; embeddings with and without it stay compatible
D = np.array(vo.embed(docs, model="voyage-4", input_type="document").embeddings)
q = np.array(vo.embed([query], model="voyage-4", input_type="query").embeddings[0])
print("Shape:", D.shape) # 1024 dims by default
print("Norms:", np.linalg.norm(D, axis=1).round(4), np.linalg.norm(q).round(4))
print("Scores:", (D @ q).round(3)) # normalized: dot = cosine
print("Billed tokens:", vo.embed([query], model="voyage-4", input_type="query").total_tokens)
small = vo.embed(docs, model="voyage-4", input_type="document", output_dimension=256)
print("Shortened:", len(small.embeddings[0]))Shape: (2, 1024)
Norms: [1. 1.] 1.0
Scores: [0.684 0.218]
Billed tokens: 9
Shortened: 256What the Voyage API gives you that others don't:
input_type("query"/"document") — Voyage documents that omitting it for retrieval degrades quality; it works by prepending an instruction to your text. Embeddings made with and withoutinput_typeare compatible, so you can add it later without re-embedding documents — but be consistent going forward.output_dimension— 256, 512, 1,024 or 2,048 on thevoyage-4*family; Matryoshka-trained, re-normalized by the API.output_dtype—"float"(default),"int8","uint8","binary","ubinary": quantized vectors straight from the API (4× smaller for int8, 32× for binary) — preview of Part 5 and 06.4.truncation(defaultTrue) — over-length inputs are truncated silently; settruncation=Falseto get an error instead. Decide per pipeline; silent truncation is how chunks lose their endings (Part 6).- Models (November 2026):
voyage-4-large(best quality),voyage-4(balanced),voyage-4-lite(lowest latency/cost) — all 32k context, 1,024 default dims (256/512/1,024/2,048 options), and all Voyage 4 series embeddings are compatible with each other (a documented shared space: embed documents with-large, queries with-lite). Domain models:voyage-code-4(32k),voyage-finance-2(32k),voyage-law-2(16k). Multimodal:voyage-multimodal-3.5viamultimodal_embed()(interleaved text/image/video, 32k). Contextualized chunks:voyage-context-4viacontextualized_embed()(120k tokens withenable_auto_chunking, else 32k total). Open weights:voyage-4-nano(Apache 2.0, on Hugging Face, self-hosted only; its model card and Anthropic's embeddings page give a 2,048-dim default but Voyage's own embeddings table lists 1,024, so setoutput_dimensionexplicitly). - Per-request caps (docs.voyageai.com reference, November 2026): at most 1,000 texts per call, and a total-token cap per call that depends on the model — 1M tokens for
voyage-4-lite/voyage-3.5-lite, 320k forvoyage-4/voyage-3.5/voyage-2, and 120k forvoyage-4-large,voyage-3-large,voyage-code-3,voyage-finance-2andvoyage-law-2. The docs don't listvoyage-code-4orvoyage-4-nanoin any group — assume the stricter cap and verify before batching large jobs. - Rerankers (
rerank-3,rerank-3-lite) exist on the same account — that's 06.9. - Pricing (docs.voyageai.com/docs/pricing, November 2026), per 1M input tokens with free-token tiers:
voyage-4-lite$0.02,voyage-4$0.06,voyage-4-large/voyage-context-4/voyage-code-4$0.12 — the first 200M tokens free on each;voyage-finance-2/voyage-law-2/voyage-code-2$0.12 with 50M free;voyage-multimodal-3.5$0.12 plus $0.60 per billion pixels. Batch API: 33% off standard pricing with a 12-hour completion window — and free tokens do not apply to batch jobs. - Rate limits (docs.voyageai.com/docs/rate-limits): expressed as RPM and TPM per model, org-wide by default with optional project-level caps. Base tier is 2,000 RPM on every model; TPM varies — 16M for
voyage-4-lite, 8M forvoyage-4/voyage-code-4, 3M forvoyage-4-large/voyage-context-4, 2M for multimodal. Higher usage tiers raise both (e.g.voyage-3.5reaches 16M TPM / 4,000 RPM at tier 2). Exceeding either returns429.
2.4 OpenRouter#
OpenRouter exposes an OpenAI-compatible embeddings endpoint at https://openrouter.ai/api/v1/embeddings, routing to embedding models from several upstream providers. The openai SDK works unchanged with a different base_url:
# openrouter_embed.py
import os
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENROUTER_API_KEY from .env
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
)
texts = ["How do I reset my password?", "I forgot my login credentials."]
response = client.embeddings.create(
model="openai/text-embedding-3-small", # "provider/model" IDs
input=texts,
dimensions=512,
)
vectors = np.array([item.embedding for item in response.data])
print("Shape:", vectors.shape)
print("Similarity:", round(float(vectors[0] @ vectors[1]), 3))Shape: (2, 512)
Similarity: 0.617Points:
- Model catalogue: browse
openrouter.ai/models?output_modalities=embeddingsor list programmatically via the models endpoint; IDs areprovider/model(e.g.openai/text-embedding-3-small,perplexity/pplx-embed-v1-0.6b). Verify a model actually accepts embeddings before building on it — OpenRouter routes many model types. - Pass-through fields: OpenRouter accepts
input_type(for upstream models that distinguish queries/documents) and multimodal inputs where the model supports them; fields theopenaiSDK doesn't know go throughextra_body={...}. - Provider routing: the
providerfield (order,allow_fallbacks,data_collection) controls which upstream serves the request — relevant for privacy and cost. - Same model, same space:
openai/text-embedding-3-smallvia OpenRouter produces the same vectors as direct OpenAI (modulo floating-point noise). The space is determined by the model, not the gateway — but two different upstream models behind one gateway are still incompatible (02.3, 7.5). - Errors follow OpenRouter's taxonomy: 400 bad request, 401 bad key, 402 insufficient credits, 403 forbidden (insufficient permissions, a guardrail block or a moderation flag), 408 timeout, 429 rate limit, 502 chosen model down or invalid response, 503 no provider meets your routing requirements — OpenRouter's errors page lists these eight, with 404
not_foundonly in its typed-error table and no 529 (03.8, 3.5). - Pricing and rate limits: OpenRouter bills the upstream model's token price (plus its credit-purchase fee); embeddings have no output tokens, so cost = input tokens × the routed model's rate — check the model page for the live number. There is no single embeddings RPM: paid models are bounded by the upstream provider's limits and your credit balance (a
402when it hits zero); free:freevariants are capped at 20 RPM plus 50–1,000 requests/day depending on credits purchased.GET /api/v1/keyreports your remaining limits — openrouter.ai/docs/api-reference/limits.
2.5 Cohere#
Cohere's Embed API (v2) is called through the cohere SDK's co.embed (cohere.ClientV2). The current lineup (docs.cohere.com/docs/models, November 2026):
| Model | Role | Context | Output dims (default) |
|---|---|---|---|
embed-v5.0-pro |
Best quality; text, images and fused text+image | 128k tokens | 256–2,048 (2,048) |
embed-v5.0-fast |
Lower latency/cost tier of the same family | 128k | 256–2,048 (2,048) |
embed-v4.0 |
Previous generation; text + images | 128k | 256–1,536 (1,536) |
embed-english-v3.0 / embed-english-light-v3.0 |
English-only v3 family | 512 tokens | 1,024 / 384 fixed |
embed-multilingual-v3.0 / embed-multilingual-light-v3.0 |
Multilingual v3 family | 512 tokens | 1,024 / 384 fixed |
Two facts in that table deserve emphasis: Pro and Fast share one embedding space — Cohere recommends indexing with Pro and querying with either, no re-embedding needed — and the v3 family caps input at 512 tokens, tiny by 2026 standards; anything longer must be chunked before it reaches the API.
# cohere_embed.py — needs: uv add cohere
import numpy as np
import cohere
from dotenv import load_dotenv
load_dotenv() # reads COHERE_API_KEY from .env
co = cohere.ClientV2()
texts = ["How do I reset my password?", "I forgot my login credentials."]
res = co.embed(
model="embed-v5.0-pro",
texts=texts,
input_type="search_query", # or "search_document", "classification", "clustering"
output_dimension=1024,
embedding_types=["float"], # or "int8", "uint8", "binary", "ubinary"
)
vectors = np.array(res.embeddings.float)
print("Shape:", vectors.shape)
print("Similarity:", round(float(vectors[0] @ vectors[1]), 3))
print("Billed tokens:", res.meta.billed_units.input_tokens) # billed input tokens; meta.tokens.input_tokens is the raw countShape: (2, 1024)
Similarity: 0.634
Billed tokens: 14Notes:
input_typeis Cohere's task hint:search_queryfor queries,search_documentfor the corpus,classification/clusteringfor symmetric tasks,imagefor image input. Usesearch_documentandsearch_queryconsistently, because the input type changes the vector; it is required for v3+ models.output_dimensionaccepts 256, 512, 768, 1,024, 1,536 or 2,048 on v5 (Matryoshka; default 2,048) — set it explicitly and record it.embedding_typesreturns compressed vectors in the same call:int8/uint8(1 byte per dim) orbinary/ubinary(bits packed into bytes — 1,024 dims → 128 bytes). You can request"int8"and"float"together and choose per use.- Images:
embed-v5.0-pro/embed-v5.0-fast/embed-v4.0take images via theimagesparameter (base64 data URLs, up to 20 MB combined, no per-call count limit) or fused text+imageinputs; the v3 family usesinput_type="image"and is limited to 1 image per call, 5 MB each.textsis capped at 96 strings per call. - Pricing (as of November 2026), per 1M input tokens:
embed-v5.0-pro$0.12 andembed-v5.0-fast$0.08, stated in Cohere's Embed 5 launch post (30 September 2026) Image inputs bill separately (v5: $0.40/1M image tokens, same post). Cohere's own pricing page (cohere.com/pricing) and its pricing explainer show no per-token figures, so the older models' rates (about $0.12 forembed-v4.0and $0.10 for the v3 family) are reported rather than confirmed here; check your Cohere dashboard. Trial keys are free. - Rate limits (docs.cohere.com/docs/rate-limits): the Embed endpoint allows 2,000 inputs/minute on both trial and production keys; image embedding is tighter — 5 inputs/min on trial keys vs 400/min on production.
EmbedJob(batch) is 5 req/min trial, 50/min production. Trial keys are also capped at ~1,000 API calls/month. - Rerank: Cohere's Rerank API is the best-known hosted reranker — 06.9.
2.6 Jina AI#
Jina's Embeddings API is at https://api.jina.ai/v1/embeddings and is OpenAI-compatible, so the openai SDK works with base_url="https://api.jina.ai/v1":
# jina_embed.py — needs: uv add openai
import os
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads JINA_API_KEY from .env
client = OpenAI(base_url="https://api.jina.ai/v1", api_key=os.environ["JINA_API_KEY"])
texts = ["How do I reset my password?", "I forgot my login credentials."]
response = client.embeddings.create(
model="jina-embeddings-v5-text-small", # see note below on model naming
input=texts,
)
vectors = np.array([item.embedding for item in response.data])
print("Shape:", vectors.shape)
print("Similarity:", round(float(vectors[0] @ vectors[1]), 3))Shape: (2, 1024)
Similarity: 0.598Notes (verified on jina.ai/embeddings, November 2026):
- Current families:
jina-embeddings-v5-textin two sizes — a 677M-parameter small (32K context) and a 239M nano (8K context) — with task-specific LoRA adapters and Matryoshka dimensions; andv5-omnimultimodal models (v5-omni-small~1.74B,v5-omni-nano~1.04B; one Jina page shows ~1.6B and ~0.9B) covering text, image, audio and video in one space, whose text output matches v5-text so Jina says text vectors need no re-embedding. Check the models page for exact IDs — Jina's naming has changed across versions, so confirm the current string rather than copying this example. - Request fields:
input(list),task(selects the LoRA adapter — see below),dimensions(Matryoshka truncation),normalized(L2-normalize; required for cosine-via-dot-product), and output format viaembedding_type(for examplefloat,binary,base64; the API reference also listsencoding_format). - Task adapters: v5-text ships task-specific LoRA adapters selected by an explicit
taskfield —retrieval.queryfor queries,retrieval.passagefor documents, plustext-matching,classificationandseparation(Jina's model page calls the clustering adapterclustering) for symmetric work. Using the wrong side of the query/passage pair measurably degrades results; confirm the exact strings on the models page. dimensions: pass e.g.dimensions=512for MRL truncation; the API truncates and L2-renormalizes server-side, and your vector store's dimension must match.- Rate limits (jina.ai/api-dashboard/pricing, November 2026), counted per API key: free key 100 RPM / 100k TPM, paid key 500 RPM / 2M TPM, premium 5,000 RPM / 50M TPM.
- Pricing: token top-up model (jina.ai, November 2026). Jina's pages do not state a per-million rate for the v5 models; earlier quotes were about $0.05 per 1M input tokens for small and $0.02 for nano, so check the dashboard before budgeting. Note Jina's weights are now stewarded by Elastic: open weights are CC BY-NC (non-commercial), commercial self-hosting needs Elastic's licence — another reason the API is the easy path.
- Jina also runs a Reranker API (
/v1/rerank) — 06.9.
2.7 Mistral#
Mistral's embeddings API serves two model families: mistral-embed (general text: fixed 1,024 dimensions, 8,192-token context, L2-normalized so cosine ≈ dot ≈ Euclidean) and code embeddings — codestral-embed-2505, optimized for code retrieval (8k context). client.embeddings.create accepts output_dimension, output_dtype (float/int8/uint8/binary/ubinary) and encoding_format (float/base64) on top of model and inputs:
# mistral_embed.py — needs: uv add mistralai
import numpy as np
from mistralai.client import Mistral
from dotenv import load_dotenv
load_dotenv() # reads MISTRAL_API_KEY from .env
client = Mistral()
texts = ["How do I reset my password?", "I forgot my login credentials."]
res = client.embeddings.create(model="mistral-embed", inputs=texts)
vectors = np.array([d.embedding for d in res.data])
print("Shape:", vectors.shape)
print("Norms:", np.linalg.norm(vectors, axis=1).round(4))
print("Similarity:", round(float(vectors[0] @ vectors[1]), 3))
print("Billed tokens:", res.usage.total_tokens)Shape: (2, 1024)
Norms: [1. 1.]
Similarity: 0.587
Billed tokens: 14Notes (docs.mistral.ai, November 2026):
mistral-embedreturns fixed 1,024-dim vectors regardless of input length; no task-type parameter — queries and documents use the same encoding.codestral-embed-2505is not fixed-dimension:output_dimensiondefaults to 1,536 and goes up to 3,072, and the docs state dimensions are ordered by relevance so keeping the first n is a smooth quality/cost trade-off — an MRL-style design, but verify on your data before trusting small dims. Its context is 8k tokens.- Pricing (docs.mistral.ai/inference/pricing):
mistral-embed$0.10/1M tokens,codestral-embed$0.15/1M (cached input billed at 10%). The batch API is 50% off, and regional EU/US endpoints cost 1.1×. - Rate limits are per-account and shown in the La Plateforme admin panel — there's no published RPM table; a free tier exists, but Mistral's help centre says Studio and API data may be used for training unless you turn off the "Anonymous improvement data" setting, so don't send real corpora through a free account without checking.
- Mistral also has La Plateforme batch processing for embeddings jobs.
2.8 Limits, rate limits, batch and errors#
| Provider | Per-request input cap | Total tokens per request | Batch/discount | Notable errors |
|---|---|---|---|---|
| OpenAI | 2,048 items, 8,192 tok each | 300,000 | Batch API at a discount | 400 on empty string / over-length input; 429 rate limits |
| Gemini 001 | list of strings | per-item 2,048 tok | Batch API at 50% | 2,048-token cap per item (count tokens first) |
| Gemini 2 | Content items |
8,192 shared | Batch API at 50% | aggregation gotcha (one vector for a bare list) |
| Voyage | 1,000 texts | 120k–1M total depending on model | Batch API at 33% off, 12h window | truncation=True default silently cuts over-length input |
| Cohere | texts ≤ 96 |
model-dependent | EmbedJob batch API | input_type mismatches degrade quality silently |
| Jina | input list |
model-dependent | — | rate limits per key/IP |
| Mistral | inputs list |
model-dependent | batch API at 50% | — |
| OpenRouter | input (OpenAI shape) |
per routed model | — | 402 credits, 403 permissions/guardrail, 429, 502/503 model or provider unavailable |
Price and rate-limit summary (all as of November 2026 — re-check the linked pages):
| Provider | Price per 1M input tokens | Rate limits — the form they take |
|---|---|---|
| OpenAI | $0.02 small / $0.13 large / $0.10 ada-002 | RPM + TPM + RPD per project per model, rising with usage tier (Free: 100 RPM / 40k TPM / 2k RPD) |
| Gemini | $0.20 text (embedding-2), $0.15 (001); per-modality rates for media | RPM + TPM + RPD per project per model; paid tiers add spend-based limits per 10 min |
| Voyage | $0.02 lite / $0.06 voyage-4 / $0.12 large+domain (200M/50M free tokens) | RPM + TPM per model, org-wide with optional project caps (base 2,000 RPM) |
| Cohere | $0.08 fast / $0.12 pro (v4 about $0.12 and v3 about $0.10, not confirmed on a Cohere page: 2.5) | Inputs/minute per endpoint (2,000/min Embed both key types; images 5 trial / 400 prod) |
| Jina | token top-up; about $0.05 small / $0.02 nano (not on Jina's pages: check the dashboard) | RPM + TPM per API key (free 100 RPM / 100k TPM; paid 500 / 2M) |
| Mistral | $0.10 mistral-embed / $0.15 codestral-embed | Per-account, shown in admin panel; free Experiment tier exists |
| OpenRouter | upstream model's price + credit fee | Credit balance (402) + upstream limits; free variants 20 RPM + daily caps |
Rules that hold everywhere:
- Count tokens before you send. Each provider has a counting endpoint or tokenizer (03.7, Part 2); for embeddings the simplest correct check is "my chunker's max token count < the model's input limit".
- Retries and backoff are exactly 03.8's subject: honour
Retry-After, cap attempts, and remember embeddings are cheap enough that a retry storm costs little but a stalled index costs a lot. - Cost model:
total_input_tokens × price_per_1M_tokens / 1e6. There is no output-token cost. Always readusagefrom the response — it's the billed truth (03.7). - Batch APIs (OpenAI, Gemini, Cohere, Mistral, Voyage) trade latency for price — right for backfills, wrong for query-time embeddings. 06.2 decides which jobs belong where.
2.9 The cloud-platform routes#
The same models are often reachable through your cloud provider instead of (or as well as) the vendor's own API. The model and its vector space stay the same — what changes is authentication, billing, regional/data-residency controls and which model versions are offered:
| Route | What it serves | Why you'd use it |
|---|---|---|
| Google Vertex AI | gemini-embedding-001 and gemini-embedding-2 (both GA; Google's Vertex model-versions page lists gemini-embedding-2 as GA from 22 April 2026), plus older English text-embedding-004/text-embedding-005 families |
GCP shops get IAM auth, regional endpoints, VPC-SC and the same billing; note Vertex-only knobs like document_ocr for PDFs |
| Azure (OpenAI Service / AI Foundry) | text-embedding-3-* as Azure deployments; AI Foundry also hosts Cohere Embed models (Microsoft's model list of 29 October 2026 shows embed-v-4-0, Cohere-embed-v5-Fast and Cohere-embed-v5-Pro, the v5 entries marked Preview — check the catalogue for current names) |
Azure governance, private endpoints, enterprise agreements; deployment names replace model IDs in the request |
| AWS Bedrock | Cohere Embed (cohere.embed-v4, cohere.embed-english-v3, cohere.embed-multilingual-v3) and Amazon Titan Text Embeddings (amazon.titan-embed-text-v2:0, 1,024 dims with 512/256 options) |
AWS-native IAM/networking; Bedrock's Cohere models lag the vendor's newest (check the model ID list — embed-v5 was announced for SageMaker, not necessarily Bedrock) |
| MongoDB (Voyage) | The Voyage models of Part 2.3 except voyage-4-nano (open weights, not served through this route) |
Voyage is MongoDB's; keys are created in its console — already the default route |
Two cautions. First, verify the model ID and version on the platform — text-embedding-3-small on Azure is the same space as on OpenAI (same weights), but a platform may lag a vendor's newest release by months, and a dated snapshot (codestral-embed-2505) pins you to one version deliberately. Second, platform billing differs: Vertex/GPU-hour-style or per-token rates, committed-use discounts and egress charges can flip the self-host-vs-API calculus in Part 4.5 — model the total cost, not just the token price.
2.10 Data retention and privacy pointers#
Embedding calls send your text to the provider exactly like chat calls do: the same data-use policies, retention windows and zero-retention options apply (02.9, Part 9, Module 12). Two embedding-specific notes:
- Vectors are sensitive too. Research shows text can often be reconstructed from its embedding (02.3, 10.7) — protect the vector store like the source documents, and delete vectors when you delete documents.
- OpenRouter's
data_collection: "deny"provider-routing option is the practical control when you must guarantee no upstream retains inputs.
Part 3: Task types and prefixes#
Every embedding model was trained for a kind of comparison. The task hint tells it which kind you want. The four canonical tasks:
| Task | What you compare | Provider mechanisms |
|---|---|---|
| Retrieval (asymmetric) | Short query ↔ long document | Voyage input_type="query"/"document"; Gemini 001 RETRIEVAL_QUERY/RETRIEVAL_DOCUMENT; Gemini 2 task: search result | query: vs title: ... | text:; Cohere search_query/search_document; E5/Qwen query:/passage: prefixes; OpenAI: none |
| Question answering | Question ↔ evidence passage | Gemini 001 QUESTION_ANSWERING; Gemini 2 task: question answering; Voyage: same retrieval pair |
| Fact verification | Claim ↔ evidence | Gemini 001 FACT_VERIFICATION; Gemini 2 task: fact checking |
| Symmetric (similarity, classification, clustering) | Like with like | Gemini 001 SEMANTIC_SIMILARITY/CLASSIFICATION/CLUSTERING; Gemini 2 task: sentence similarity/classification/clustering on both sides; Cohere classification/clustering; E5-style models: same prefix both sides |
3.1 The open-model conventions#
Hosted APIs hide the mechanism; open-weight models expose it as text you prepend. The conventions differ per family — this is why "just embed the string" fails on some models:
| Family | Query side | Document side | Source |
|---|---|---|---|
| E5 / E5-Mistral (intfloat) | "query: " + text |
"passage: " + text |
model card; 02.3 uses it |
| BGE v1.5 (English) (BAAI) | "Represent this sentence for searching relevant passages: " + text |
bare text | FlagEmbedding docs |
| BGE-M3 (BAAI, multilingual) | no prefix — embed queries and passages bare | bare text | FlagEmbedding docs (its table leaves the instruction cell empty) |
Nomic (nomic-embed-text-v1.5) |
"search_query: " + text |
"search_document: " + text |
model card |
| Qwen3-Embedding | "Instruct: {one-sentence task}\nQuery:{text}" |
bare text (no instruction) | HF model card |
| Gemini 2 | task: ... | query: {text} |
title: ... | text: {text} |
Google docs |
def get_detailed_instruct(task_description: str, query: str) -> str:
return f"Instruct: {task_description}\nQuery:{query}"
task = "Given a web search query, retrieve relevant passages that answer the query"
query_text = get_detailed_instruct(task, "What is the capital of China?")
# documents: embed the raw text, no instruction3.2 What forgetting the hint actually does#
On a symmetric-trained model the hint changes nothing. On an asymmetric one it shifts the query vector into the "looks-like-a-question" region of the space. A hand-made illustration (pure NumPy, real output):
import math
def dot(a,b): return sum(x*y for x,y in zip(a,b))
def unit(a): n=math.sqrt(sum(x*x for x in a)); return [x/n for x in a]
docs = [unit(d) for d in [[1.0,0.1],[0.2,0.9],[0.9,0.2]]]
q_plain, q_prefixed = unit([0.95,0.3]), unit([0.7,0.7])
for name,q in [("no prefix",q_plain),("with prefix",q_prefixed)]:
s=[round(dot(d,q),3) for d in docs]
print(name,"scores:",s,"-> best doc",max(range(3),key=lambda i:s[i])+1)no prefix scores: [0.979, 0.501, 0.996] -> best doc 3
with prefix scores: [0.774, 0.844, 0.844] -> best doc 2The "prefix" moved the query vector and flipped the winner — on real models the effect is smaller but consistent: the model authors measure it on thousands of queries, which is why you should too (Part 8). The engineering fix is structural: put the hint inside your Embedder (embed_query adds it, embed_documents doesn't) so it can't be forgotten per call.
3.3 Symmetric vs asymmetric — don't mix them up#
For duplicate detection, clustering and classification you compare like with like: use the symmetric task (SEMANTIC_SIMILARITY, classification, or the same prefix on both sides), not the query/document pair. Voyage's docs make the same point for input_type. Getting this wrong degrades quality silently in both directions.
Part 4: Open-weight models locally#
When data can't leave your infrastructure, when volume makes per-token pricing hurt, or when you need embeddings offline, you run an open-weight embedding model yourself. Two runtimes cover almost everything:
| Runtime | What it is | When to pick it |
|---|---|---|
sentence-transformers |
The reference library (PyTorch + transformers); every model card ships a one-line SentenceTransformer("org/model") |
Default choice: widest model coverage, built-in prompts/pooling/quantization helpers, training hooks |
fastembed |
Qdrant's ONNX Runtime library — no PyTorch dependency, small footprint, CPU-friendly | Serverless/lambda, minimal installs, Qdrant-adjacent stacks; supports dense, sparse, late-interaction, image models |
Both are pip-installable and run on CPU; GPU (CUDA) and Apple Silicon (MPS) accelerate the PyTorch path. The samples below were checked against sentence-transformers 6.2.0 and fastembed 0.9.1 as of November 2026. A plain install gives you the newest release, and a newer major version may change names or defaults (the encode_query and encode_document calls used here are the ones to check first), so read the changelog if a call does not match.
4.1 sentence-transformers: the encode contract#
# local_embed.py — needs: uv add sentence-transformers numpy
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") # ~90 MB, CPU-friendly
# encode() options that matter:
# batch_size — texts per forward pass; bigger = faster until memory binds
# normalize_embeddings — return unit vectors so dot product = cosine (an encode()
# argument, NOT a constructor argument — passing it to
# SentenceTransformer(...) raises TypeError)
# prompts — model's required query/document prefixes, registered once
# device — "cpu", "cuda", "mps"
# convert_to_numpy / convert_to_tensor
# A model with trained prefixes: register once, then encode_query/encode_document add them.
# Normalization is requested per encode call:
model = SentenceTransformer(
"intfloat/e5-small-v2",
prompts={"query": "query: ", "document": "passage: "},
)
docs = model.encode_document(
["Refunds are issued within 14 days."], normalize_embeddings=True,
)
q = model.encode_query(["can I get my money back"], normalize_embeddings=True)
print("dims:", docs.shape, "norm:", float((docs[0]**2).sum()**0.5))
# max_seq_length: models truncate silently beyond it
print("max_seq_length:", model.max_seq_length) # e.g. 512 for e5-small; set deliberatelydims: (1, 384) norm: 1.0
max_seq_length: 512Key facts:
prompts=(or the model's built-in prompt config) is how prefixes are applied correctly —encode_query()/encode_document()add them for you. This is the local-model equivalent of Voyage'sinput_type; forgetting it is the same silent quality bug as Part 3.similarity_fn_nametells you the model's trained metric (usuallycosine);model.similarity(a, b)applies it — don't hand-roll the wrong metric.max_seq_lengthdiffers per model (256 forall-MiniLM-L6-v2, 512 for e5-small, 32k for Qwen3-Embedding); over-length inputs truncate silently. Count tokens first.truncate_dim=gives Matryoshka shortening for MRL-trained models; for others it just loses information — measure before relying on it (Part 5).- Precision/quantization:
SentenceTransformer(..., model_kwargs={"dtype": "float16"})or the newerbackend/quantization options;sentence_transformers.quantization.quantize_embeddingsproduces int8/binary vectors calibrated on your data.
4.2 fastembed: the ONNX path#
# fastembed_demo.py — needs: uv add fastembed
from fastembed import TextEmbedding
model = TextEmbedding(model_name="BAAI/bge-small-en-v1.5") # downloads an ONNX model
# embed() returns a GENERATOR of float32 arrays; list() it
docs = list(model.embed(["Refunds are issued within 14 days."]))
print("dims:", len(docs[0]))dims: 384Notes (verified on PyPI fastembed 0.9.1, Apache-2.0, October 2026): ONNX Runtime instead of PyTorch — lighter, CPU-fast, serverless-friendly; fastembed-gpu for CUDA. It also covers sparse (SPLADE), late-interaction (ColBERT) and image embeddings, plus rerankers. The trade-off: fewer models and less flexibility than sentence-transformers; check its supported-model list for your model.
4.3 Hardware: CPU, GPU, MPS#
| Device | Reality |
|---|---|
| CPU | Fine for small models (≤ ~0.5B) and moderate batch jobs; embedding is throughput-bound, so cores and batch size matter more than clock speed |
| GPU (CUDA) | The right answer for bulk indexing of large corpora or big models; device="cuda" in sentence-transformers, providers=["CUDAExecutionProvider"] in fastembed |
| Apple Silicon (MPS) | Works via PyTorch MPS backend for moderate speedups; unified memory means large models can exceed comfortable RAM — watch memory pressure |
| Memory | Rough rule: model weights (params × bytes/param at your precision) + batch activations. A 0.5B model at fp32 ≈ 2 GB; an 8B at fp16 ≈ 16 GB |
4.4 Serving open models over HTTP#
For production you don't embed in-process — you serve the model:
- Hugging Face Text Embeddings Inference (TEI) — a dedicated Rust server for transformer embedding models with continuous batching, quantization and a
/embedAPI (github.com/huggingface/text-embeddings-inference). - vLLM — serves embedding/pooling models with high-throughput continuous batching alongside LLM serving (github.com/vllm-project/vllm; its pooling/embedding API).
- Ollama — serves open embedding models locally over an HTTP API (its
/api/embedendpoint) — the free local stand-in from 03.1, Part 12 is relevant here. - Managed hosts — Hugging Face Inference Endpoints, cloud GPU instances, or the provider's own open-model APIs (e.g. Voyage
voyage-4-nanois open-weight but self-hosted only).
Pattern level: put a load balancer and a queue in front, batch aggressively, and treat the embedding server like any other stateless service — health checks, autoscaling on queue depth, and model-version pinning (a silent model swap is the same mixed-space bug as Part 9).
4.5 When self-hosting wins and when it doesn't#
| Self-host wins when... | API wins when... |
|---|---|
| Data can't leave your infra (regulated, on-prem) | You want zero ops; the provider handles scaling |
| Very high, steady volume amortizes hardware | Spiky/low volume — per-token pricing is cheaper than idle GPUs |
| You need a niche/open model no API serves | You need frontier quality with no model-ops team |
| Offline/air-gapped or latency-critical local inference | You value the provider's latest models and updates |
| You need custom quantization/fine-tuning control | Time-to-production matters more than marginal cost |
The honest costs of self-hosting: you own model updates, GPU capacity, batching efficiency, monitoring and the quality-evaluation loop — and open models usually trail the best hosted models on retrieval quality for general text. For most teams the right answer is API for documents + a small local model for latency-critical queries, or API everywhere until volume forces the question.
4.6 A shortlist of open-weight embedding models (as of November 2026)#
Open-weight models change faster than any other row in this lesson, so treat this table as a starting shortlist to test, not a ranking. Each row was read from the model's own Hugging Face card in November 2026; open the card before you rely on a number, because cards are edited and new versions appear.
| Model | Size | Context | Output dims | Licence | Prefix / instruction convention | Worth knowing |
|---|---|---|---|---|---|---|
| Qwen3-Embedding (0.6B / 4B / 8B) | 0.6B–8B | 32K | 1,024 / 2,560 / 4,096; custom 32–4,096 (MRL) | Apache-2.0 | Instruct: {task}\nQuery:{text} on queries only |
100+ languages including programming languages; the 8B was No. 1 on the MTEB multilingual leaderboard when released (June 2025), so check today's board |
EmbeddingGemma (google/embeddinggemma-300m) |
~300M | 2,048 | 768; MRL to 512 / 256 / 128 | Gemma terms (accept on Hugging Face) | Google's task: ... | query: and title: ... | text: templates, applied by encode_query / encode_document |
Small enough for laptops and phones; 100+ languages; activations do not support float16, so use float32 or bfloat16 |
| BGE-M3 (BAAI) | not stated on the card | 8,192 | 1,024 | MIT | None: embed queries and passages bare | One model, three retrieval modes (dense, sparse lexical weights and multi-vector), which makes it popular for hybrid search (06.8) |
| Harrier-OSS-v1 (Microsoft; 270M / 0.6B / 27B) | 0.27B–27B | 32,768 (model cards) | 640 (270M) / 1,024 (0.6B) / 5,376 (27B) | MIT | Instruct: {task}\nQuery: {query} on queries only; last-token pooling, L2-normalised |
Model repositories published on Hugging Face on 30 March 2026; 94 languages tagged on the model cards (as of November 2026) |
| pplx-embed-v1 (Perplexity; 0.6B card) | 0.6B | 32K | 1,024 (MRL) | MIT | None | Native INT8 or binary output (the card says the INT8 vectors are unnormalised, so use cosine similarity) |
| voyage-4-nano (Voyage AI) | ~0.3B | 32,000 | 2,048; MRL to 1,024 / 512 / 256 | Apache-2.0 | Built-in prompts via encode_query / encode_document (trust_remote_code=True) |
Shares one embedding space with voyage-4, voyage-4-lite and voyage-4-large (2.3): develop or serve queries locally and index with the hosted model without re-indexing |
| jina-embeddings-v5 (small / nano) | 677M / 239M | 32K / 8K | MRL | CC BY-NC (non-commercial) | task adapters (2.6) |
Check the licence before any commercial self-hosting |
What this table is for:
- Licences differ in ways that block shipping. MIT and Apache-2.0 allow commercial use; the Gemma terms and CC BY-NC come with conditions. Read the licence line before you shortlist, not after you have built on the model.
- Several models want an instruction on the query side only (Qwen3-Embedding, Harrier, and Google's templates for EmbeddingGemma). That is the Part 3 rule again: put the instruction inside your
Embedder. Changing the query-side wording leaves stored document vectors valid (but changes results, so re-run your eval); changing the document-side text means re-embedding the corpus. - Bigger is not automatically better for you. A 27B embedding model needs a GPU server and costs real latency per query; a 300M–600M model on CPU may be within a couple of points on your corpus. Run your Part 8 test set on a small and a large candidate before provisioning hardware.
- Pair a local model with a hosted one only inside a documented shared space.
voyage-4-nanowithvoyage-4is explicitly supported; mixing any other local model with any hosted model is the mixed-space bug of Part 9.
Part 5: Dimensions, Matryoshka and quantization in code#
02.3, Parts 4 and 10 owns the concepts (normalization, cosine, Matryoshka, int8/binary). This part is the engineering: the three ways to get shorter or smaller vectors, and how to measure what they cost you.
5.1 Three ways to shrink a vector#
| Method | How | When it's safe | Cost |
|---|---|---|---|
| API dimension parameter | dimensions= (OpenAI, Jina), output_dimensionality= (Gemini), output_dimension= (Voyage, Cohere, Mistral), MRL truncate_dim (sentence-transformers) |
Only on Matryoshka-trained models — the API/library truncates and re-normalizes | Small quality loss, graceful |
| Manual truncation + renormalize | Keep first k numbers, divide by new norm | Only MRL-trained models; on others it degrades fast | You must remember to renormalize |
| Quantization | int8 (1 byte/dim), binary (1 bit/dim), PQ | Any model, measured on your data; binary usually wants rescoring | Bigger quality risk at small dims; big storage win |
# shrink_demo.py — pure stdlib, real output
import math, random
def dot(a,b): return sum(x*y for x,y in zip(a,b))
def unit(a): n=math.sqrt(sum(x*x for x in a)); return [x/n for x in a]
random.seed(7)
D=[unit([random.gauss(0,1) for _ in range(16)]) for _ in range(6)]
Q=[unit([random.gauss(0,1) for _ in range(16)]) for _ in range(2)]
def top3(Dm,Qm,k):
out=[]
for q in Qm:
qk = unit(q[:k]) if k < len(q) else q
scored = sorted(range(len(Dm)), key=lambda i: -dot(unit(Dm[i][:k]) if k < len(Dm[i]) else Dm[i], qk))
out.append(scored[:3])
return out
full = top3(D,Q,16)
for k in (16,8,4):
cut = top3(D,Q,k)
agree = sum(len(set(a)&set(b))/3 for a,b in zip(full,cut))/len(full)
print(f"dims {k:2d}: top-3 agreement vs full = {agree:.0%}")dims 16: top-3 agreement vs full = 100%
dims 8: top-3 agreement vs full = 83%
dims 4: top-3 agreement vs full = 83%On random vectors truncation is meaningless; on real embeddings trained for it (MRL), quality degrades gracefully — Google's embeddings page publishes an MTEB-by-dimension table with scores of 68.17 at 1,536 dims vs 67.99 at 768 and 66.19 at 256 (the page, as of November 2026, does not label which of its two models the table belongs to, so treat it as an illustration of graceful degradation, not a per-model guarantee). The lesson: measure on your data, don't trust the leaderboard delta.
5.2 int8 and binary at the vector level#
Quantization shrinks each number, not the count. int8 gives 4× storage reduction with typically negligible recall loss; binary gives 32× but needs rescoring (retrieve more candidates cheaply, re-score with full vectors — 06.4 owns the index side). Voyage's output_dtype and Cohere's embedding_types return these directly; sentence_transformers.quantization.quantize_embeddings does it locally. Storage arithmetic (N × d × bytes): 10M chunks at 1,024 dims is 41 GB float32, 10 GB int8, 1.3 GB binary — the difference decides whether your vector DB fits in RAM.
5.3 PCA and other dimensionality reduction#
02.3, 9.1 shows PCA in NumPy. For embeddings, PCA is a diagnostic (visualization, 02.3, Part 9), not a compression strategy — unlike Matryoshka truncation it isn't trained to preserve retrieval. Don't ship PCA-reduced vectors unless you've measured them like everything else.
Part 6: Long inputs#
Deep-dive
Every model has a max input length; the failure modes differ:
| Behaviour | Providers/models |
|---|---|
| Reject with error | OpenAI (>8,192 tok → 400); safer — you find out |
| Silent truncation | sentence-transformers models; Voyage truncation=True (default); Gemini multimodal/PDF over 8,192; most local models |
| You choose | Voyage truncation=False → error; set deliberately |
The engineering response, in order of preference:
- Chunk before embedding — 05.6 owns this; a 10k-token document becomes ~20 focused chunks, each well under the limit and each a better retrieval unit anyway. One vector for a long document averages many topics and matches nothing well (02.3, 5.7).
- Count tokens before sending — use the provider's counting endpoint (03.7) or your chunker's own count; alert when a chunk exceeds ~80% of the limit.
- Long-context embedding models — Voyage
voyage-context-4(120k tokens with auto-chunking), Gemini 2 (8,192), Qwen3-Embedding (32k) accept much longer inputs; useful for whole-document or late-chunking-style embeddings, not a substitute for chunking. - Late chunking — embed the whole document once, pool per chunk (05.7, 4.1 owns it); needs a long-context model and per-token vectors, which most hosted embedding APIs don't expose.
Part 7: Multilingual, domain-specific and multimodal embeddings#
Deep-dive
7.1 Multilingual and cross-lingual retrieval#
All the hosted models in Part 2 are multilingual to some degree (Gemini claims 100+ languages; Voyage and Cohere similarly), but quality varies sharply by language — high-resource languages first, low-resource last. The failure is silent: an English-only model returns plausible-looking vectors for other languages that rank badly. Rules:
- Match the model to your language mix. If queries and documents span languages, you need a multilingual model and you must test per language — a model that's great in English and German may be mediocre in Hindi.
- Cross-lingual search (English query → Spanish documents) works when the model maps translations near each other; 02.3's demo showed a multilingual model scoring 0.93–0.99 on translations vs 0.10–0.43 for an English-only one. Verify on your own languages.
- Query/document language mismatch is the common production case: users ask in their language, docs may be in another. Test that direction explicitly.
- Script and tokenization effects matter: CJK and non-Latin scripts tokenize differently and some models handle them worse — measure, don't assume (02.2).
7.2 Domain-specific models#
General models embed general text well; jargon-heavy domains benefit from specialists. Verified examples (November 2026): Voyage voyage-code-4 (code), voyage-finance-2 (finance), voyage-law-2 (legal, 16k ctx); Mistral codestral-embed-2505 (code); open families like BGE-M3 (multilingual + code), E5, Qwen3-Embedding. Cohere's current lineup is general-purpose — its domain edge comes from the 128k context and multimodal inputs rather than separate domain models. The decision is empirical: run your Part 8 test set with the general model and the domain model — the domain model wins only if your data is actually in-domain. Don't pay a domain premium for a corpus that's mostly plain English prose.
7.3 Multimodal embeddings#
Models that put text and other modalities in one space enable cross-modal search:
| Route | Modalities | Notes |
|---|---|---|
Gemini gemini-embedding-2 |
text, image, audio, video, PDF | 8,192 shared token cap; modality limits per type; one of the path's four providers |
Voyage voyage-multimodal-3.5 |
interleaved text, images, video | multimodal_embed(); 32k ctx |
Cohere embed-v5.0-* / embed-v4.0 / embed-*-v3.0 |
text + images (fused or separate) | v5/v4: no image-count limit, ≤20 MB combined; v3: input_type="image", 1 image/call |
Jina v5-omni |
text, image, audio, video | open-weight sizes; compatible with v5-text |
| Open-weight CLIP/SigLIP-style | image ↔ text | run locally via sentence-transformers/fastembed; the classic baseline |
Part 8: Choosing a model with evidence#
8.1 Reading MTEB honestly#
The MTEB/MMTEB leaderboards are the standard public comparison, and RTEB adds private datasets to catch benchmark overfitting (02.3, 7.4 covers the caveats fully — link, don't repeat). The engineering additions:
- Look at the retrieval column for your task type, in your languages, not the headline average.
- Check dimensions, context length and price alongside score — the leaderboard ignores all three, and they're your real constraints.
- Treat a <1-point gap as noise; use MTEB to build a shortlist of 2–4, then decide on your data.
8.2 Your own test set#
Build 30–100 queries with known relevant chunks from your real corpus (the Module 05 running corpus is ideal: handbook, help centre, tickets, contracts). For each query, mark which chunk IDs should be retrieved. This is the same evaluation set Module 10A will deepen — here it's just enough to rank models.
8.3 The harness: recall@k and MRR#
Two metrics cover most retrieval comparisons:
- recall@k — fraction of relevant items found in the top k.
recall@10is the usual headline for RAG (you feed ~10 chunks to the LLM). - MRR (mean reciprocal rank) — 1/(rank of first relevant result), averaged. Rewards putting the answer first.
# eval_harness.py — pure stdlib, works with ANY embedder (real output below)
import math
def recall_at_k(ranked_ids, relevant, k):
if not relevant: return None
return len(set(ranked_ids[:k]) & set(relevant)) / len(relevant)
def mrr(ranked_ids, relevant):
if not relevant: return None # unanswerable query: excluded, same as recall
for i, doc_id in enumerate(ranked_ids, 1):
if doc_id in relevant: return 1.0 / i
return 0.0
def evaluate(ranked_lists, qrels, ks=(1, 3, 10)):
"""ranked_lists: list of ranked doc-id lists, one per query.
qrels: list of relevant-id sets, same order. Returns mean metrics.
Queries with no relevant docs are excluded from every metric —
Module 10A's harness will treat them as a separate abstention case."""
out = {f"recall@{k}": [] for k in ks}
out["mrr"] = []
for ranked, rel in zip(ranked_lists, qrels):
for k in ks:
r = recall_at_k(ranked, rel, k)
if r is not None: out[f"recall@{k}"].append(r)
r = mrr(ranked, rel)
if r is not None: out["mrr"].append(r)
return {m: round(sum(v)/len(v), 3) for m, v in out.items() if v}
# Toy run: 5 queries over 5 docs (hand-made rankings stand in for real retrieval)
ranked_lists = [
[3, 1, 4, 2, 5], # q1: relevant doc 1 at rank 2
[2, 3, 1], # q2: relevant doc 3 at rank 2
[5, 4, 3, 2, 1], # q3: relevant {2,4}; 4 at rank 2, 2 at rank 4
[1, 2, 3], # q4: no relevant docs -> excluded from every metric
[4, 1, 2, 3, 5], # q5: relevant doc 5 at rank 5
]
qrels = [{1}, {3}, {2, 4}, set(), {5}]
print(evaluate(ranked_lists, qrels)){'recall@1': 0.0, 'recall@3': 0.625, 'recall@10': 1.0, 'mrr': 0.425}To use it with real models, inject an embed function: embed all chunks once, embed each query, rank by cosine — the metrics code doesn't change. That's the whole point of the injectable design: swap sentence-transformers, an API embedder, or the deterministic fake and the harness is identical.
8.4 The selection scorecard#
Score each shortlisted model 1–5 on: retrieval quality on your test set (the dominant factor), dimensions (storage/compute), max input tokens, language coverage, price per 1M tokens, query latency, rate limits, licence (open weights), privacy/deployment (API vs self-host), lock-in (proprietary vs open). Weight quality highest; let cost break ties. The output is a decision, not a beauty contest.
8.5 The model-change cost#
Changing embedding models means re-embedding the entire corpus — new space, new vectors, old ones useless (02.3, 7.5). Budget it: corpus_tokens × new_model_price plus the blue/green reindex machinery (05.9 owns incremental re-embedding and embedding reuse by content hash; the vector-store side is 06.5). This is why "start with a decent model, measure, then decide" beats "pick the leaderboard winner and migrate later".
Part 9: Versioning embeddings#
A stored vector is only meaningful relative to the model that produced it. The space isn't just the model name — it's the model, its version, the dimension requested, the normalisation state, the task-type hint, and the preprocessing you applied. Two vectors from "the same model" embedded under different settings can be as incompatible as vectors from different models.
9.1 The metadata every vector needs#
Every stored vector (or every batch of them) should carry:
model— the exact ID used (text-embedding-3-small, not "openai")model_version/ revision — dated or pinned version where the provider exposes one; for open models, the HF revision hashdimensions— what you requested and what came backnormalization— whether vectors are unit-norm (and whether you verified it)task_type/ prefix — which hint was applied, if anyinput_prep— chunker version, truncation policy, preprocessing hashcreated_at— for drift analysis
In practice this is one JSON metadata blob per embedding batch, or columns on the vector store's records.
9.2 A worked example of mixed models#
The classic production bug: the index was built with text-embedding-ada-002 two years ago; this week someone "upgraded" the query embedder to text-embedding-3-small to chase better recall. Both emit 1,536-dimension vectors. Nothing errors. Retrieval silently degrades to near-random because the query and document vectors live in different spaces. (The same trap exists between any two models that are not in a documented shared family such as the Voyage 4 series; see 2.3.)
# version_guard.py — pure stdlib, real output
def embedding_space(meta):
"""The identity of a vector space — everything that changes it.
task_type is deliberately NOT part of the space: query/document
hints are meant to interoperate within one model. dtype/quantization
is also excluded: int8 vs float32 is a precision detail inside the
same space (verify with a recall check, not the guard)."""
return (meta["model"], meta.get("revision", ""), meta["dimensions"],
meta.get("normalization", ""), meta.get("input_prep", ""))
def assert_compatible(stored_meta, query_meta):
if embedding_space(stored_meta) != embedding_space(query_meta):
raise ValueError(
f"Embedding space mismatch: stored={embedding_space(stored_meta)} "
f"query={embedding_space(query_meta)}"
)
stored = {"model": "text-embedding-ada-002", "dimensions": 1536, "normalization": "unit",
"task_type": "document", "input_prep": "chunker-v3"}
same = {"model": "text-embedding-ada-002", "dimensions": 1536, "normalization": "unit",
"task_type": "query", "input_prep": "chunker-v3"}
diff = {"model": "text-embedding-3-small", "dimensions": 1536, "normalization": "unit",
"task_type": "query", "input_prep": "chunker-v3"}
unnorm = {"model": "text-embedding-ada-002", "dimensions": 1536, "normalization": "raw",
"task_type": "query", "input_prep": "chunker-v3"}
assert_compatible(stored, same) # query/document task difference is FINE — same space
print("same model, different task_type: OK")
for bad, label in [(diff, "different model"), (unnorm, "unnormalized")]:
try:
assert_compatible(stored, bad)
except ValueError as e:
print(f"refused ({label}):", e)same model, different task_type: OK
refused (different model): Embedding space mismatch: stored=('text-embedding-ada-002', '', 1536, 'unit', 'chunker-v3') query=('text-embedding-3-small', '', 1536, 'unit', 'chunker-v3')
refused (unnormalized): Embedding space mismatch: stored=('text-embedding-ada-002', '', 1536, 'unit', 'chunker-v3') query=('text-embedding-ada-002', '', 1536, 'raw', 'chunker-v3')Note the subtleties the code encodes: query vs document task_type is the same space (they're meant to be compared); a different model or a different normalisation state is a different space. The guard compares model+revision+dimensions+normalisation+preprocessing, not the task hint or dtype.
9.3 The migration rule#
When you do change models, it's a blue/green reindex: embed the new space in parallel, verify quality on your Part 8 test set, then cut over. Never do an in-place swap — you can't have two spaces in one index. 05.9 owns the incremental re-embedding machinery; 06.5 owns the store.
One more versioning trap the guard can't catch: providers can change the vectors a model produces without changing its ID — a silent server-side update, a tokenizer fix, a precision change. That's exactly why §9.1 records model_version/revision and created_at: when retrieval quality drifts with no code change on your side, suspect the provider first, diff a few probe embeddings against your stored ones, and re-run your Part 8 eval before trusting the index.
Part 10: The Embedder protocol#
Deep-dive
Embedder protocol#Every lesson in Module 06 needs to call some embedding model. Rather than couple each lesson to one provider, define one small interface — the same move 03.11 made for chat clients.
# embedder_protocol.py — the contract every adapter implements
from typing import Protocol, runtime_checkable
@runtime_checkable
class Embedder(Protocol):
"""Turns texts into vectors. Implementations: OpenAI, Gemini,
sentence-transformers local, and a deterministic fake for tests."""
@property
def model_id(self) -> str:
"""The exact model identifier — used for version guards."""
...
@property
def dimensions(self) -> int:
"""Vector width this embedder returns."""
...
def embed_documents(self, texts: list[str]) -> list[list[float]]:
"""Embed corpus-side texts (document task type where supported)."""
...
def embed_query(self, text: str) -> list[float]:
"""Embed a single query-side text (query task type where supported)."""
...Adapters (illustrative — wire to real SDKs in your project):
# adapters.py — illustrative implementations
import hashlib
import math
class OpenAIEmbedder:
def __init__(self, client, model="text-embedding-3-small", dimensions=None):
self._c, self._model, self._dims = client, model, dimensions
@property
def model_id(self): return self._model
@property
def dimensions(self):
if self._dims is not None:
return self._dims
# Native widths from Part 2.1; `dimensions=` only exists on text-embedding-3*.
known = {"text-embedding-3-small": 1536,
"text-embedding-3-large": 3072,
"text-embedding-ada-002": 1536}
if self._model in known:
return known[self._model]
raise ValueError(f"unknown model {self._model!r}; pass dimensions=")
def _embed(self, texts):
kw = {"dimensions": self._dims} if self._dims else {}
r = self._c.embeddings.create(model=self._model, input=texts, **kw)
return [d.embedding for d in r.data]
def embed_documents(self, texts): return self._embed(texts)
def embed_query(self, text): return self._embed([text])[0]
class GeminiEmbedder:
def __init__(self, client, model="gemini-embedding-001", dims=768):
self._c, self._model, self._dims = client, model, dims
@property
def model_id(self): return self._model
@property
def dimensions(self): return self._dims
def _embed(self, texts, task):
from google.genai import types
r = self._c.models.embed_content(
model=self._model, contents=texts,
config=types.EmbedContentConfig(task_type=task, output_dimensionality=self._dims))
return [list(e.values) for e in r.embeddings]
def embed_documents(self, texts): return self._embed(texts, "RETRIEVAL_DOCUMENT")
def embed_query(self, text): return self._embed([text], "RETRIEVAL_QUERY")[0]
class LocalSTEmbedder:
"""sentence-transformers backend — prefixes via encode_query/encode_document.
normalize_embeddings is an encode()-family argument (default False), so the
adapter stores the flag and passes it through on every call — setting it as
an attribute does nothing."""
def __init__(self, model_name, prompts=None, device="cpu", normalize=True):
from sentence_transformers import SentenceTransformer
self._m = SentenceTransformer(model_name, prompts=prompts or {}, device=device)
self._name, self._norm = model_name, normalize
@property
def model_id(self): return self._name
@property
def dimensions(self): return int(self._m.get_embedding_dimension())
def embed_documents(self, texts):
return self._m.encode_document(texts, normalize_embeddings=self._norm).tolist()
def embed_query(self, text):
return self._m.encode_query([text], normalize_embeddings=self._norm)[0].tolist()
class FakeEmbedder:
"""Deterministic, no-network embedder for tests and CI.
Hashes words into a fixed-dim space so similar texts share dimensions."""
def __init__(self, dims=64): self._dims = dims
@property
def model_id(self): return "fake-hash-v1"
@property
def dimensions(self): return self._dims
def _vec(self, text):
v = [0.0] * self._dims
for w in text.lower().split():
h = int(hashlib.md5(w.encode()).hexdigest(), 16)
v[h % self._dims] += 1.0
n = math.sqrt(sum(x*x for x in v)) or 1.0
return [x/n for x in v]
def embed_documents(self, texts): return [self._vec(t) for t in texts]
def embed_query(self, text): return self._vec(text)Use it everywhere:
# usage.py
emb = FakeEmbedder(dims=64) # or OpenAIEmbedder(client), GeminiEmbedder(client)...
names = ["app download", "refund policy"]
docs = emb.embed_documents(names)
q = emb.embed_query("how do I get a refund")
# rank by cosine — identical code regardless of backend
scores = sorted(zip(docs, names),
key=lambda p: -sum(a*b for a,b in zip(p[0], q)))
print([name for _, name in scores])['refund policy', 'app download']The fake ranks the right document first only because the query and that document share the word "refund": it hashes words, so it measures word overlap, not meaning (a query like "money back" would score 0.0 against both documents). That is exactly what you want from a test double — deterministic and key-free — but never use it to judge retrieval quality.
Why this matters beyond tidiness: the version guard, the eval harness and every later lesson plug into this interface. The fake lets you test pipelines end-to-end with zero keys, zero cost and zero flakiness — it's the embedder 06.10's evaluation harness measures. Errors, retries and timeouts stay 03.8's job inside each adapter.
Failure gallery#
| What you see | Likely cause | Fix |
|---|---|---|
| Retrieval fine, then garbage overnight | Model silently changed / mixed spaces | Version guard (Part 9); blue-green reindex |
| "Similar" texts score ~0.5 | Missing task prefix / wrong input_type |
Check Part 3; put hints inside the Embedder |
dimensions mismatch error on insert |
Query embedder dims ≠ stored dims | Assert embedder.dimensions == index.dimensions at startup |
| Batch request 400s | Over 2,048 items / 300k tokens (OpenAI) | Split per Part 2.8 |
| Vectors look fine, search is random | One space, two models; or unnormalized dot product | Norm check + model-ID check (Part 1.3) |
| Costs 3× expected | dimensions default vs requested; batch not used for backfill |
Read usage; use Batch API for bulk (06.2) |
| Non-English queries rank poorly | English-tuned model or tokenizer | Per-language eval; pick multilingual (Part 7.1) |
| Chunk tails missing | Silent truncation | Count tokens; truncation=False where supported (Part 6) |
| Whole batch 400s on one item | Empty string in input (OpenAI rejects them) |
Filter/validate texts before sending; never send "" |
| Index build stalls for minutes, no errors | Rate-limit waits: RPM/TPM caps or provider-side 429s with Retry-After |
Budget concurrency to the tier's RPM/TPM (Part 2.8); backfill via Batch API |
| Retrieval was fine, slowly got worse — no deploy | Provider changed the model's vectors under the same ID (silent server-side update) | Record model_version/revision; probe-diff embeddings; re-run Part 8 eval; re-embed if drifted (Part 9.3) |
Decision table#
| Situation | Choose |
|---|---|
| Quick prototype, any provider | FakeEmbedder for tests; text-embedding-3-small or voyage-4-lite for real |
| Best general quality, managed | voyage-4-large or text-embedding-3-large — measure on your data |
| Anthropic/Claude stack | Voyage AI (Anthropic's recommended partner) |
| Multimodal search (text+image) | gemini-embedding-2, voyage-multimodal-3.5, Cohere v5, or Jina v5-omni |
| Data can't leave infra / high steady volume | Open-weight local: sentence-transformers (Qwen3-Embedding, BGE-M3, E5) served via TEI/vLLM |
| Minimal footprint / serverless | fastembed (ONNX) or Ollama |
| One gateway for many models | OpenRouter /embeddings with provider routing |
| Code retrieval | voyage-code-4, codestral-embed, or a code-tuned open model |
| Big offline backfill | Batch API (OpenAI/Gemini 50%/Cohere/Mistral/Voyage) — 06.2 |
Common misconceptions#
- "Embeddings are magic — any model works." They're trained representations with specific task types, languages and limits; the wrong model or missing hint degrades silently.
- "Higher dimension = better." Matryoshka models make 256–768 dims nearly as good at a fraction of the storage; measure before paying for 3,072.
- "Same provider = same space."
text-embedding-ada-002≠text-embedding-3-small≠gemini-embedding-001≠gemini-embedding-2— each is its own space; only documented families share one (the Voyage 4 series, Cohere'sembed-v5.0-proand-fast). - "The API will tell me if input is too long." Many truncate silently. Count tokens.
- "Quantization ruins embeddings." int8 is usually free; binary needs rescoring. Measure recall, don't guess.
- "MTEB #1 is the right model." Leaderboards ignore your domain, languages, dims and price — shortlist, then test on your corpus.
- "You can mix query and document models freely." Within a documented family it's fine (Voyage 4); across models it's the mixed-space bug.
Key takeaways#
- Every embedding API shares one contract — model + input + optional task hint + dimension/dtype controls — but each provider's knobs differ; learn them per provider, not generically.
- Task types and prefixes are the highest-leverage correctness detail: put them inside your
Embedderso they can't be forgotten. - Normalization, dimensions and model identity are part of the vector's meaning — version all of them, including the provider-side revision.
- Choose models with evidence: MTEB shortlists, your own 30–100-query test set,
recall@k+ MRR, then a scorecard. - Self-host when compliance/volume demands it; APIs when speed-to-quality matters.
sentence-transformersandfastembedcover the local cases. - The
Embedderprotocol + a deterministic fake is how you keep every later lesson provider-agnostic and testable.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
Task type / input_type |
The hint telling an asymmetric embedding model whether text is a query or a document (Voyage/Cohere input_type, Gemini task_type, open-model prefixes) |
| Matryoshka dimension | A shorter prefix of a longer vector that remains usable because the model was trained for nested representations (MRL) |
| Vector quantization | Storing each vector component in fewer bits (int8, binary) to cut storage and bandwidth at some quality cost |
| Embedding space | The coordinate system a model's vectors live in — determined by model + version + dimensions + normalisation + preprocessing; vectors from different spaces can't be compared |
recall@k |
Fraction of relevant documents found in the top-k results for a query |
| MRR (mean reciprocal rank) | Average of 1/(rank of first relevant result) across queries; rewards putting the answer first |
| Silent truncation | Cutting over-length input without an error — the dangerous default on several providers/models |
| Late chunking | Embedding a whole document once and pooling per chunk (owned by 05.7) |
| Instruction-aware embedding | An embedding model that takes a one-sentence task description (usually on the query side only) and changes the vector accordingly; typical of LLM-backbone open models such as Qwen3-Embedding and Harrier |
| TEI / vLLM | Open-source servers for hosting embedding models over HTTP |
| Blue/green reindex | Building a new embedding space in parallel, verifying it, then cutting over — never an in-place swap |
Exercises#
- Wire one real provider. Pick any key you have, adapt the Part 2 sample to embed 10 sentences, and print norms — confirm they're ≈1.0.
- Prefix experiment. With
sentence-transformers, embed queries with and without the model's required prefix on a few pairs; compare cosine scores. (No key needed; model downloads once.) - Build the harness. Take the Part 8
evaluate()and run it againstFakeEmbedderon a hand-made corpus; then swap inLocalSTEmbedderand compare. - Version guard. Extend
embedding_space()to includeencoding_format/dtype; write a test that two metas differing only in task_type pass and two differing in model fail. - Dimension sweep. On one provider, request dims {default, 512, 256} for the same texts and compare pairwise cosine rank correlation on your own pairs.
- Cost check. Compute the embedding cost of a 1M-chunk corpus at two shortlisted models using their per-1M-token prices and your measured tokens/chunk.
Check yourself#
- Why must queries and documents sometimes be embedded differently, and which providers let you say so?Retrieval is asymmetric: queries are short questions, documents are long passages, and asymmetric-trained models embed the two sides differently. Voyage (
input_type), Cohere (input_type), Gemini (task_typeon 001, text prefixes on 2), Jina (task) and open models (prefixes/instructions) all expose a hint; OpenAI'stext-embedding-3-*offers none. - A teammate passes
normalize_embeddings=Trueto theSentenceTransformer(...)constructor. What happens, and where does the flag actually belong?SentenceTransformer.__init__has nonormalize_embeddingsparameter — it raisesTypeError. The flag belongs to theencode/encode_query/encode_documentcalls (defaultFalse), so it must be passed per call or stored and forwarded by an adapter likeLocalSTEmbedder. - What three things, besides the model name, define an embedding's "space" — and which of them does the Part 9 guard deliberately exclude?Model + revision/version, dimensions, and preprocessing/normalisation state (plus the task-type hint on the input side). The guard deliberately excludes
task_type(query/document hints interoperate within one model) and dtype/quantization (a precision detail inside the same space). - What's the difference between Matryoshka truncation and manual slicing, and why does the difference matter?Matryoshka truncation keeps the first k dimensions and re-normalizes, and the model was trained so those prefixes stay meaningful. Manual slicing without renormalizing breaks cosine comparisons; on non-MRL models even renormalized truncation degrades fast.
gemini-embedding-2returns one vector for a list of five texts. What went wrong, and how do you fix the request?gemini-embedding-2aggregates a bare list incontentsinto ONE vector. Wrap each text in its owntypes.Content(or use the Batch API) to get one vector per input.- Why is silent truncation worse than an error for embeddings?Several providers/models truncate over-length input without erroring (Voyage
truncation=Truedefault, Gemini multimodal over 8,192, most local models). The cut tail — often the answer-bearing sentence — disappears silently, corrupting retrieval with no signal. Prefer erroring (truncation=False) and counting tokens first. - Cohere's
embed-v5.0-proandembed-v5.0-fastshare an embedding space. What does that let you do operationally, and which Cohere pairs can't you mix the same way?Because they share a space you can index documents once with Pro and serve queries through Fast (or either) without re-embedding — Cohere's recommended split. You can't mix across the v5/v4/v3 families or across differentoutput_dimensions; those are different spaces. - Your retrieval quality decays over a month with no deploys on your side. What are the two most likely causes, and what metadata would have caught each?(a) A provider-side model update changed the vectors under an unchanged model ID — caught by
model_version/revision metadata, probe-diffing embeddings, and re-running the Part 8 eval. (b) An accidental model/dimension/normalisation change in config — caught by the Part 9assert_compatibleguard refusing mixed spaces. - How do you choose between an embedding API and self-hosting?Self-host when data can't leave your infra, volume is high and steady enough to amortize hardware, you need a niche/open model, or you need offline/latency-critical inference. API wins for zero-ops, spiky/low volume, frontier quality and fast time-to-production.
- What two metrics does the Part 8 harness compute, and why those two? What happens to a query with no relevant documents?
recall@k(fraction of relevant items in top-k — the RAG headline) and MRR (mean reciprocal rank of the first hit — rewards ranking the answer first). Queries with no relevant documents are excluded from every metric in this harness. - Why does the
Embedderprotocol need bothembed_documentsandembed_queryinstead of oneembedmethod?Because the task hint differs by side:embed_documentsapplies the document-side hint (or none),embed_querythe query-side hint. One method couldn't express the asymmetry without every caller remembering which mode it's in. - Name three request fields that let you shrink or compress vectors, and which providers offer each.
dimensions(OpenAI, Jina),output_dimensionality(Gemini),output_dimension(Voyage, Cohere, Mistral), MRLtruncate_dim(sentence-transformers), and dtype controlsoutput_dtype(Voyage, Mistral),embedding_types(Cohere),encoding_format(OpenAI, Mistral, Jina).
Further resources#
- 02.3: Embeddings — the conceptual foundation this lesson builds on
- 03.11: Provider-Agnostic Client — the pattern the
Embedderprotocol follows - OpenAI Embeddings guide · Embeddings API reference
- Gemini Embeddings docs · Anthropic on embeddings → Voyage
- Voyage docs · Cohere embeddings · Jina embeddings · Mistral embeddings · OpenRouter embeddings
- sentence-transformers docs · fastembed · TEI · vLLM
- MTEB leaderboard
← Module 05: Data Engineering for AI | Module 06 overview | 06.2 — Embedding Pipelines: Batching, Caching, Scale and Cost →