Ir para o conteúdo

Lição 13 · Embeddings and Retrieval

Embeddings and Semantic Search

Create OpenAI embeddings, compare vectors with cosine similarity, shorten dimensions, store vectors in a database and build a small semantic search.

Keyword search finds the words you type. A user who searches for "money back" may miss a page titled "Refund policy." An embedding helps here. It is a list of numbers that represents a piece of text, produced by a model so that texts with related meanings tend to get similar vectors. You can compare vectors to find related text.

Embeddings power semantic search, recommendations, grouping, duplicate detection and retrieval for chat apps.

Create an embedding

Embeddings use their own endpoint and their own models.

Python
# Read-only
response = client.embeddings.create(
    model="text-embedding-3-small",
    input=["How do I get a refund?", "Our opening hours"],
)

vectors = [item.embedding for item in response.data]
print(len(vectors[0]))   # number of dimensions

As of December 2026, the documentation lists these current models:

Model Default dimensions Max input tokens Price per 1M tokens
text-embedding-3-small 1536 8192 $0.02
text-embedding-3-large 3072 8192 $0.13

An older model, text-embedding-ada-002, still appears in the docs. Choose the newer ones for new work. Check the current price page before you budget.

Compare vectors with cosine similarity

Cosine similarity measures how closely two vectors point in the same direction. A higher value means more similar. It is the dot product divided by the product of the lengths. If both vectors have length 1, the dot product alone is enough.

Real embeddings have hundreds or thousands of numbers. The runnable example below uses hand-made three-number vectors so you can follow the math. Think of the three positions as "refund," "delivery" and "hours." Real embedding dimensions do not have readable meanings like these.

Python Stand-in: semantic ranking with tiny vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

"Money back" finds "Refund policy" although they share no words. In a real system, the embedding model produces the vectors.

Rules that keep search working

  • Use the same model for documents and queries. Vectors from different models, or different dimension settings, cannot be compared.
  • Record the model and dimensions next to stored vectors.
  • If you change models, re-embed all documents before you switch queries.
  • Embed only text you are allowed to send to the API.
  • When a document changes, replace its vectors. When it is deleted, delete them too.

A content hash helps you re-embed only what changed:

Python
import hashlib

def fingerprint(text, model):
    return hashlib.sha256((model + "\n" + text).encode()).hexdigest()

Shorten vectors

The v3 models accept a dimensions parameter that returns shorter vectors. Shorter vectors use less storage and compare faster, with a possible loss in quality that you should test.

Python
# Read-only
response = client.embeddings.create(
    model="text-embedding-3-large",
    input="Refund policy",
    dimensions=1024,
)

The documentation recommends this parameter over cutting vectors yourself. If you do cut a vector after you receive it, normalize it again so its length is 1.

Split long documents

One embedding for a 30-page manual mixes many topics. Search works better on chunks: sections or groups of paragraphs. Keep headings with their text, keep the source and position of each chunk, and allow a little overlap if ideas cross boundaries. Each input must also fit the token limit. Chunking documents compares strategies.

Store and search vectors

For a few thousand chunks, you can keep vectors in memory and compare the query with all of them. For larger collections, use a database with vector support or a vector database, which uses indexes to search quickly. Your normal data still matters: store the text, source, owner and access rules with each vector, and filter by permission before returning results. You can also use OpenAI's hosted vector stores, which the next lesson covers.

Many strong search systems combine embeddings with keyword search. Exact codes such as ERR-4021 are often easier to find with keywords. See hybrid search and reranking.

Similarity is not truth

A high score means the texts are close in the model's view. It does not mean the document answers the question or that it is current. Two sentences that differ only by "not" can look very similar. Test search with real questions: for each one, note which document should appear, and measure how often it is in the top results.

Python Measure hit rate at k

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Do not pick a fixed score cutoff by guessing. Score ranges depend on the model and your data. Choose thresholds from labeled test questions.

Other uses for embeddings

Search is only one use. The same vectors can:

  • Find near-duplicates, such as two support tickets about the same problem. Compare each new item with recent ones and show likely matches to a person.
  • Group items with a clustering method, to discover common themes in feedback.
  • Recommend related articles by finding the nearest neighbors of the one being read.
  • Classify by comparing text with a few labeled examples. This can be a cheap first pass, but test it against your categories.

Each use needs its own check. A threshold that works for search may be wrong for duplicate detection, where a false match could merge two different customers' problems.

Cost and updates

Embedding is billed by input tokens. Estimate the cost of your first full index, then of regular updates. Send several texts in one request where the limits allow, and use the fingerprint idea so unchanged chunks are not embedded again. For a large first load that is not urgent, the Batch API supports the embeddings endpoint.

Remember that vectors are derived from your text. Protect them as you protect the text, and delete them when the source is deleted.

Common mistakes

  • Changing the embedding model for new documents only, which mixes two vector spaces in one index.
  • Embedding page navigation, footers and other repeated text, which makes unrelated chunks look alike.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is an embedding?

    Embeddings are used to compare texts, not to store them for exact recovery.
  2. 2. Can you compare vectors from two different embedding models?

    Each model has its own vector space.
  3. 3. What should you do after truncating a vector yourself?

    Normalizing keeps comparisons meaningful after cutting.
  4. 4. Why filter results by permission?

    Search must respect the same access rules as the rest of your app.

Summary

  • Embeddings turn text into vectors that you can compare.
  • Cosine similarity ranks related content.
  • Keep models and dimensions consistent, and update vectors when text changes.
  • Chunk long documents and enforce access rules.
  • Evaluate search with your own questions.

Next: Vector Stores and File Search

Seu progresso fica salvo neste navegador. Não precisa de conta.