Square CloudSquare Cloud

What are embeddings and what are they used for?

Embeddings are lists of numbers (vectors) that a model generates to represent the meaning of a text, image or audio clip. Similar content produces nearby vectors, so you can search, group and classify by meaning.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand what an embedding is and how cosine similarity compares two vectors
  • Know what the number of dimensions changes in quality, storage and speed
  • Learn the main uses (semantic search, RAG, classification, deduplication) and the limits
On this page

A computer compares text character by character. To it, "deploy my app" and "put my code on the server" have nothing in common, even though they mean the same thing. Keyword search fails right there: the user types one phrasing and the document uses another.

Embeddings fix that by turning meaning into geometry. Each text becomes a point in a space with many dimensions, and texts with similar meaning land close together. They power semantic search, recommendations and the retrieval step of RAG.

What is an embedding?#

An embedding is a vector of floating-point numbers that a model generates to represent the meaning of a piece of content. In practice, you send a text and get back something like [0.012, -0.044, 0.031, ...], with hundreds or thousands of positions.

The vector comes from an embedding model, which is a different model from the chat model that writes answers. It was trained so that content with the same meaning lands close together in the space and unrelated content lands far apart. You cannot read meaning from the individual numbers: what matters is where one vector sits relative to the others.

The same idea works for images and audio, as long as the model accepts that kind of input. This article uses text, the most common case.

How do you compare two embeddings?#

The most common measure is cosine similarity: the cosine of the angle between the two vectors. It ranges from -1 to 1. The closer to 1, the more the vectors point the same way and the closer the meaning. You compute it as the dot product of the vectors divided by the product of their lengths.

Two variations show up in tools:

  • Dot product (inner product). If the vectors are already normalized to length 1, it gives the same value as the cosine and is cheaper to compute. OpenAI states that its embeddings are normalized this way, so cosine similarity and Euclidean distance produce the same ranking.
  • Euclidean distance (L2). The straight-line distance between the points. Here, smaller means more similar.

The example below generates real embeddings with the OpenAI SDK and ranks three sentences by similarity to a query. Install with pip install openai numpy and save it as similarity.py:

python
import os

import numpy as np
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from the environment
MODEL = os.environ["OPENAI_EMBEDDING_MODEL"]

documents = [
    "How to keep my Discord bot online 24/7",
    "Carrot cake recipe with chocolate frosting",
    "Step-by-step guide to deploying a Python API",
]
query = "host a bot"

response = client.embeddings.create(model=MODEL, input=documents + [query])
vectors = np.array([item.embedding for item in response.data])
docs, q = vectors[:-1], vectors[-1]

# cosine: dot product divided by the product of the lengths
sims = docs @ q / (np.linalg.norm(docs, axis=1) * np.linalg.norm(q))

for i in np.argsort(-sims):
    print(f"{sims[i]:.3f}  {documents[i]}")
print("dimensions:", vectors.shape[1])

Set the variables and run it:

bash
export OPENAI_API_KEY="your-key"
export OPENAI_EMBEDDING_MODEL="id-of-an-embedding-model"
python similarity.py

The model ID comes from the provider's models page. With any reasonable embedding model, expect the bot sentence to rank first, the deployment one second and the recipe last, even though none of them contains the word "host". The absolute scores change from model to model; the order is what holds.

What are the dimensions of an embedding?#

Each position in the vector is a dimension. The model decides how many there are, usually between a few hundred and a few thousand. More dimensions can capture finer distinctions, but they cost storage and search time.

The storage math is simple. A single-precision float takes 4 bytes, so a 1,536-dimension vector takes about 6 KB. A million vectors pass 6 GB before any index. That is why some providers let you request smaller vectors: OpenAI has the dimensions parameter and Google has output_dimensionality. A shortened vector needs to be normalized again: OpenAI asks for it when you truncate a vector yourself, and Google, for some of its models, even when you use the parameter.

The database sets limits too. In pgvector, the vector extension for PostgreSQL, a vector column holds up to 16,000 dimensions, but HNSW and IVFFlat indexes only cover up to 2,000. The half-precision halfvec type uses 2 bytes per dimension and can be indexed up to 4,000. Choosing between an extension and a dedicated database is covered in pgvector vs a dedicated vector database.

What are embeddings used for?#

Almost every use comes down to one question: what is close to this vector?

Use How the embedding fits in Example
Semantic search The query becomes a vector and you fetch the closest documents Finding "refund policy" when the user types "I want my money back"
RAG The passages closest to the question go into the LLM's prompt A chatbot that answers from your documentation
Classification Compare the text with labeled examples or label vectors, or feed the vector to a classifier Sorting tickets into "billing", "bug" and "question"
Clustering Nearby vectors form groups Finding the most common topics in a thousand reviews
Deduplication Two items above a similarity threshold count as the same Merging repeated questions in a forum
Recommendations Items close to what the person already used "Articles similar to this one"

Search and RAG are the most common uses in LLM apps. Storing the vectors and finding neighbors quickly is the job of a vector database, and the full flow, with table and query, is in how to build a RAG chatbot with PostgreSQL and pgvector.

Why use the same model for documents and queries?#

Because every model has its own space. The vector model A produces for "host a bot" has no relationship with the vector model B produces for the same sentence, even if both have the same number of dimensions. Comparing them gives meaningless numbers.

In practice, that leads to three rules:

  1. Documents and queries use the same model. If you embedded the documents with one model, the user's question must go through the same one.
  2. Switching models means re-embedding everything. Google says it plainly when comparing two generations of its own embedding models: the spaces are incompatible, and upgrading means re-embedding all existing data. Store the model name next to each vector so you know what needs redoing.
  3. Follow the model's instructions for each side. Some models ask you to say whether a text is a query or a document. Google, for example, has the RETRIEVAL_QUERY and RETRIEVAL_DOCUMENT task types, and for other models uses a prefix in the text itself. Same model, different marking for each role.

Preprocess both sides the same way, too: if you strip HTML or split documents into chunks, apply the same cleanup to queries.

What are the limits of embeddings?#

  • Exact terms. Error codes, order numbers and function names are poorly served by closeness of meaning: "error 502" and "error 504" may land very close. Combine with text search. pgvector, for instance, documents hybrid search with PostgreSQL full-text search.
  • Thresholds depend on the model. There is no universal similarity value that means "same". To deduplicate or filter, calibrate the threshold with your own examples, and recalibrate if you switch models.
  • Input size. Each model accepts a maximum number of tokens per text; OpenAI, for example, documents 8,192 for its embedding models. Long texts need to be split into chunks, which also makes search more precise.
  • Language and domain. A model that is weak in your language or your business vocabulary returns poor neighbors, no matter how fast the index is. Test with real queries before you choose.
  • Cost and time. Every text you embed is an API call billed by token. Embed documents once, store the result and only redo what changed. The pricing logic is the same as in how much an LLM API costs.

Embeddings do not replace the LLM either: they find the content, but they do not write the answer.

How to do this on Square Cloud#

A system built on embeddings has three parts: whatever generates the vectors, the place they live and the application that connects the two. On Square Cloud, the hosted PostgreSQL comes with the pgvector extension, so the vectors can sit in the same table as the text and metadata, and a RAG system's vector index can live there. Database hosting starts on the Standard plan, from R$44.99 a month, and a PostgreSQL database uses at least 1024 MB of the plan's RAM. Each database is a fixed, single-node instance.

The dashboard gives you the full connection URL, and TLS is required: the client trusts the CA downloaded from the dashboard and presents the certificate (.pem). Copy the URL into an environment variable of your application, along with the key for your embedding provider.

The vectors come from an embedding provider of your choice. The AI Gateway, also from Standard, does not generate embeddings: it serves the cubic model for the text step, such as the final answer of a RAG system built from the passages your search found. See the database details on PostgreSQL hosting.

AI

Host AI apps in always-on containers

PostgreSQL hosting

FAQs

What is the difference between an embedding and a vector database?

The embedding is the data: the vector that represents a text. The vector database is where you store those vectors and find the ones closest to a query, with indexes that speed up the search.

Can I mix embeddings from different models?

No. Each model has its own vector space, and vectors from different models are not comparable, even when they have the same number of dimensions. When you switch models, re-embed every document.

How many dimensions should an embedding have?

The model sets the default, usually somewhere between a few hundred and a few thousand. Some providers let you request fewer: smaller vectors take less space and search faster. Measure quality on your own queries before you shrink them.

Is an embedding the same as tokenization?

No. Tokenization splits text into tokens, the pieces a model reads. An embedding is a single vector that sums up the meaning of the whole passage.

Next articleWhat is an AI agent (and how it differs from a chatbot)?An AI agent is a language model that picks, in a loop, which tools to use until it reaches a goal. Learn how it works, how it differs from a chatbot and the risks.