Vector Stores
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/vectorstores/base.py
- libs/partners/chroma/langchain_chroma/vectorstores.py
- libs/core/langchain_core/vectorstores/in_memory.py
- libs/langchain/langchain/chains/qa_with_sources/vector_db.py
- libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py
- libs/core/langchain_core/indexing/api.py
- README.md
Vector Stores are a fundamental component in LangChain for building applications that combine Large Language Models (LLMs) with external data. They provide an interface for storing, managing, and retrieving unstructured data as numerical vectors (embeddings). This capability is central to patterns like Retrieval Augmented Generation (RAG), where relevant data is fetched from a vector store and provided to an LLM as context to answer questions or generate content.
LangChain provides a standard, abstract interface for vector stores, allowing for interoperability with numerous third-party integrations like Chroma, FAISS, Qdrant, and more. This modular design enables developers to easily swap out vector database backends without changing their application logic.
Sources: README.md, libs/core/langchain_core/vectorstores/base.py
Core Abstraction: The VectorStore Class
The core of the vector store system is the VectorStore abstract base class. It defines a standard contract that all vector store implementations must adhere to. This ensures a consistent API for adding, deleting, and searching for documents across different underlying databases.
Sources: libs/core/langchain_core/vectorstores/base.py
Class Diagram
This diagram shows the abstract VectorStore class and some of its concrete implementations.
Key Methods
The VectorStore class defines several key methods for interacting with the data.
| Method | Description |
|---|---|
add_documents() / aadd_documents() | Adds a list of Document objects to the vector store. It handles embedding the documents and storing them. |
delete() / adelete() | Deletes documents from the vector store based on their IDs. |
similarity_search() / asimilarity_search() | Finds the most similar documents to a given query string. |
similarity_search_with_score() | Similar to similarity_search, but also returns the similarity score (distance) for each document. |
max_marginal_relevance_search() | Performs a search that optimizes for a balance between similarity to the query and diversity among the selected documents. |
as_retriever() | Returns a VectorStoreRetriever instance, which is a Runnable interface for use in LCEL chains. |
Sources: libs/core/langchain_core/vectorstores/base.py:48-250
Core Operations
Adding Documents
The process of adding documents to a vector store typically involves taking a list of Document objects, using an Embeddings implementation to convert their content into vectors, and then storing these vectors along with their metadata and IDs in the database.
This flowchart illustrates the add_documents process.
Searching
Searching is the primary way to retrieve data from a vector store. The most common method is similarity_search.
This sequence diagram shows the flow of a similarity search operation.
Maximal Marginal Relevance (MMR) Search
MMR is a search algorithm that aims to reduce redundancy in the search results while maintaining relevance. It first fetches a larger set of documents (fetch_k) and then selects a smaller subset (k) that is diverse. The lambda_mult parameter controls the trade-off between similarity and diversity.
lambda_mult= 1: Maximum similarity, minimum diversity (equivalent tosimilarity_search).lambda_mult= 0: Minimum similarity, maximum diversity.
Sources: libs/core/langchain_core/vectorstores/base.py:133-157, libs/partners/chroma/langchain_chroma/vectorstores.py:821-863
Indexing API
LangChain provides a high-level index function to streamline the process of populating and maintaining a vector store. This API handles document hashing, deduplication, and cleanup of stale records. It uses a RecordManager to track which documents have been indexed and when.
Sources: libs/core/langchain_core/indexing/api.py
Indexing Flow
The index function orchestrates the interaction between a document source, a record manager, and the vector store.
Document Hashing
To track documents, the index function generates a unique ID for each document by hashing its content and metadata. This allows for deterministic identification and deduplication.
The key_encoder parameter controls the hashing algorithm.
sha1(default): Fast but not collision-resistant. A warning is issued upon use.sha256,sha512,blake2b: More secure alternatives.Callable[[Document], str]: A custom function can be provided for full control over ID generation.
Sources: libs/core/langchain_core/indexing/api.py:126-170
Cleanup Modes
The cleanup parameter in the index function determines how stale documents are handled.
| Mode | Description |
|---|---|
None | No documents are deleted. |
incremental | Deletes documents associated with source IDs seen during the current indexing run that were not updated. Requires source_id_key. |
full | After indexing, deletes all documents from the vector store that were not part of the current indexing run. |
scoped_full | A combination of full and incremental. After indexing, it deletes all documents associated with source IDs seen during the run that were not updated. Requires source_id_key. |
Sources: libs/core/langchain_core/indexing/api.py:228-268
Usage in Chains and Agents
Vector stores are rarely used in isolation. They are key components of more complex systems like chains and agents.
QA with Sources Chains
The VectorDBQAWithSourcesChain is a specialized chain that uses a vector store to answer questions and cite its sources. It retrieves relevant documents from the VectorStore and passes them to an LLM to synthesize an answer.
# libs/langchain/langchain/chains/qa_with_sources/vector_db.py
class VectorDBQAWithSourcesChain(BaseQAWithSourcesChain):
"""Question-answering with sources over a vector database."""
vectorstore: VectorStore = Field(exclude=True)
"""Vector Database to connect to."""
k: int = 4
"""Number of results to return from store"""
# ...
def _get_docs(
self,
inputs: dict[str, Any],
*,
run_manager: CallbackManagerForChainRun,
) -> list[Document]:
question = inputs[self.question_key]
docs = self.vectorstore.similarity_search(
question,
k=self.k,
**self.search_kwargs,
)
return self._reduce_tokens_below_limit(docs)
Sources: libs/langchain/langchain/chains/qa_with_sources/vector_db.py:16-50
Agent Toolkits
The VectorStoreToolkit and VectorStoreRouterToolkit expose vector stores as tools that an agent can use. This allows an agent to decide dynamically when to query a vector store to get information needed to complete a task. The VectorStoreInfo class provides the agent with the necessary context about the vector store's name and the type of data it contains.
Sources: libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py:9-79