Embedding Models
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/embeddings/embeddings.py
- libs/partners/openai/langchain_openai/embeddings/base.py
- libs/partners/huggingface/langchain_huggingface/embeddings/huggingface.py
- libs/langchain/langchain/embeddings/cache.py
- libs/langchain/langchain/chains/hyde/base.py
- libs/langchain/langchain/embeddings/init.py
- libs/cli/langchain_cli/integration_template/integration_template/embeddings.py
Embedding models are a core component of the LangChain framework, responsible for creating numerical vector representations of textual data. These models act as wrappers around various embedding model providers and APIs, offering a standardized interface for converting documents and queries into dense vectors. These vectors are fundamental for semantic search, retrieval-augmented generation (RAG), and other applications that rely on understanding the semantic similarity between pieces of text.
The system is designed to be modular, with a base Embeddings class that defines the core interface, and numerous specific implementations for different services like OpenAI, HuggingFace, and more. This allows developers to easily swap out embedding models without changing the rest of their application logic. LangChain also provides utility wrappers, such as CacheBackedEmbeddings, to enhance functionality and efficiency.
Sources: libs/core/langchain_core/embeddings/embeddings.py, libs/langchain/langchain/embeddings/init.py, README.md:29-32
Core Architecture
The foundation of the embedding system is the Embeddings abstract base class. All specific embedding model implementations inherit from this class.
Embeddings Base Class
The Embeddings class, defined in langchain_core, establishes the contract for all embedding model wrappers. It ensures a consistent interface across the ecosystem.
The class defines two primary abstract methods for generating embeddings:
embed_documents(self, texts: List[str]) -> List[List[float]]: Takes a list of texts and returns a list of embeddings (each embedding is a list of floats). This is used for processing batches of documents, typically for indexing in a vector store.embed_query(self, text: str) -> List[float]: Takes a single text (a query) and returns a single embedding. This is used for creating a vector representation of a user's query to perform a similarity search.
It also provides asynchronous versions of these methods, aembed_documents and aembed_query, for use in async applications.
Sources: libs/core/langchain_core/embeddings/embeddings.py:14-46
This diagram shows the abstract Embeddings class and its core methods.
Implementations
LangChain offers a wide array of integrations with various embedding model providers. The langchain/embeddings/__init__.py file lists dozens of available embedding classes, which are dynamically imported from langchain_community. Below are details on two common implementations.
Sources: libs/langchain/langchain/embeddings/init.py:100-153
OpenAI Embeddings
The OpenAIEmbeddings class provides a wrapper for OpenAI's embedding models. It handles API requests, batching, and retries.
This diagram illustrates the inheritance from the base Embeddings class.
Key Parameters
| Parameter | Type | Description |
|---|---|---|
model | str | The name of the OpenAI model to use (e.g., "text-embedding-3-small"). |
dimensions | int | The desired dimension of the output embeddings. |
api_key | SecretStr | The OpenAI API key. |
chunk_size | int | The maximum number of texts to embed in a single API call. Defaults to 1000. |
max_retries | int | The maximum number of retries for API requests. |
Sources: libs/partners/openai/langchain_openai/embeddings/base.py:100-145
HuggingFace Embeddings
The HuggingFaceEmbeddings class allows for the use of open-source models from the Hugging Face Hub, typically running locally. It relies on the sentence-transformers library.
This diagram shows its relationship with the base class and its key dependency.
Key Parameters
| Parameter | Type | Description |
|---|---|---|
model_name | str | The path to the model on the Hugging Face Hub or a local directory. Defaults to "sentence-transformers/all-mpnet-base-v2". |
model_kwargs | Dict | Keyword arguments to pass to the SentenceTransformer model constructor (e.g., {'device': 'cuda'}). |
encode_kwargs | Dict | Keyword arguments to pass to the encode method (e.g., {'batch_size': 32}). |
cache_folder | Optional[str] | Path to a folder to cache the model. |
Sources: libs/partners/huggingface/langchain_huggingface/embeddings/huggingface.py:53-65
Advanced Wrappers and Chains
LangChain provides higher-level abstractions that build upon the base embedding models to add features like caching or more complex embedding strategies.
CacheBackedEmbeddings
This class acts as a wrapper around an underlying embedding model to cache results and avoid redundant computations and API calls. It is particularly useful for reducing costs and latency when processing the same documents multiple times.
The caching logic follows these steps:
- Receive a request to embed texts.
- For each text, generate a unique key (hash of the text and embedder identifier).
- Check the
document_embedding_store(the cache) for this key. - If a cached embedding exists (a cache hit), retrieve it.
- If not (a cache miss), call the
underlying_embedderto generate the embedding. - Store the newly generated embedding in the cache.
- Return the final list of embeddings.
This flowchart illustrates the caching process for embed_documents.
Components
| Component | Type | Description |
|---|---|---|
underlying_embedder | Embeddings | The actual embedding model (e.g., OpenAIEmbeddings) to use for generating embeddings on a cache miss. |
document_embedding_store | BaseStore[str, List[float]] | The key-value store used for caching. It maps a unique key (hash) to the corresponding embedding vector. |
Sources: libs/langchain/langchain/embeddings/cache.py:28-33
HypotheticalDocumentEmbedder (HyDE)
HyDE is a specialized chain that aims to improve retrieval accuracy by embedding a hypothetical document instead of the raw user query. It uses a Language Model (LLM) to generate a plausible document that could answer the user's query, and then embeds this generated document. The resulting vector is often more semantically aligned with the actual documents in the vector store.
The process for embed_query is as follows:
- The user's query (
text) is passed to thellm_chain. - The
llm_chaininvokes an LLM to generate a hypothetical document based on the query. - The generated document is then passed to the
base_embeddingsmodel. - The
base_embeddingsmodel creates a vector embedding from the hypothetical document. - This vector is returned as the final query embedding.
This diagram shows the data flow within the HyDE chain.
HyDE inherits from both Chain and Embeddings, allowing it to be used as a drop-in replacement for a standard embedding model in a retrieval chain.