DS DevShelfHub Projects · AI tools
Tutorials / LangChain / Reference / Methods / .as_retriever()
Method Vector stores

.as_retriever(): Reference Guide

By DevShelfHub

Convert vector store to retriever for use in chains.

What is .as_retriever()?

.as_retriever() is the bridge between a vector store object (FAISS, Chroma, Pinecone, Weaviate, and others) and LangChain's Runnable retriever interface. Without it, a vector store only exposes raw methods like .similarity_search() — useful for one-off queries but incompatible with the | pipe operator and LCEL chain composition.

Calling .as_retriever() wraps the vector store in a VectorStoreRetriever that implements BaseRetriever and the full Runnable protocol. This means you can invoke it, batch it, pass it to astream(), compose it into LCEL chains, and register it as a tool in agent executors — all without any extra adapter code.

Three search types are supported: similarity (default, ranks by cosine or dot-product distance), mmr (Maximum Marginal Relevance — trades some relevance for diversity among results, useful when top-k results are near-duplicates of each other), and similarity_score_threshold (returns only documents above a minimum relevance score, filtering out noise at the cost of sometimes returning zero results). Tune the result count with search_kwargs={"k": N}. For MMR, set fetch_k to 3–5× your k value to give the diversity algorithm a large enough candidate pool. Most vector stores also accept a filter key inside search_kwargs for scoping retrieval by metadata field — exact syntax varies per provider.

Use Cases

  • • RAG chain integration
  • • Question-answering
  • • Document retrieval chains
  • • Similarity search in agents
  • • Semantic search backends
  • • Chat with docs

Key Features

  • ✓ Vector-store conversion
  • ✓ Search type selection
  • ✓ Parameter customization
  • ✓ Works in chains
  • ✓ Filter support
  • ✓ Score output

When NOT to Use

For standalone similarity search—use similarity_search(). When you need raw scores without threshold filtering.

Notes

k defaults to 4 — increase for complex multi-part questions

The default search_kwargs={"k": 4} works for single-fact lookups but underperforms on multi-part questions. Increase to 6–10 for answers that require synthesising multiple chunks. Very large k values dilute the context window and inflate token cost.

MMR requires fetch_k substantially larger than k

If you set search_type="mmr" without increasing fetch_k, the diversity algorithm has too small a pool to reshuffle and produces results nearly identical to plain similarity. Set fetch_k to at least 3× k, e.g., k=4 with fetch_k=20.

Score threshold can return zero documents

similarity_score_threshold is strict: if nothing in the index crosses the threshold, the retriever returns an empty list — no error, no fallback. Always check the returned list length and handle the empty case explicitly in production chains.

Retriever reflects live index state

.as_retriever() is a thin wrapper, not a snapshot. Documents added to the underlying vector store after retriever creation are immediately searchable. This is useful for incremental indexing pipelines but can cause non-deterministic results in tests if the index is shared.

Method Signature

python
retriever = vector_store.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 4},
)

Parameters

Parameter Type Required Purpose
search_type str No 'similarity', 'mmr', or 'similarity_score_threshold'
search_kwargs dict No Dict passed to the underlying search method

Return Value

Type:

VectorStoreRetriever

Description:

Runnable retriever

Example Output:

retriever = vector_store.as_retriever()

Code Examples

MMR retriever with diversity re-ranking

python
retriever = vector_store.as_retriever(
    search_type='mmr',
    search_kwargs={'k': 4, 'fetch_k': 20}
)
docs = retriever.invoke("What is RAG?")

Score threshold with empty-result guard

python
from langchain_community.vectorstores import Chroma

retriever = store.as_retriever(
    search_type='similarity_score_threshold',
    search_kwargs={'score_threshold': 0.75, 'k': 6}
)
docs = retriever.invoke("explain embeddings")
if not docs:
    print("No documents met the relevance threshold")

Full RAG chain wired with LCEL

python
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

prompt = ChatPromptTemplate.from_template(
    "Answer using this context:\n{context}\n\nQuestion: {question}"
)
chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | ChatOpenAI(model="gpt-4o")
    | StrOutputParser()
)
print(chain.invoke("What is LangChain?"))

Common Mistakes

❌ Use vector_store directly in chains

✅ Use vector_store.as_retriever() for chain compatibility

Browse the full LangChain API reference index to explore more classes, methods, and decorators, or start with the LangChain introduction tutorial for end-to-end context on building with .as_retriever() and the wider framework.

.as_retriever() FAQ

What does .as_retriever() do in LangChain?

Convert vector store to retriever for use in chains. .as_retriever() is the bridge between a vector store object (FAISS, Chroma, Pinecone, Weaviate, and others) and LangChain's Runnable retriever interface. Without it, a vector store only exposes raw methods like .similarity_search() — useful for one-off queries but incompatible with the | pipe operator and LCEL chain composition. Calling .as_retriever() wraps the vector store in a VectorStoreRetriever that implements BaseRetriever and the full Runnable protocol. This means yo…

Which LangChain classes support .as_retriever()?

.as_retriever() is available on Vector stores. Pin your installed LangChain version and verify the method exists in that release before deploying.

When should I use .as_retriever()?

Use .as_retriever() when your LangChain chains, agents, or pipelines need the behavior described in this guide.

What does .as_retriever() return?

.as_retriever() returns a VectorStoreRetriever. Runnable retriever

Does .as_retriever() have an async equivalent?

.as_retriever() does not have a documented async variant. Avoid .as_retriever() For standalone similarity search—use similarity_search(). When you need raw scores without threshold filtering.

Where can I explore more LangChain API reference pages?

Open the LangChain API reference index on DevShelfHub to browse classes, methods, and decorators, each with runnable examples, parameters, common mistakes, and cross-links.