Want search that understands meaning, not just keywords? The OpenAI embeddings API turns any text into a list of numbers, and similar texts get similar numbers.
This tutorial walks you through it in Python. You will learn the models, the dimensions parameter, cosine similarity, a working semantic search with numpy, batching and real costs.
- Models:
text-embedding-3-small(1,536 dimensions) andtext-embedding-3-large(3,072 dimensions). The oldertext-embedding-ada-002still works. - Price: $0.02 per 1M tokens for small, $0.13 per 1M for large.
- Batch API: 50% off, with results within 24 hours.
- Limits: 8,192 tokens per input, 2,048 inputs per request, 300,000 tokens per request.
- Shrink vectors: pass
dimensions=256(or any size) on the v3 models to save storage. - SDK checked:
openaiPython package 3.60.0 (26 Nov 2026).
What Embeddings Are and When to Use Them
An embedding is a vector, which is just a list of floating point numbers. OpenAI’s guide puts it simply: the distance between two vectors measures how related the texts are.
Small distance means the texts are about the same thing. Large distance means they are not related. That lets you compare meaning with simple math.
OpenAI lists these common uses:
- Search: rank results by relevance to a query.
- Clustering: group texts by similarity.
- Recommendations: suggest items with related text.
- Anomaly detection: find outliers that relate to nothing else.
- Diversity measurement: study how spread out a set of texts is.
- Classification: label a text by its most similar example.
Embeddings are also the “retrieval” half of RAG (retrieval augmented generation). You embed your documents once, find the closest ones for each question, then pass them to a chat model.
Current OpenAI Embedding Models and Dimensions
OpenAI’s embeddings guide still calls the text-embedding-3 family its newest and most capable embedding models. I checked the docs and model pages for releases in the last few weeks and found no newer embedding model as of 28 Nov 2026.
| Model | Default dimensions | Max input | MTEB score | Price per 1M tokens | Pages per dollar |
|---|---|---|---|---|---|
text-embedding-3-small |
1,536 | 8,192 tokens | 62.3% | $0.02 | 62,500 |
text-embedding-3-large |
3,072 | 8,192 tokens | 64.6% | $0.13 | 9,615 |
text-embedding-ada-002 (older) |
1,536 (fixed) | 8,192 tokens | 61.0% | $0.10 | 12,500 |
OpenAI’s “pages per dollar” figure assumes about 800 tokens per page. MTEB is a public benchmark for embedding quality, and higher is better.
Which model should you pick?
- text-embedding-3-small: the default for most apps. It is cheap, fast and beats ada-002 on MTEB.
- text-embedding-3-large: pick it when retrieval quality matters more than cost, for example legal or multilingual search.
- text-embedding-ada-002: only keep it if you already have a large index built with it. It costs more than small and has no
dimensionsoption.
Warning: Vectors from different models are not compatible. If you switch models, you must re-embed every document and every query with the new model.
Prerequisites and Setup
You need three things before you write any code:
- Python 3.10 or newer: the current
openaipackage requires it. - An OpenAI API key: see my guide on how to get an OpenAI API key.
- A little credit: embeddings are cheap, but the API is pay as you go.
- Create a project folder and a virtual environment. Run
python -m venv .venv, then activate it withsource .venv/bin/activate(Mac/Linux) or.venv\Scripts\activate(Windows). - Install the packages. Run
pip install openai numpy. This tutorial was checked againstopenai3.60.0 and numpy 2.x. - Set your key as an environment variable. On Mac/Linux run
export OPENAI_API_KEY="sk-...". On Windows PowerShell run$env:OPENAI_API_KEY="sk-...". - Check the install. Run
python -c "import openai; print(openai.__version__)". You should see 3.60.0 or newer. - Run the first example below. If it prints a list of numbers, you are ready.
Note: Never paste your key into code or commit it to Git. The SDK reads OPENAI_API_KEY from the environment automatically. New to the SDK? My OpenAI API Python tutorial covers the basics.
Example 1: Your First Embedding
The call is client.embeddings.create(). It needs two arguments: input (your text) and model.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
response = client.embeddings.create(
model="text-embedding-3-small",
input="Freakyjolly writes simple AI tutorials.",
)
vector = response.data[0].embedding
print("Dimensions:", len(vector)) # 1536
print("First 5 numbers:", vector[:5])
print("Tokens billed:", response.usage.total_tokens)
The response has four parts you will use often:
- data: a list of embedding objects, one per input.
- data[i].embedding: the vector itself, a list of floats.
- data[i].index: the position of that input in your request.
- usage:
prompt_tokensandtotal_tokens, which is what you pay for.
The create() method also accepts dimensions, encoding_format ("float" by default, or "base64") and user, an optional ID for your end user that helps OpenAI detect abuse.
The dimensions Parameter
By default, small returns 1,536 numbers and large returns 3,072. The dimensions parameter lets you ask for fewer. It only works on text-embedding-3 and later models, not on ada-002.
Why shrink? Shorter vectors use less storage and memory, and search runs faster. Many vector databases also cap the vector size they accept.
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-large",
input="How do I reset my password?",
dimensions=256,
)
print(len(response.data[0].embedding)) # 256
Quality drops only a little. OpenAI’s guide says a text-embedding-3-large vector cut to 256 dimensions still beat a full 1,536-dimension ada-002 vector on MTEB.
Shortening vectors yourself
You can also slice a full vector and keep the first N numbers. If you do that, you must normalize the result again. OpenAI recommends passing dimensions instead, because the API does this for you.
import numpy as np
def shorten(vec, size):
cut = np.array(vec[:size], dtype=np.float32)
return cut / np.linalg.norm(cut) # back to length 1
Tip: Pick one size and stick to it. Every document and every query must use the same model and the same dimensions value, or the comparisons are meaningless.
Cosine Similarity Explained
Cosine similarity measures the angle between two vectors. It ranges from -1 to 1, and closer to 1 means more similar. OpenAI’s own text search example in the embeddings guide ranks documents this way.
The formula is the dot product divided by the two vector lengths:
import numpy as np
def cosine_similarity(a, b):
a = np.asarray(a, dtype=np.float32)
b = np.asarray(b, dtype=np.float32)
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
OpenAI embeddings come back with a length of about 1. When both vectors have length 1, the bottom of the fraction is 1, so the plain dot product gives the same ranking and is a bit faster.
Treat scores as a ranking, not a grade. Compare them against each other, and only use a fixed “good match” cut-off after you test it on your own data.
Example 2: Semantic Search with numpy
Now let’s build a tiny search engine. It embeds a few documents, saves the vectors, and returns the best match for a question. No vector database is needed for a few thousand items.
import numpy as np
from openai import OpenAI
client = OpenAI()
MODEL = "text-embedding-3-small"
docs = [
"Reset your password from the Settings page under Security.",
"Our refund policy allows returns within 30 days of purchase.",
"You can export your data as a CSV file from the Account tab.",
"Two-factor authentication adds a code from your phone at login.",
"Shipping to Europe usually takes 5 to 7 business days.",
]
def embed(texts):
resp = client.embeddings.create(model=MODEL, input=texts)
vectors = [item.embedding for item in sorted(resp.data, key=lambda d: d.index)]
matrix = np.array(vectors, dtype=np.float32)
# normalize rows so a dot product equals cosine similarity
return matrix / np.linalg.norm(matrix, axis=1, keepdims=True)
# 1. Embed the documents once and save them
doc_matrix = embed(docs)
np.save("doc_vectors.npy", doc_matrix)
# 2. Search
def search(query, top_k=3):
q = embed([query])[0]
scores = doc_matrix @ q # cosine similarity for every doc
best = np.argsort(scores)[::-1][:top_k]
return [(float(scores[i]), docs[i]) for i in best]
for score, text in search("how do I get my money back?"):
print(f"{score:.3f} {text}")
The query “how do I get my money back?” shares no keywords with “refund policy”. The refund document should still rank first, because the vectors capture meaning.
How the search works
- Embed once: documents are embedded a single time and saved to
doc_vectors.npy. - Normalize: each row is scaled to length 1, so
doc_matrix @ qgives cosine scores for every document in one step. - Sort:
np.argsortreturns the highest scores first after the[::-1]flip. - Sort by index: the code orders results by
indexso vectors always match the input order.
For tens of thousands of items, this numpy approach is still fine. Past a few million, move to a vector database or a library with approximate search.
Example 3: Batching Many Texts
Sending one text per request is slow and burns your requests-per-minute limit. Pass a list instead. One request can hold up to 2,048 inputs and up to 300,000 tokens in total.
import time
import numpy as np
from openai import OpenAI, RateLimitError
client = OpenAI()
MODEL = "text-embedding-3-small"
BATCH_SIZE = 500 # well under the 2,048 input limit
def embed_all(texts, dimensions=None):
vectors = []
for start in range(0, len(texts), BATCH_SIZE):
chunk = [t.strip() or " " for t in texts[start:start + BATCH_SIZE]]
kwargs = {"model": MODEL, "input": chunk}
if dimensions:
kwargs["dimensions"] = dimensions
for attempt in range(5):
try:
resp = client.embeddings.create(**kwargs)
break
except RateLimitError:
time.sleep(2 ** attempt) # 1, 2, 4, 8, 16 seconds
else:
raise RuntimeError("Still rate limited after 5 tries")
resp_sorted = sorted(resp.data, key=lambda d: d.index)
vectors.extend(item.embedding for item in resp_sorted)
return np.array(vectors, dtype=np.float32)
texts = [f"Support ticket number {i}" for i in range(1200)]
matrix = embed_all(texts, dimensions=512)
print(matrix.shape) # (1200, 512)
Keep each batch under 300,000 tokens. With 500 inputs, that means an average of 600 tokens or less per text. If your texts are long, lower BATCH_SIZE.
The line t.strip() or " " swaps empty strings for a space. Empty strings in a list trigger an “input is invalid” error, which is covered in the troubleshooting table.
Texts longer than 8,192 tokens
Every single input must fit in 8,192 tokens. OpenAI’s cookbook suggests three options for longer texts:
- Truncate: keep only the first 8,192 tokens. Simple, but you lose the rest.
- Chunk: split the text into pieces and store each piece as its own vector. This is the usual choice for RAG.
- Chunk and average: embed each piece, take a length-weighted average, then normalize it.
To count tokens before sending, use the tiktoken package. The v3 embedding models use the cl100k_base encoding.
Example 4: The Batch API for 50% Off
If you do not need vectors right away, the Batch API halves the price. You upload a JSONL file, and OpenAI returns results within 24 hours. It is ideal for embedding a whole knowledge base overnight.
Batch limits from the official guide:
- Requests: up to 50,000 per batch.
- File size: up to 200 MB.
- Embeddings cap: at most 50,000 embedding inputs across all requests in one batch.
- One model per file: every line must use the same model.
import json
from openai import OpenAI
client = OpenAI()
docs = ["First document text", "Second document text", "Third document text"]
# 1. Write one request per line
with open("embed_batch.jsonl", "w", encoding="utf-8") as f:
for i, text in enumerate(docs):
line = {
"custom_id": f"doc-{i}",
"method": "POST",
"url": "/v1/embeddings",
"body": {"model": "text-embedding-3-small", "input": text},
}
f.write(json.dumps(line) + "\n")
# 2. Upload the file and start the batch
batch_file = client.files.create(file=open("embed_batch.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/embeddings",
completion_window="24h",
)
print("Batch id:", batch.id)
# 3. Later: check status and download results
batch = client.batches.retrieve(batch.id)
print("Status:", batch.status)
if batch.status == "completed":
output = client.files.content(batch.output_file_id).text
for row in output.splitlines():
result = json.loads(row)
vec = result["response"]["body"]["data"][0]["embedding"]
print(result["custom_id"], len(vec))
Results may not come back in the same order as your file. Always match them with custom_id.
curl Example
Want to test without Python? This calls the same endpoint, POST https://api.openai.com/v1/embeddings, from a terminal:
curl https://api.openai.com/v1/embeddings \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "text-embedding-3-small",
"input": ["first text", "second text"],
"dimensions": 256
}'
The JSON reply has an "object": "list" field, a data array with one embedding per input, and a usage block with the token count.
Pricing and a Worked Cost Example
You pay only for input tokens. There is no output charge, and the dimensions setting does not change the price.
| Model | Standard (per 1M tokens) | Batch API (per 1M tokens) |
|---|---|---|
text-embedding-3-small |
$0.02 | $0.01 |
text-embedding-3-large |
$0.13 | $0.065 |
text-embedding-ada-002 |
$0.10 | $0.05 |
Batch prices are the standard price with the Batch API’s 50% discount applied. For chat model prices, see my OpenAI API pricing guide.
Worked example: a 10,000-article help center
Say you have 10,000 articles of about 500 tokens each. That is 5 million tokens to embed once.
| Item | 3-small | 3-large |
|---|---|---|
| Index 5M tokens (standard) | 5 x $0.02 = $0.10 | 5 x $0.13 = $0.65 |
| Index 5M tokens (Batch API) | $0.05 | $0.325 |
| 1M searches a month at 20 tokens each (20M tokens) | 20 x $0.02 = $0.40 | 20 x $0.13 = $2.60 |
| Storage at default size (float32) | 10,000 x 1,536 x 4 bytes = about 61 MB | 10,000 x 3,072 x 4 bytes = about 123 MB |
Storage with dimensions=256 |
about 10 MB | about 10 MB |
The API bill is tiny. For most projects, storage and vector database fees cost more than the embeddings themselves, which is why dimensions matters.
Tip: Cache vectors and only re-embed text that changed. Hash each document and skip any hash you have already embedded.
Limits and Rate Limits
These are the hard limits from the API reference:
| Limit | Value |
|---|---|
| Max tokens per input | 8,192 (all embedding models) |
| Max inputs per request | 2,048 |
| Max total tokens per request | 300,000 |
| Empty input | Not allowed |
dimensions |
v3 models only, minimum 1 |
| Batch API | 50,000 requests, 200 MB file, 50,000 embedding inputs per batch |
Default rate limits are the same for both v3 models, according to their model pages:
| Tier | Requests per minute | Requests per day | Tokens per minute | Batch queue limit |
|---|---|---|---|---|
| Free | 100 | 2,000 | 40,000 | – |
| Build | 5,000 | – | 1,000,000 | 20,000,000 |
| Launch | 10,000 | – | 5,000,000 | 500,000,000 |
| Grow | 10,000 | – | 10,000,000 | 4,000,000,000 |
Your own limits can differ, so check the Limits page of your project. For how tiers work across providers, read LLM API rate limits and tiers explained.
Troubleshooting: Common Problems and Fixes
| Error message | Cause | Fix |
|---|---|---|
| 401 “Incorrect API key provided” | Typo, stray space, deleted key or key from another project. | Create a new key and set OPENAI_API_KEY again. Restart your terminal. |
| 400 “This model’s maximum context length is 8192 tokens, however you requested … tokens” | One input is longer than 8,192 tokens. | Count tokens with tiktoken and chunk or truncate long texts. |
| 400 “‘$.input’ is invalid” | An empty list, or a list containing an empty string. | Filter out empty items before the call, or replace them with a space. |
| 400 “This model does not support specifying dimensions.” | You passed dimensions to text-embedding-ada-002. |
Switch to a text-embedding-3 model, or remove the parameter. |
| 429 “Rate limit reached for requests” | Too many requests or tokens per minute. | Batch inputs into lists and retry with exponential backoff. |
| 429 credit balance exhausted | Your organization has no prepaid credit left. | Add credit in Billing settings. Retrying will not help. |
| 503 “Model temporarily overloaded” | Short capacity problem on OpenAI’s side. | Wait and retry. Check the OpenAI status page. |
Search results look wrong
- Mixed models: documents and queries were embedded with different models or different
dimensions. Re-embed with one setting. - Order mix-up: you matched vectors to texts by position after a retry. Sort by
indexor use IDs. - Chunks too big: one vector for a 20-page document blurs its meaning. Split into paragraphs of a few hundred tokens.
Frequently Asked Questions
Which OpenAI embedding model is best?
text-embedding-3-large scores highest on MTEB (64.6%). For most apps, text-embedding-3-small (62.3%) is the better value at about one sixth of the price.
How many dimensions do OpenAI embeddings have?
text-embedding-3-small returns 1,536 dimensions and text-embedding-3-large returns 3,072 by default. You can lower either one with the dimensions parameter.
How much do OpenAI embeddings cost?
$0.02 per 1M tokens for small and $0.13 per 1M for large. The Batch API cuts both by 50%.
Do I need a vector database?
Not for small projects. A numpy array works well for thousands or tens of thousands of vectors, and a vector database helps once you reach millions.
Can I use cosine similarity or dot product?
Both work. OpenAI embeddings have a length of about 1, so dot product and cosine similarity give the same ranking.
Is text-embedding-ada-002 still available?
Yes, it is still listed in the API’s model options. It costs $0.10 per 1M tokens, which is more than text-embedding-3-small, so new projects should use v3.
How does OpenAI compare with Gemini embeddings?
Both turn text into vectors for search and RAG. See my Gemini Embedding 2 tutorial for Google’s model, then test both on your own data before you decide.
Sources
- OpenAI: Vector embeddings guide
- OpenAI API reference: Create embeddings
- OpenAI: text-embedding-3-small model page
- OpenAI: text-embedding-3-large model page
- OpenAI: Batch API guide
- OpenAI Cookbook: Embedding texts that are longer than the model’s maximum context length
- OpenAI: Error codes
- OpenAI: New embedding models and API updates
- PyPI: openai Python package



