Embedding

Embedding is a fundamental technology in machine learning and natural language processing that transforms discrete or complex objects (such as words, sentences, or images) into numerical vector representations of a fixed dimension.

In a RAG (Retrieval-Augmented Generation) system, embedding is the foundation of retrieval. Without embeddings, you cannot perform semantic search — you would be stuck with keyword matching only

Core Concepts

Vector Space & Similarity

Embeddings live in a multi-dimensional vector space. To measure how similar two pieces of text are, we measure the distance between their embedding vectors. The most common measure is cosine similarity.
存在于一个多维向量空间中。要衡量两段文本有多相似,我们衡量它们的 Embedding 向量之间的距离。最常用的度量是余弦相似度(Cosine Similarity).

Cosine Similarity explained:

  • Range: -1 (opposite) to 1 (identical)
    -1(相反)到 1(完全相同)
  • For text embeddings, values close to 1 mean high semantic similarity
    对于文本 Embedding,接近 1 的值表示高语义相似度
  • It measures the cosine of the angle between two vectors, ignoring magnitude
    它测量两个向量之间的夹角余弦值,忽略向量大小
import numpy as np

def cosine_similarity(vec_a: np.ndarray, vec_b: np.ndarray) -> float:
    """
    Calculate cosine similarity between two vectors.
    计算两个向量之间的余弦相似度。
    
    Purpose: Measures semantic similarity between two embeddings.
    目的:衡量两个 Embedding 之间的语义相似度。
    """
    # Normalize vectors / 归一化向量
    norm_a = np.linalg.norm(vec_a)
    norm_b = np.linalg.norm(vec_b)
    
    # Dot product / 点积
    dot_product = np.dot(vec_a, vec_b)
    
    # Cosine similarity = dot product / (norm_a * norm_b)
    # 余弦相似度 = 点积 / (norm_a * norm_b)
    return dot_product / (norm_a * norm_b)

Dense vs Sparse Vectors

稠密向量 vs 稀疏向量

AspectDense EmbeddingSparse (One-Hot)
DimensionFixed, low (e.g., 384, 768, 1536)Very high (vocabulary size)
ValuesContinuous floats0 or 1
Semantic info
语义信息
Captures meaning
捕获含义
Only captures identity
仅捕获身份
EfficiencyComputationally efficientWastes memory

Sparse (One-Hot) 中,每个词是一个独立的维度,”king”是 [0,0,0,…,1,…,0],”queen”是另一个位置。它们没有任何语义关系。而 Embedding 中,”king”和”queen”的向量是相似的。

Captures meaning 捕获含义 = 不看字,看“意思像不像”
Only captures identity 仅捕获身份 = 只认“是不是这个词”,不管什么意思

Contextual vs Static Embeddings

上下文 Embedding vs 静态 Embedding

TypeExamplesCharacteristics
StaticWord2Vec, GloVe, FastTextOne vector per word, regardless of context
每个词一个向量,无论上下文
ContextualBERT-based, OpenAI text-embedding-3Vector changes based on surrounding words
向量根据周围词变化
  • Word2Vec: Word2Vec is a method that learns word meanings by looking at the context in which words appear.
    是一种通过“上下文”来学习词语含义的模型。它通过“上下文预测”学习词向量的方法。看词和词之间的搭配关系来学习语义,让语义相似的词在向量空间中靠得更近。
  • GloVe = Global Vectors for Word Representation. It learns word meaning from: global word co-occurrence statistics
    “统计全世界词和词的关系”
  • FastText:FastText (Facebook) represents words as: sum of character n-grams把“词拆成字母/子词”来学向量

“bank” in “river bank” vs “bank account” : static embedding gives the same vector; contextual embedding gives different vectors based on context.
静态 Embedding 给相同的向量;上下文 Embedding 根据上下文给不同的向量。

BERT = Bidirectional Encoder Representations from Transformers

It learns: context-aware word meaning using Transformer attention
用 Transformer(注意力机制)来理解上下文的语言模型。
“河岸”,“银行账号” “同一个词,在不同句子里有不同含义”

Mainstream Embedding Models

For modern RAG systems, the most relevant embedding models are

ModelProviderDimNotes
text-embedding-3-smallOpenAI1536Cost-effective, good for most RAG
text-embedding-3-largeOpenAI3072Higher quality, higher cost
text-embedding-ada-002OpenAI1536Legacy, being replaced by v3
BGE-M3BAAI1024Open-source, multilingual
KaLM-Embedding-Gemma3-12BTencent3840SOTA on MMTEB

Code Implementation

OpenAI API generates Embedding:

# ============================================================
# 1. IMPORTS / 导入依赖
# ============================================================
import os
import numpy as np
from openai import OpenAI
from typing import List, Dict, Any

# ============================================================
# 2. CLIENT INITIALIZATION / 客户端初始化
# ============================================================
# Purpose: Initialize the OpenAI client with API key from environment.
# 目的:使用环境变量中的 API Key 初始化 OpenAI 客户端。
client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),  # Get from env / 从环境变量获取
)

# ============================================================
# 3. EMBEDDING FUNCTION / Embedding 生成函数
# ============================================================
def get_embedding(
    text: str, 
    model: str = "text-embedding-3-small"
) -> List[float]:
    """
    Generate an embedding vector for a given text using OpenAI API.
    使用 OpenAI API 为给定文本生成 Embedding 向量。
    
    Purpose: Convert text into a numerical vector for semantic search.
    目的:将文本转换为数值向量,用于语义搜索。
    
    Args:
        text: Input text string / 输入文本字符串
        model: Embedding model name / Embedding 模型名称
        
    Returns:
        List[float]: Embedding vector of length model-specific dimension
        List[float]: Embedding 向量,长度为模型指定的维度
        
    Important: The same model must be used for both query and document embeddings
    重点:查询和文档的 Embedding 必须使用同一个模型[reference:30]
    """
    # Remove newlines and excess whitespace for cleaner embedding
    # 移除换行和多余空白,获得更干净的 Embedding
    text = text.replace("\n", " ")
    
    # Call OpenAI Embeddings API / 调用 OpenAI Embeddings API
    # Purpose: Send text to OpenAI and get back the embedding vector
    # 目的:发送文本到 OpenAI,获取 Embedding 向量
    response = client.embeddings.create(
        model=model,           # Which embedding model to use / 使用的模型
        input=text,            # Text to embed / 要嵌入的文本
        encoding_format="float"  # Return as list of floats / 以浮点数列表返回
    )
    
    # Extract the embedding from response / 从响应中提取 Embedding
    # Purpose: The embedding is in response.data[0].embedding
    # 目的:Embedding 位于 response.data[0].embedding 中
    embedding = response.data[0].embedding
    
    return embedding

# ============================================================
# 4. BATCH EMBEDDING / 批量 Embedding
# ============================================================
def get_embeddings_batch(
    texts: List[str],
    model: str = "text-embedding-3-small"
) -> List[List[float]]:
    """
    Generate embeddings for multiple texts in a single API call.
    在单个 API 调用中为多个文本生成 Embedding。
    
    Purpose: More efficient than calling get_embedding() in a loop.
    目的:比在循环中调用 get_embedding() 更高效。
    
    Important: OpenAI limits total tokens to 300,000 per request[reference:31]
    重点:OpenAI 限制每个请求总 token 不超过 300,000[reference:32]
    """
    # Clean texts / 清理文本
    cleaned_texts = [t.replace("\n", " ") for t in texts]
    
    # Batch API call / 批量 API 调用
    response = client.embeddings.create(
        model=model,
        input=cleaned_texts,   # List of texts / 文本列表
        encoding_format="float"
    )
    
    # Extract all embeddings / 提取所有 Embedding
    # Purpose: Each response.data[i] corresponds to texts[i]
    # 目的:每个 response.data[i] 对应 texts[i]
    embeddings = [item.embedding for item in response.data]
    
    return embeddings

# ============================================================
# 5. SIMILARITY SEARCH / 相似度搜索
# ============================================================
def cosine_similarity(vec_a: List[float], vec_b: List[float]) -> float:
    """
    Calculate cosine similarity between two embedding vectors.
    计算两个 Embedding 向量之间的余弦相似度。
    
    Purpose: Measure semantic similarity between query and document.
    目的:衡量查询和文档之间的语义相似度。
    
    Important: Embeddings must be from the SAME model.
    重点:Embeddings 必须来自同一个模型。
    """
    # Convert to numpy arrays for efficient math / 转换为 numpy 数组以便高效计算
    a = np.array(vec_a)
    b = np.array(vec_b)
    
    # Calculate cosine similarity / 计算余弦相似度
    # Formula: cos(θ) = (A · B) / (||A|| * ||B||)
    # 公式:cos(θ) = (A · B) / (||A|| * ||B||)
    dot_product = np.dot(a, b)
    norm_a = np.linalg.norm(a)
    norm_b = np.linalg.norm(b)
    
    # Avoid division by zero / 避免除以零
    if norm_a == 0 or norm_b == 0:
        return 0.0
    
    return float(dot_product / (norm_a * norm_b))

def find_most_similar(
    query: str,
    documents: List[str],
    model: str = "text-embedding-3-small",
    top_k: int = 3
) -> List[Dict[str, Any]]:
    """
    Find the most semantically similar documents to a query.
    找到与查询语义最相似的文档。
    
    Purpose: Core retrieval function for RAG systems.
    目的:RAG 系统的核心检索函数[reference:33]。
    
    Args:
        query: User question / 用户问题
        documents: List of document chunks / 文档块列表
        model: Embedding model / Embedding 模型
        top_k: Number of top results to return / 返回前 K 个结果
    
    Returns:
        List of dicts with document text and similarity score
        包含文档文本和相似度分数的字典列表
    """
    # Step 1: Embed the query / 第一步:嵌入查询
    # Purpose: Convert user question to vector for comparison
    # 目的:将用户问题转换为向量以便比较
    query_embedding = get_embedding(query, model)
    
    # Step 2: Embed all documents / 第二步:嵌入所有文档
    # Purpose: Convert all documents to vectors
    # 目的:将所有文档转换为向量
    doc_embeddings = get_embeddings_batch(documents, model)
    
    # Step 3: Calculate similarities / 第三步:计算相似度
    # Purpose: Compare query vector against all document vectors
    # 目的:将查询向量与所有文档向量比较
    results = []
    for i, doc_embedding in enumerate(doc_embeddings):
        score = cosine_similarity(query_embedding, doc_embedding)
        results.append({
            "document": documents[i],
            "score": score,
            "index": i
        })
    
    # Step 4: Sort by score descending and return top_k
    # 第四步:按分数降序排序,返回 top_k
    # Purpose: Return the most relevant documents first
    # 目的:首先返回最相关的文档
    results.sort(key=lambda x: x["score"], reverse=True)
    return results[:top_k]

# ============================================================
# 6. USAGE EXAMPLE / 使用示例
# ============================================================
if __name__ == "__main__":
    # Example: RAG retrieval scenario / 示例:RAG 检索场景
    
    # User question / 用户问题
    query = "What is the capital of France?"
    
    # Document chunks from a knowledge base / 来自知识库的文档块
    documents = [
        "France is a country in Western Europe. Its capital is Paris.",
        "Germany's capital is Berlin. It is the largest city in Germany.",
        "The Eiffel Tower is located in Paris, France.",
        "London is the capital of the United Kingdom."
    ]
    
    # Find most relevant documents / 找到最相关的文档
    top_results = find_most_similar(query, documents, top_k=2)
    
    print(f"Query: {query}")
    print("\nTop Results:")
    for i, result in enumerate(top_results):
        print(f"{i+1}. Score: {result['score']:.4f}")
        print(f"   Document: {result['document']}")
        print()
    
    # Expected output: Documents about France and Paris should rank highest
    # 预期输出:关于法国和巴黎的文档应该排名最高

Azure OpenAI generates Embedding(Azure AI Foundry intgerate)

# ============================================================
# AZURE OPENAI EMBEDDING / Azure OpenAI Embedding
# ============================================================
from openai import AzureOpenAI

# Initialize Azure OpenAI client / 初始化 Azure OpenAI 客户端
# Purpose: Use Azure OpenAI Service instead of OpenAI's direct API
# 目的:使用 Azure OpenAI 服务替代 OpenAI 的直接 API
azure_client = AzureOpenAI(
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    api_version="2024-02-15-preview",  # Azure API version / Azure API 版本
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
)

def get_azure_embedding(text: str, deployment: str = "text-embedding-3-small") -> List[float]:
    """
    Generate embedding using Azure OpenAI Service.
    使用 Azure OpenAI 服务生成 Embedding。
    
    Purpose: Enterprise-grade embedding with Azure's infrastructure.
    目的:使用 Azure 基础设施的企业级 Embedding。
    """
    response = azure_client.embeddings.create(
        model=deployment,  # Deployment name in Azure / Azure 中的部署名称
        input=text,
        encoding_format="float"
    )
    return response.data[0].embedding

Key Takeaways

要点ENCN
Embedding 是将文本转换为数值向量Embedding converts text to numerical vectorsEmbedding 将文本转换为数值向量
语义相似度通过向量距离衡量Semantic similarity is measured by vector distance语义相似度通过向量距离衡量
余弦相似度是最常用的度量Cosine similarity is the most common measure余弦相似度是最常用的度量
查询和文档必须用同一个 Embedding 模型Query and documents must use the SAME embedding model查询和文档必须用同一个 Embedding 模型
OpenAI 限制单请求总 token 300,000OpenAI limits total tokens to 300,000 per requestOpenAI 限制单请求总 token 300,000
上下文 Embedding 比静态 Embedding 更精准Contextual embeddings are more accurate than static上下文 Embedding 比静态 Embedding 更精准
Embedding 是 RAG 检索质量的决定因素Embedding quality determines RAG retrieval qualityEmbedding 质量决定 RAG 检索质量

RAG 2.0

RAG (Retrieval-Augmented Generation) is an AI architecture that retrieves relevant information from external knowledge sources and provides it to an LLM, enabling the model to generate accurate, up-to-date, and context-aware responses.

LLM = Answer from Training
while
RAG = Search First + Then Answer

What is RAG 2.0? There is no official industry standard that defines “RAG 1.0”, “RAG 2.0”, or “RAG 3.0”.

The concept of “RAG 2.0”, known as Agentic RAG, represents a shift from a “simple data retrieval plugin” to a “deeply integrated, agentic system with reasoning capabilities.” The industry has indeed evolved from 1.0 and is now progressing toward 3.0.

Simplest Way to Remember

VersionMeaning
RAG 1.0Search Once
RAG 2.0Search + Reason
RAG 3.0
(coming ? on the way?)
Agent + Search + Tools + Workflow
RAG Foundation: Embedding

Embedding is a fundamental technology in machine learning and natural language processing that transforms discrete or complex objects (such as words, sentences, or images) into numerical vector representations of a fixed dimension

more …

RAG Foundation: RAG Pipeline

A simple RAG pipeline has two phases and five stages

  • Phase 1: Indexing (Offline / 离线阶段)
    Build the searchable knowledge base before users ask questions.
    离线阶段(索引):先把所有文档加载进来,切分成小块,调用 Embedding 模型转成向量,最后存进 FAISS 等向量数据库里。
  • Phase 2: Retrieval & Generation (Online / 在线阶段)
    Execute at query time for each user question.
    在线阶段(检索+生成):用户提问时,先把问题也转成向量,去库里找最相似的 Top-K 个块,把这几个块作为“参考资料”连同问题一起扔给 GPT,让它写出最终回答。

more …

In AI, a chunking strategy is the method used to break down large pieces of information—like long documents, complex prompts, or even audio and video—into smaller, more manageable segments called “chunks”. These chunks are the fundamental units that AI systems, especially Large Language Models (LLMs), work with to understand, process, and retrieve information efficiently.

Common Chunking Strategies

The best strategy depends on the type of data and the specific task. Here are the most common approaches:

StrategyDescriptionBest For
Fixed-Size ChunkingSplits text into chunks of a predetermined size (e.g., a specific number of words, characters, or tokens). Often uses a “sliding window” with overlap to preserve context across boundaries.Simple implementation; works well when document structure is uniform and not critical.
Semantic ChunkingGroups text based on meaning, using algorithms to find natural topic boundaries and keep related ideas together.Maintaining the coherence of ideas within each chunk for better understanding.
Structure-Aware ChunkingRespects the natural format of the document, splitting at points like paragraphs, sentences, or headers.Documents with clear structure (e.g., articles, reports, code) where breaking mid-section would lose meaning.
Recursive ChunkingStarts with large chunks and recursively splits them into smaller ones until they meet a target size, trying to respect natural boundaries like paragraphs or sentences.A balanced approach that aims to create the largest possible meaningful chunks.
Multimodal ChunkingExtends the concept to non-text data, such as segmenting audio by silences, video by scene changes, or identifying objects within images.AI systems that process images, audio, and video, not just text
Chunking Strategy: Recursive Chunking

Recursive Chunking is a hierarchical text splitting strategy that uses a priority list of separators (e.g., ["\n\n", "\n", " ", """]), starting with the highest-level (semantically strongest) separator. If a chunk still exceeds the chunk_size limit after splitting, it recursively applies the next-level separator to that chunk, continuing until all chunks meet the size requirement.

more …

Chunking Strategy: Semantic Chunking

Semantic Chunking is a strategy for splitting documents into smaller pieces (chunks) based on meaning, rather than on fixed character counts or simple separators. It tries to keep sentences or paragraphs that are about the same topic together, and split where the topic changes. Think of it as “a smart editor who knows where one idea ends and the next begins

more …

Chunking Strategy: Parent-Child Retrieval

Parent-Child Retrieval (also known as Small-to-Big Retrieval) is a two-tier hierarchical indexing strategy.

more …


Hybrid Search refers to a search technique that combines multiple search algorithms simultaneously to retrieve the most relevant results. It most commonly merges Lexical (Keyword) Search with Semantic (Vector/Dense) Search.
基于关键词的搜索(词汇搜索)与基于语义的搜索(向量/稠密搜索)

  1. Lexical Search (Sparse Retrieval): Typically powered by algorithms like BM25 or TF-IDF. It relies on exact keyword matching and statistical term frequency. It excels at finding specific proper nouns, IDs, or rare terminology (e.g., “error code 404”).
    词汇搜索(稀疏检索): 通常由 BM25 或 TF-IDF 等算法驱动。它依赖于精确的关键词匹配和统计词频。它在查找特定的专有名词、ID 或罕见术语时表现出色(例如:“错误代码 404”)。
  2. Semantic Search (Dense Retrieval): Powered by embedding models (e.g., Sentence-BERT). It converts text into high-dimensional vectors and retrieves documents based on “meaning” rather than exact words. It excels at understanding synonyms, context, and natural language queries (e.g., “How to fix a broken internet connection”).
    语义搜索(稠密检索): 由嵌入模型(如 Sentence-BERT)驱动。它将文本转换为高维向量,并根据“含义”而非精确词汇来检索文档。它在理解同义词、上下文和自然语言查询(例如:“如何修复断开的网络连接”)方面表现出色。
BM25 (keyword-based search)

BM25 (Best Matching 25) is a keyword-based ranking algorithm used in information retrieval to score and rank documents based on their relevance to a search query. It’s called “Best Matching 25” because it was the 25th variant in a series of scoring functions proposed by its creators. BM25 is the default ranking algorithm in Elasticsearch and most production search engines

more …

RRF

RRF stands for Reciprocal Rank Fusion. It is an algorithm that merges multiple ranked result lists from different search systems into a single unified ranking.
全称是 Reciprocal Rank Fusion(倒数排名融合)。它是一种将来自不同检索系统的多个排名结果列表合并成一个统一排名的算法.

more …

Vector Database Selection

Compare normal DB, such as SQL DB, MySQL, PostgreSQL, They fundamental difference is what they search for and how they find it. A traditional SQL database (like MySQL, PostgreSQL without pgvector) is built for exact matching and structured queries. It answers questions like: “Find the customer with ID = 12345” or “Give me all orders over $100.” A Vector Database is built for semantic similarity and unstructured data. It answers questions like: “Find all documents that talk about the same topic as this paragraph” or “Show me products that look visually similar to this image.”

Normal DB vs Vector DB

要点ENCN
核心:精确匹配 vs. 语义相似度Core: Exact matching vs. Semantic similarity核心:精确匹配 vs. 语义相似度
SQL存结构化数据(数字/字符串),Vector存浮点数数组(含义)SQL stores structured data (numbers/strings); Vector stores float arrays (meaning)SQL存结构化数据,Vector存浮点数数组(含义)
SQL查询用WHERE精确条件;Vector查询用ORDER BY距离SQL queries use WHERE exact conditions; Vector queries use ORDER BY distanceSQL查询用WHERE精确条件;Vector查询用ORDER BY距离
SQL用B-Tree/哈希(精确查找);Vector用HNSW/IVF(近似查找)SQL uses B-Tree/Hash (exact lookup); Vector uses HNSW/IVF (approximate)SQL用B-Tree/哈希(精确);Vector用HNSW/IVF(近似)
SQL结果是二元的(匹配/不匹配);Vector结果是排序的(相似度分数)SQL results are binary (match/no match); Vector results are ranked (similarity scores)SQL结果是二元的;Vector结果是排序的
SQL适合事务、财务报表;Vector适合RAG、推荐、AISQL suits transactions, ledgers; Vector suits RAG, recommendations, AISQL适合事务、报表;Vector适合RAG、推荐、AI
专用向量库不能做JOIN和ACID;但pgvector可以在PostgreSQL中兼得Dedicated vector DBs can’t do JOINs/ACID; pgvector lets you have both in PostgreSQL专用向量库不能做JOIN和ACID;pgvector可以让两者兼得
在实际RAG中,两者是互补的,不是替代关系In real-world RAG, they are complementary, not replacements在实际RAG中,两者是互补的,不是替代关系

Vector database selection is the process of choosing the right vector database technology for your AI application from dozens of available options — Milvus, Qdrant, Weaviate, Pinecone, pgvector, Chroma, and more.

Mainstream Vector Database Landscape

CategoryExamplesCN
Fully Managed (PaaS)Pinecone, Zilliz Cloud, Weaviate Cloud全托管云服务
Self-Hosted Open SourceQdrant, Milvus, Weaviate, Chroma自托管开源
Database Extensionspgvector, MongoDB Vector Search, Elasticsearch数据库扩展
Cloud Provider ServicesAzure AI Search, AWS S3 Vectors, Tencent Cloud VDB云厂商服务
Embedded/SpecializedSQLite (vector), LanceDB嵌入式/专用

Detailed Comparison

DatabaseAvg Query TimeCost (1M @ 1536-dim)Best ForCN 最适合
Milvus/Zilliz50.7ms$115/moFastest queries + good flexibility最快查询+灵活性好
Weaviate51.7ms$160/moNative datetime/geo + hybrid search原生时间/地理+混合检索
Qdrant73.1ms$103/moBest balance (speed + flexibility + cost)最佳平衡(速度+灵活性+成本)
Pinecone106.3ms$30/moCheapest (⚠️ poor schema flexibility)最便宜(⚠️ Schema灵活性差)
Chroma275.4ms$139/moEasiest setup + prototyping最简单设置+原型开发

7 Types of Data Stored in VectorDB in AI Projects

类型ENCN更新频率过滤器主要用途
RAG 文档块RAG Document ChunksRAG 文档块source, page问答
用户记忆 (Mem0)User Memory (Mem0)用户记忆 (Mem0)user_id个性化
工具 SchemaTool Schemas工具 Schematool_category工具选择
Agent 轨迹Agent TrajectoriesAgent 轨迹user_id, outcome经验复用
黄金数据集Golden Dataset黄金数据集category评估
语义缓存Semantic Cache语义缓存降本提速
代码索引Code Index代码索引language, path代码生成

Reranker is a sophisticated machine learning model designed to refine and reorder a list of candidate items—such as search results, document passages—to maximize their relevance to a specific query or context.

Reranker(重排序器)是一种复杂的机器学习模型,旨在优化并重新排序候选项目列表(如搜索结果、文档片段),以最大程度提高它们与特定查询或上下文的相关性。

Reranker

Reranker实战


Advanced RAG (Advanced Retrieval-Augmented Generation) is an evolutionary upgrade over the basic “Naive RAG” pipeline. It adds a suite of optimization techniques at every stage of the RAG workflow — pre-retrieval, retrieval, post-retrieval, and evaluation — to systematically improve retrieval precision, recall, and generation quality.

Advanced RAG

Query Rewrite

Multi Query Retrieval

Context Compression