LESSON 27 Β· EMBEDDINGS

Text Embeddings

Go deeper into how text is represented as vectors. Learn how documents and queries are embedded, how similarity search works, and how to build a practical text-embedding workflow with Python.

30 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain how text is converted into an embedding vector.
  • Distinguish document embeddings from query embeddings.
  • Understand similarity search at a practical level.
  • Prepare text before embedding and avoid common mistakes.
  • Build a small text-embedding search workflow with Python.
1

Text Becomes a Numerical Representation

A text embedding model takes text as input and returns a vector of numbers. The vector is a representation that applications can use for comparison and retrieval.

TEXTβ€œHow do I change my password?”
β†’
EMBEDDING MODELRepresent meaning
β†’
VECTOR[0.18, -0.42, 0.73, …]
Think of it this way:Text is easy for humans to read. Vectors are easier for software to compare mathematically.
2

Document Embeddings vs Query Embeddings

A semantic search system usually embeds two sides: the content you want to search and the user's query. Both need compatible representations so they can be compared.

DOCUMENT EMBEDDING

Stored content

β€œTo reset your password, open Account Settings and select Security.”

β†’ stored as a vector
QUERY EMBEDDING

User question

β€œWhere can I change my password?”

β†’ compared with document vectors

The search system can rank stored documents according to their similarity to the query vector.

3

The Text Embedding Pipeline

01CollectDocuments or text
β†’
02CleanRemove noise
β†’
03ChunkSplit long content
β†’
04EmbedCreate vectors
β†’
05StoreVectors + metadata

At query time, the application embeds the user's question, searches the stored vectors, and returns the most relevant text.

4

Prepare Text Before Embedding

The embedding model can only represent the text you give it. Unnecessary navigation, repeated headers, broken extraction, or irrelevant boilerplate can make retrieval less useful.

NOISY TEXT
HOME | PRODUCTS | LOGIN | SUPPORT

Refund Policy
Refunds may be requested within 30 days...

FOOTER
Copyright 2026...
β†’
USEFUL TEXT
Refund Policy

Refunds may be requested
within 30 days of purchase.
Practical rule:Preserve information that helps answer questions and avoid embedding large amounts of irrelevant repeated content.
5

Why Chunking Matters

Long documents are often divided into smaller chunks before embedding. A query can then retrieve the specific passages that are most relevant.

LONG DOCUMENT
β†’
Chunk 1Introduction
Chunk 2Refund policy
Chunk 3Password reset
Chunk 4Contact details

Very small chunks can lose context, while very large chunks can mix unrelated information and increase retrieval payload.

6

Similarity Search

After creating a query embedding, the system compares it with stored document embeddings and ranks the closest matches.

QUERYβ€œHow do I reset my password?”
1

Password reset instructions

0.94
2

Account login troubleshooting

0.86
3

Update account profile

0.62
4

Shipping address changes

0.21

Scores here are examples, not universal thresholds. Your model, data, and evaluation method determine what scores are useful.

7

Python: Create Text Embeddings

An embedding API converts text into a vector that your application can store, compare, or send to a vector database.

PythonEmbedding one text
from openai import OpenAI

client = OpenAI()

text = "Refunds are available within 30 days."

response = client.embeddings.create(
    model="YOUR_EMBEDDING_MODEL",
    input=text,
)

embedding = response.data[0].embedding

print("Vector length:", len(embedding))
print("First 5 values:", embedding[:5])
8

Python: Embed Multiple Texts

Embedding multiple inputs is useful when preparing a document collection for search.

PythonBatch embedding
from openai import OpenAI

client = OpenAI()

texts = [
    "How do I reset my password?",
    "How can I request a refund?",
    "Where is my order?",
]

response = client.embeddings.create(
    model="YOUR_EMBEDDING_MODEL",
    input=texts,
)

embeddings = [
    item.embedding
    for item in response.data
]

for text, vector in zip(texts, embeddings):
    print(text)
    print("Dimensions:", len(vector))
Production note:For large datasets, process documents in sensible batches, store vectors with stable document IDs, and keep the original text or a reliable reference to it.
9

Python: Calculate Cosine Similarity

Cosine similarity compares the direction of two vectors and is commonly used for semantic similarity.

PythonCompare vectors
import numpy as np

def cosine_similarity(a, b):
    a = np.array(a)
    b = np.array(b)

    return np.dot(a, b) / (
        np.linalg.norm(a) * np.linalg.norm(b)
    )

score = cosine_similarity(
    query_embedding,
    document_embedding,
)

print("Similarity:", score)
ConceptuallyQuery vector + Document vector β†’ Similarity scoreHigher similarity can indicate more closely aligned representations.
10

Build a Small Semantic Search

A basic semantic search implementation embeds a query, scores stored vectors, and sorts the results.

PythonMinimal semantic search
documents = [
    {"text": "Reset your password from Account Settings.",
     "embedding": password_vector},
    {"text": "Refunds can be requested within 30 days.",
     "embedding": refund_vector},
    {"text": "Track your order from the Orders page.",
     "embedding": shipping_vector},
]

query_vector = embed("I forgot my password.")

results = []

for document in documents:
    score = cosine_similarity(
        query_vector,
        document["embedding"],
    )
    results.append({
        "text": document["text"],
        "score": score,
    })

results.sort(key=lambda item: item["score"], reverse=True)

for result in results:
    print(result)
11

Embeddings Need Metadata Too

A vector by itself is rarely enough for a useful application. Store metadata that helps you identify, filter, and reconstruct the source of each result.

VECTOR[0.18, -0.42, 0.73, …]
DOCUMENT IDfaq-104
SOURCEaccount-help.html
SECTIONPassword reset
LANGUAGEen

Metadata can support filters such as product, language, customer type, date, or access permissions.

12

Normalization and Consistent Comparison

Vector search systems may normalize vectors or use distance measures where normalization is useful. The exact approach depends on the model and database.

RAW VECTOR[2.0, 4.0, 1.0]Magnitude matters
β†’
NORMALIZED[0.44, 0.88, 0.22]Unit-length representation
Do not assume:Whether to normalize and which distance metric to use are system-specific decisions.
13

Text Embeddings Across Languages

Multilingual applications should evaluate how well the selected embedding model represents the languages used by their users and documents.

Englishβ€œHow do I reset my password?”
Spanishβ€œΒΏCΓ³mo restablezco mi contraseΓ±a?”
Frenchβ€œComment rΓ©initialiser mon mot de passe ?”
QueryCompare compatible representations.

Evaluate multilingual retrieval with real examples instead of assuming identical performance across languages.

14

Common Text Embedding Mistakes

01Mixing incompatible embedding spaces

Compare vectors only when they are designed to share a compatible representation space.

02Embedding noisy content

Repeated navigation and irrelevant boilerplate can reduce retrieval usefulness.

03Ignoring chunk design

Chunk boundaries affect whether useful context is retrieved.

04Trusting scores blindly

A similarity score is a signal. Evaluate whether results are actually useful.

HANDS-ON PRACTICE

Build a Mini FAQ Semantic Search

Create a small FAQ collection and use text embeddings to retrieve the most relevant answer.

  1. Create 10 FAQ entries for a fictional online store.
  2. Clean the text and give each FAQ a stable ID.
  3. Create embeddings for all 10 entries.
  4. Write five user questions that do not exactly repeat the FAQ wording.
  5. Embed each query and rank the FAQ entries by similarity.
  6. Check whether the top result is actually useful.
Challenge: Add metadata for category and language, then filter candidate results before ranking them.
QUICK QUIZ

Test Your Understanding

1. What does a text embedding model return?

A numerical vector representation of the supplied text.

2. Why embed the query?

So the query can be compared with stored document representations in the same compatible vector space.

3. Why does chunking matter?

It determines the units that can be retrieved and influences how much relevant context each result contains.

4. Is a high similarity score proof that a result is correct?

No. Similarity is a retrieval signal and should be evaluated against real queries and expected results.

30-SECOND RECAP

Text Embeddings in One Flow

TextDocuments and queries
β†’
EmbeddingNumerical vector
β†’
SimilarityCompare vectors
β†’
RankingRelevant results

Key Takeaways

  • Text embeddings convert text into numerical vectors.
  • Document and query embeddings enable semantic search.
  • Cleaning and chunking can have a major effect on retrieval quality.
  • Cosine similarity is one common way to compare text vectors.
  • Useful systems store vectors together with document IDs and metadata.
  • Evaluate retrieved results with realistic queries instead of trusting similarity scores alone.