For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Primary navigation

Vector embeddings

Learn how to turn text into numbers, unlocking use cases like search.

New embedding models
text-embedding-3-small and text-embedding-3-large, our newest and most performant embedding models, are now available. They feature lower costs, higher multilingual performance, and new parameters to control the overall size.

What are embeddings?

OpenAI’s text embeddings measure the relatedness of text strings. Embeddings are commonly used for:

  • Search (where results are ranked by relevance to a query string)
  • Clustering (where text strings are grouped by similarity)
  • Recommendations (where items with related text strings are recommended)
  • Anomaly detection (where outliers with little relatedness are identified)
  • Diversity measurement (where similarity distributions are analyzed)
  • Classification (where text strings are classified by their most similar label)

An embedding is a vector (list) of floating point numbers. The distance between two vectors measures their relatedness. Small distances suggest high relatedness and large distances suggest low relatedness.

Visit our pricing page to learn about embeddings pricing. Requests are billed based on the number of tokens in the input.

How to get embeddings

To get an embedding, send your text string to the embeddings API endpoint along with the embedding model name (for example, text-embedding-3-small):

Example: Getting embeddings
import OpenAI from "openai";
const openai = new OpenAI();

const embedding = await openai.embeddings.create({
  model: "text-embedding-3-small",
  input: "Your text string goes here",
  encoding_format: "float",
});

console.log(embedding);

The response contains the embedding vector (list of floating point numbers) along with some additional metadata. You can extract the embedding vector, save it in a vector database, and use for many different use cases.

{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [
        -0.006929283495992422, -0.005336422007530928, -4.547132266452536e-5,
        -0.024047505110502243
      ]
    }
  ],
  "model": "text-embedding-3-small",
  "usage": {
    "prompt_tokens": 5,
    "total_tokens": 5
  }
}

By default, the length of the embedding vector is 1536 for text-embedding-3-small or 3072 for text-embedding-3-large. To reduce the dimensions of an embedding without losing its ability to represent concepts, pass in the dimensions parameter. Find more detail on embedding dimensions in the embedding use case section.

Embedding models

OpenAI offers two powerful third-generation embedding model (denoted by -3 in the model ID). Read the embedding v3 announcement blog post for more details.

Usage is priced per input token. Below is an example of pricing pages of text per US dollar (assuming ~800 tokens per page):

Model ~ Pages per dollar Performance on MTEB eval Max input
text-embedding-3-small 62,500 62.3% 8192
text-embedding-3-large 9,615 64.6% 8192
text-embedding-ada-002 12,500 61.0% 8192

Use cases

Here we show some representative use cases, using the Amazon fine-food reviews dataset.

Obtaining the embeddings

The dataset contains a total of 568,454 food reviews left by Amazon users up to October 2012. We use a subset of the 1000 most recent reviews for illustration purposes. The reviews are in English and tend to be positive or negative. Each review has a ProductId, UserId, Score, review title (Summary) and review body (Text). For example:

Product Id User Id Score Summary Text
B001E4KFG0 A3SGXH7AUHU8GW 5 Good Quality Dog Food I have bought several of the Vitality canned…
B00813GRG4 A1D87F6ZCVE5NK 1 Not as Advertised Product arrived labeled as Jumbo Salted Peanut…

Below, we combine the review summary and review text into a single combined text. The model encodes this combined text and outputs a single vector embedding.

Get_embeddings_from_dataset.ipynb

Download and extract the TypeScript samples and locked dependencies, including OpenAI and the CSV parser and writer. Save the review dataset as data/fine_food_reviews_1k.csv and set OPENAI_API_KEY. Keep Summary, Text, Score, UserId, and ProductId; the producer preserves these columns in its output for the analysis programs. Use a dataset with at least four rows for the four-cluster example.

Create review embeddings
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";
import { stringify } from "csv-stringify/sync";
import OpenAI from "openai";

const reviews: Record<string, string>[] = parse(
  await readFile("data/fine_food_reviews_1k.csv", "utf8"),
  { columns: true, skip_empty_lines: true }
);
if (!reviews.length) throw new Error("No reviews in the input CSV");
for (const review of reviews) {
  for (const column of ["Summary", "Text", "Score", "UserId", "ProductId"]) {
    if (typeof review[column] !== "string" || !review[column].trim())
      throw new Error(`Review is missing ${column}`);
  }
  const score = Number(review.Score);
  if (!Number.isInteger(score) || score < 1 || score > 5)
    throw new Error("Score must be an integer from 1 to 5");
}
const combined = reviews.map((review) =>
  `${review.Summary} ${review.Text}`.replaceAll("\n", " ")
);
const client = new OpenAI();
const response = await client.embeddings.create({
  model: "text-embedding-3-small",
  input: combined,
});
const embeddings = [...response.data].sort((a, b) => a.index - b.index);
if (embeddings.length !== reviews.length)
  throw new Error("Embedding response did not include every review");
const rows = reviews.map((review, index) => {
  if (embeddings[index].index !== index)
    throw new Error("Embedding response has invalid review indices");
  return {
    ...review,
    combined: combined[index],
    ada_embedding: JSON.stringify(embeddings[index].embedding),
  };
});
await mkdir("output", { recursive: true });
await writeFile(
  "output/embedded_1k_reviews.csv",
  stringify(rows, { header: true })
);

Download and extract the TypeScript samples and locked dependencies. From the extracted typescript-examples directory, install with pnpm install --ignore-workspace --frozen-lockfile. Run each complete analysis program separately with node --experimental-strip-types embeddings/<filename>.ts from that directory.

The programs read output/embedded_1k_reviews.csv with JSON arrays in ada_embedding and numeric review ratings in Score. Grouped averages also require UserId and ProductId. Each program loads its own input; do not concatenate the excerpts. The linked Python notebooks supply the metrics below. Results from the TypeScript algorithms can differ from those metrics, and t-SNE coordinates can vary between runs.

To load the data from a saved file, you can run the following:

Load saved embeddings
import { readFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";

const records: { Score: string; ada_embedding: string }[] = parse(
  await readFile("output/embedded_1k_reviews.csv", "utf8"),
  { columns: true, skip_empty_lines: true }
);
const rows = records.map((row) => ({
  score: Number(row.Score),
  embedding: JSON.parse(row.ada_embedding) as number[],
}));
if (!rows.length) throw new Error("No embeddings");
const dimensions = rows[0].embedding.length;
for (const row of rows) {
  if (
    !Number.isFinite(row.score) ||
    !Array.isArray(row.embedding) ||
    !dimensions ||
    row.embedding.length !== dimensions ||
    !row.embedding.every(Number.isFinite)
  ) {
    throw new Error(
      "Expected finite scores and embeddings with consistent dimensions"
    );
  }
}
console.log(rows);

FAQ

How can I tell how many tokens a string has before I embed it?

In Python, you can split a string into tokens with OpenAI’s tokenizer tiktoken.

Example code:

Count tokens before embedding
import { getEncoding } from "js-tiktoken";
import type { TiktokenEncoding } from "js-tiktoken";

function numTokensFromString(
  text: string,
  encodingName: TiktokenEncoding
): number {
  return getEncoding(encodingName).encode(text).length;
}

console.log(numTokensFromString("tiktoken is great!", "cl100k_base"));

For third-generation embedding models like text-embedding-3-small, use the cl100k_base encoding.

More details and example code are in the OpenAI Cookbook guide how to count tokens with tiktoken.

How can I retrieve K nearest embedding vectors quickly?

For searching over many vectors quickly, we recommend using a vector database. You can find examples of working with vector databases and the OpenAI API in our Cookbook on GitHub.

Which distance function should I use?

We recommend cosine similarity. The choice of distance function typically doesn’t matter much.

OpenAI embeddings are normalized to length 1, which means that:

  • Cosine similarity can be computed slightly faster using just a dot product
  • Cosine similarity and Euclidean distance will result in the identical rankings

Can I share my embeddings online?

Yes, customers own their input and output from our models, including in the case of embeddings. You are responsible for ensuring that the content you input to our API does not violate any applicable law or our Terms of Use.

Do V3 embedding models know about recent events?

No, the text-embedding-3-large and text-embedding-3-small models lack knowledge of events that occurred after September 2021. This is generally not as much of a limitation as it would be for text generation models but in certain edge cases it can reduce performance.