A retriever obtains relevant documents from a vector store for a query. In LangChain.js, vectorStore.asRetriever() turns indexed content into a composable component for query pipelines. section 6.2.3
A typical retrieval pipeline passes the query through a retriever, formats returned Document instances as text, combines that context with the original question, and sends both to a prompt and language model. RunnableSequence coordinates the steps, while RunnablePassthrough preserves the question. section 6.2.3
Answering a question with retrieved context
Create a retriever with vectorStore.asRetriever(), pipe it through formatDocumentsAsString, and invoke the chain with question: "What is artificial intelligence?". The chain retrieves context, formats the documents, generates an answer, and parses the result. section 6.2.3
Retrievers can also become agent tools through createRetrieverTool. A name and description help the agent decide when to call the retriever, but tool descriptions and intermediate data add to context length and can increase delays across the agent pipeline. section 6.4.2
Listing 6.7 Calling a retriever with a prompt message
import { StringOutputParser }
from "@langchain/core/output_parsers"; #1
import { formatDocumentsAsString } from "langchain/util/document";
import {
RunnablePassthrough,
RunnableSequence,
} from "@langchain/core/runnables";
const retriever = vectorStore.asRetriever(); #2
const chain = RunnableSequence.from([ #3
{
context: retriever.pipe(formatDocumentsAsString), #4
question: new RunnablePassthrough(),
},
prompt,
module,
new StringOutputParser(),
]);
const answer = await chain.invoke({
question: "What is artificial intelligence?" });
/*
' Artificial Intelligence (AI) is basically intelligence shown by machines...
*/
Inspect the runnable JavaScript pattern for connecting a retriever to document formatting, a prompt, a language model, and an output parser. section 6.2.3


