Skip to main content

02 - Implementing RAG with TypeScript and LangChain.js

Build a RAG pipeline with LangChain.js 1.x: loader, splitter, index, a chain with history and a createRetrievalChain trap, with listings that were run.

What do you think about this article?

At a Glance

Build a RAG pipeline with LangChain.js 1.x: loader, splitter, index, a chain with history and a createRetrievalChain trap, with listings that were run.

You understood what RAG does and now you want to write it. You look for a LangChain.js tutorial, copy it, and the import fails: langchain/chains/retrieval no longer exists. With version 1 of LangChain the "classic" chains were moved into a separate package, and most of the tutorials in circulation describe the previous layout. This article builds the RAG pipeline with the packages that exist today, and where a piece requires a key, a service or a server, it says so instead of pretending to have run it.

To show real outputs without calling any model, the listings that were run use two declared stand-ins: a fake embedding (it counts words) and a scripted fake model (it returns the prompt it received, or a rewrite fixed in the code). Everything else is real LangChain.js: the loaders, the splitter, the in-memory index, the chains. You need Node.js 24 (it runs .ts files directly) and the concept of RAG explained in What is RAG.

Which packages to install, and why there are five

From version 1 the langchain package concentrates on agents, and the historical code lives in @langchain/classic: the official migration guide says so, and the export list of the installed package confirms it (langchain 1.6.5 has neither chains/retrieval nor chains/combine_documents, @langchain/classic 1.0.61 does). The versions are the ones I installed on 2026-11-12 in a temporary folder.

Installation (run in a temporary folder)
npm init -y
npm pkg set type=module
npm install @langchain/core @langchain/textsplitters @langchain/classic langchain
# only for the pieces with external services (listing 4, not run):
npm install @langchain/openai @langchain/community @langchain/pinecone @pinecone-database/pinecone chromadb

npm pkg set type=module is the step people forget: the LangChain packages are ES modules, and without "type": "module" Node treats your file as CommonJS and answers with Cannot use import statement outside a module. The role of the packages is this: @langchain/core defines Document, the prompts and the interfaces; @langchain/textsplitters contains the splitters; @langchain/classic the RAG chains, the file loaders and the in-memory index; the packages named after a service contain the bindings to that service.

Document loader: from file to Document

The loader reads a source and returns Document objects, each with the text in pageContent and the origin information in metadata. In the listing, the DirectoryLoader receives an extension-to-loader map: for each .txt file in the docs folder it builds a TextLoader. A file with an extension that is not foreseen, with no matching entry, makes the loading fail: the map is also the list of accepted formats. Loaders for PDFs (@langchain/community/document_loaders/fs/pdf) and web pages (.../web/cheerio) exist in the community package, but they require other dependencies (pdf-parse, cheerio) and I did not run them here.

Listing 1: loading and splitting (run with Node 24 on three small text files)
import { DirectoryLoader } from "@langchain/classic/document_loaders/fs/directory";
import { TextLoader } from "@langchain/classic/document_loaders/fs/text";
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
import { basename } from "node:path";

const loader = new DirectoryLoader("./docs", {
  ".txt": (path: string) => new TextLoader(path),
});
const docs = (await loader.load()).sort((a, b) =>
  a.metadata.source.localeCompare(b.metadata.source));
console.log("documents:", docs.length);
console.log("metadata of the first:", JSON.stringify({ source: basename(docs[0].metadata.source) }));

const splitter = new RecursiveCharacterTextSplitter({
  chunkSize: 80,
  chunkOverlap: 20,
});
const chunks = await splitter.splitDocuments(docs);
console.log("chunks:", chunks.length);
for (const c of chunks) {
  console.log(`- ${basename(c.metadata.source)} lines ${c.metadata.loc.lines.from}-${c.metadata.loc.lines.to} (${c.pageContent.length}): ${JSON.stringify(c.pageContent)}`);
}

// Output:
// documents: 3
// metadata of the first: {"source":"chunking.txt"}
// chunks: 8
// - chunking.txt lines 1-1 (73): "Chunking splits documents into fragments. A chunk that is too large mixes"
// - chunking.txt lines 1-1 (36): "is too large mixes different topics."
// - chunking.txt lines 2-2 (68): "A chunk that is too small loses the context needed to understand it."
// - chunking.txt lines 4-4 (74): "Overlap repeats a bit of text between one chunk and the next, so as not to"
// - chunking.txt lines 4-4 (41): "next, so as not to split an idea in half."
// - invoices.txt lines 1-1 (75): "Invoices can be downloaded as PDF from the Billing section of your profile."
// - password.txt lines 1-1 (79): "To reset your password open Settings, choose Security and press Reset password."
// - password.txt lines 2-2 (50): "The link received by email expires after one hour."

The three files give eight chunks. The splitter first tried to cut on double newlines, then on single newlines, then on spaces, and only if a piece still exceeds chunkSize does it go down to the next separator: that is why short paragraphs stay whole (invoices.txt is a single chunk) and long ones are split on spaces. Look at the first two chunks: "is too large mixes" appears in both. It is the 20-character overlap, and it is there only where a cut inside a paragraph was necessary. In the metadata each chunk carries the origin file and the lines (loc.lines), that is the provenance for citations. The full path, in the real metadata, depends on your machine: in the listing I print its file name.

The numbers 80 and 20 are deliberately small to make the cut visible; RecursiveCharacterTextSplitter measures in characters unless you pass a lengthFunction, so in production you start from values of hundreds of characters and tune by looking at the retrieval results. The table of "recommended sizes by document type" that circulates in tutorials has no source: the right value is the one you measure on your corpus.

Embeddings: the interface you must respect

For LangChain an embedding model is a class that extends Embeddings and implements two methods: embedQuery for the question and embedDocuments for the chunks. The rest of the pipeline talks only to this interface, and that is why you can change model by touching one line. Listing 2 writes a fake version of one: the vocabulary is the set of words of the corpus, and the vector of a text counts how many times each one appears. It does not understand synonyms, and that is fine: it is there to run the rest without a key.

Listing 2: a fake embedding that respects the interface (run)
import { Document } from "@langchain/core/documents";
import { Embeddings } from "@langchain/core/embeddings";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
import { RunnableLambda, RunnablePassthrough, RunnableSequence } from "@langchain/core/runnables";
import { AIMessage, HumanMessage } from "@langchain/core/messages";
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { createStuffDocumentsChain } from "@langchain/classic/chains/combine_documents";
import { createHistoryAwareRetriever } from "@langchain/classic/chains/history_aware_retriever";

// 1. Fake embedding: counts the vocabulary words. It knows no synonyms.
const STOP = new Set(["how", "do", "i", "my", "the", "a", "an", "to", "your", "of", "from", "by", "and", "in", "after", "until", "long", "it"]);
const words = (t: string) =>
  t.toLowerCase().replace(/[^a-z0-9 ]/g, " ").split(/\s+/).filter(w => w && !STOP.has(w));

class BagOfWordsEmbeddings extends Embeddings {
  private vocab: string[];
  constructor(corpus: string[]) {
    super({});
    this.vocab = [...new Set(corpus.flatMap(words))].sort();
  }
  async embedQuery(text: string): Promise<number[]> {
    const w = words(text);
    return this.vocab.map(v => w.filter(x => x === v).length);
  }
  async embedDocuments(texts: string[]): Promise<number[][]> {
    return Promise.all(texts.map(t => this.embedQuery(t)));
  }
}

const chunks = [
  new Document({ pageContent: "To reset your password open Settings, choose Security and press Reset password.", metadata: { source: "password.txt" } }),
  new Document({ pageContent: "The link received by email expires after one hour.", metadata: { source: "password.txt" } }),
  new Document({ pageContent: "Invoices can be downloaded as PDF from the Billing section of your profile.", metadata: { source: "invoices.txt" } }),
];

The constructor fixes the vocabulary once, and this is the most important point: documents and questions must be transformed with the same vocabulary, otherwise the positions of the vectors do not match. With a real model the same principle holds, where the "vocabulary" is the model and its dimensions. The STOP filter removes empty words such as "the" and "how", because a count would reward them for no reason.

Vector store: the in-memory index and the search

The MemoryVectorStore keeps the vectors in an array and computes the cosine similarity at every search. You find it in @langchain/classic/vectorstores/memory, and it is the right choice for learning and for corpora of a few hundred chunks; it does not survive a restart of the process, so it is not a production index. fromDocuments computes the embeddings of all the chunks and saves them; similaritySearchWithScore returns document-score pairs.

Listing 3: in-memory index and search with score (run; the code continues in listing 5)
// 2. In-memory index
const embeddings = new BagOfWordsEmbeddings(chunks.map(c => c.pageContent));
const store = await MemoryVectorStore.fromDocuments(chunks, embeddings);
const hits = await store.similaritySearchWithScore("How do I reset my password?", 2);
for (const [d, s] of hits) console.log(`score ${s.toFixed(3)} ${d.metadata.source}`);

// Output:
// score 0.784 password.txt
// score 0.000 password.txt

The question about the password finds the right chunk with a score of 0.784; the second result, the one about the link that expires, has a score of 0: it shares no word. With k = 2 the library returns two results anyway, even when the second has nothing to do with the question, and that is the reason why in production you look at the score and decide a threshold below which you answer "I don't know" instead of passing irrelevant material to the model. The threshold must be measured on your index with your embedding model, not copied.

For an index that survives restarts you only change how the store is built. Listing 4 shows Chroma (a server to start separately) and Pinecone (a managed service with a key): they are schemas to adapt, not run, but I passed them to the TypeScript compiler with the packages installed, so names and signatures match the versions listed.

Listing 4: schema with external services (not run, compiled with tsc without errors)
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { Chroma } from "@langchain/community/vectorstores/chroma";
import { PineconeStore } from "@langchain/pinecone";
import { Pinecone } from "@pinecone-database/pinecone";
import type { Document } from "@langchain/core/documents";

export const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small" });
export const chatModel = new ChatOpenAI({
  model: process.env.CHAT_MODEL ?? "",   // you choose the model name
  temperature: 0.2,
});

export async function chromaStore(chunks: Document[]) {
  return Chroma.fromDocuments(chunks, embeddings, {
    collectionName: "rag-demo",
    url: "http://localhost:8000",
  });
}

export async function pineconeStore(chunks: Document[]) {
  const index = new Pinecone().Index("rag-demo");
  return PineconeStore.fromDocuments(chunks, embeddings, { pineconeIndex: index });
}

The constructor of OpenAIEmbeddings accepts model (the OpenAI documentation gives 1536 default dimensions for text-embedding-3-small) and reads the key from the environment variable OPENAI_API_KEY; new Pinecone() without arguments reads its own. I left the name of the chat model in an environment variable: it changes more often than an article gets updated, and it must be read from the catalogue of the provider you choose. The risk to keep in mind with any external store is the same as in the rest of the series: if you change embedding model, you have to reindex everything.

The chain: retrieval, prompt and model

Here the pieces come together. createStuffDocumentsChain takes a prompt with the placeholders {context} and {input} and "stuffs" the documents into the context; a retriever with conversation memory completes the picture. The prompt has a place reserved for the history (MessagesPlaceholder) and the instruction to answer only with the context. As the model I use the scripted stand-in: it returns the complete prompt it would have received, so the output shows exactly what your model would read.

Listing 5: chain with history and fake model (run; identical output in two runs)
// 3. Fake model: returns the prompt it received
const echoModel = new RunnableLambda({ func: (p: { toString(): string }) => p.toString() });
const prompt = ChatPromptTemplate.fromMessages([
  ["system", "Answer ONLY with the context. If it is missing, say so.\n\nContext:\n{context}"],
  new MessagesPlaceholder("chat_history"),
  ["human", "{input}"],
]);
const combineDocsChain = await createStuffDocumentsChain({ llm: echoModel, prompt });

// 4. Retrieval chain with history. The question rewrite is scripted.
const rewrite = new RunnableLambda({
  func: (p: { toString(): string }) => {
    console.log("rewrite called, last lines:", p.toString().split("\n").slice(-2).join(" | "));
    return "How long until the reset link expires?";
  },
});
const rephrasePrompt = ChatPromptTemplate.fromMessages([
  ["system", "Rephrase the last question so that it can be understood without the history."],
  new MessagesPlaceholder("chat_history"),
  ["human", "{input}"],
]);
const retriever = await createHistoryAwareRetriever({
  llm: rewrite,
  retriever: store.asRetriever({ k: 1 }),
  rephrasePrompt,
});
const chain = RunnableSequence.from([
  RunnablePassthrough.assign({ context: retriever }),
  RunnablePassthrough.assign({ answer: combineDocsChain }),
]);

const r1 = await chain.invoke({ input: "How do I reset my password?", chat_history: [] });
console.log("--- without history, sources:", r1.context.map((d: Document) => d.pageContent.slice(0, 30)));

const history = [new HumanMessage("How do I reset my password?"), new AIMessage("Open Settings.")];
const r2 = await chain.invoke({ input: "And how long until it expires?", chat_history: history });
console.log("--- with history, sources:", r2.context.map((d: Document) => d.pageContent.slice(0, 30)));
console.log(r2.answer);

// Output:
// --- without history, sources: [ 'To reset your password open Se' ]
// rewrite called, last lines: AI: Open Settings. | Human: And how long until it expires?
// --- with history, sources: [ 'The link received by email exp' ]
// System: Answer ONLY with the context. If it is missing, say so.
//
// Context:
// The link received by email expires after one hour.
// Human: How do I reset my password?
// AI: Open Settings.
// Human: And how long until it expires?

The first question has an empty history: createHistoryAwareRetriever passes the question directly to the retriever, without consulting the model (the output does not show "rewrite called"). The second, "And how long until it expires?", does not say by itself what it refers to: the rewrite model turns it into a standalone question, and only then does the search happen. In the listing the rewrite is a fixed script ("How long until the reset link expires?"), so it demonstrates the path, not the quality of a real model: the output shows that the retrieved chunk becomes the one about the link. In a real application the rewrite costs one more model call for every question after the first.

The createRetrievalChain trap

Tutorials pass the retriever with history to createRetrievalChain. With @langchain/classic 1.0.61 I did not find an error, but a silently wrong behaviour: in the function's code the "is it a retriever?" check is typeof x.invoke === "function", which holds for any runnable, so the retriever with history gets wrapped in a step that extracts input.input and receives a string instead of the object with input and chat_history. Listing 6 reproduces it with a fake retriever that prints the question it receives.

Listing 6: the retriever with history inside createRetrievalChain (run on classic 1.0.61)
import { Document } from "@langchain/core/documents";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
import { RunnableLambda } from "@langchain/core/runnables";
import { createHistoryAwareRetriever } from "@langchain/classic/chains/history_aware_retriever";
import { createRetrievalChain } from "@langchain/classic/chains/retrieval";

const base = new RunnableLambda({ func: (q: string) => [new Document({ pageContent: `found for: ${q}` })] });
const llm = new RunnableLambda({ func: () => "rewritten question" });
const rephrasePrompt = ChatPromptTemplate.fromMessages([
  new MessagesPlaceholder("chat_history"),
  ["human", "{input}"],
]);
const haRetriever = await createHistoryAwareRetriever({ llm, retriever: base, rephrasePrompt });
const chain = await createRetrievalChain({
  retriever: haRetriever,
  combineDocsChain: new RunnableLambda({ func: () => "answer" }),
});
try {
  const r = await chain.invoke({ input: "hello", chat_history: [] });
  console.log(r.context[0].pageContent);
} catch (e) {
  console.log("ERROR:", (e as Error).message.split("\n")[0]);
}

// Output:
// found for: undefined

The question "hello" reaches the retriever as undefined. With a real index the same situation shows up as an error inside the embedding (Cannot read properties of undefined, which I saw with my fake embedding) or as a request with an empty text to a service. I verified it only on that version; that is why listing 5 composes the chain by hand with RunnablePassthrough.assign, two steps that add first context and then answer to the input object. If you only need single questions, without history, createRetrievalChain with a simple retriever works.

Retrieving better: MMR and filters

If the first k chunks are almost the same as each other, the model receives the same information repeated and less useful material. The Maximal Marginal Relevance picks each result by balancing relevance to the question with diversity from those already chosen. The lambda parameter shifts the balance: close to 1 relevance counts, close to 0 diversity does. The listing uses two-dimensional vectors written by hand, in which the first two texts are almost identical.

Listing 7: similarity versus MMR (run; hand-written vectors)
import { Document } from "@langchain/core/documents";
import { Embeddings } from "@langchain/core/embeddings";
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";

// Two-dimensional hand-written vectors: the first two texts are almost identical.
const vectors: Record<string, number[]> = {
  "reset the password from the settings": [1, 0.1],
  "reset the password from settings": [1, 0.12],
  "the link for the password expires in an hour": [0.7, 0.7],
  "question": [1, 0.2],
};
class Fixed extends Embeddings {
  constructor() { super({}); }
  async embedQuery(t: string) { return vectors[t]; }
  async embedDocuments(ts: string[]) { return ts.map(t => vectors[t]); }
}
const docs = Object.keys(vectors).filter(k => k !== "question").map(t => new Document({ pageContent: t }));
const store = await MemoryVectorStore.fromDocuments(docs, new Fixed());

const simple = await store.asRetriever({ k: 2 }).invoke("question");
console.log("similarity:", simple.map(d => d.pageContent));

const mmr = await store.asRetriever({
  k: 2,
  searchType: "mmr",
  searchKwargs: { fetchK: 3, lambda: 0.3 },
}).invoke("question");
console.log("MMR       :", mmr.map(d => d.pageContent));

// Output:
// similarity: [
//   'reset the password from settings',
//   'reset the password from the settings'
// ]
// MMR       : [
//   'reset the password from settings',
//   'the link for the password expires in an hour'
// ]

With similarity alone, the two results are the two almost-twin variants of the same instruction. With MMR and lambda 0.3 the second place goes to the chunk about the link that expires: different, but still tied to the password. fetchK is how many candidates to consider before choosing the final k. Not all vector stores support every type of search; MemoryVectorStore does, for Chroma and Pinecone check the documentation of the version you use.

What to look at before going to production

  • Check retrieval on its own: print the chunks found for a set of real questions before connecting the model
  • Keep the metadata: they are the basis of citations and filters
  • Set a threshold on the score: below the threshold, answer that you don't know
  • Few chunks in the prompt: more material is not always better, and every chunk costs tokens
  • Low temperature: to answer factual questions it is better to reduce the model's variability

They are the same five rules in five forms: keep under control what the model sees. First the quality of retrieval, because a brilliant model does not fix a wrong context; then the quantity, because the context is limited and paid for. The numeric value of each rule (how many chunks, which threshold, which temperature) is measured on your case: there is no figure valid for everyone, and the ones you find in tutorials without a measurement next to them should be ignored.

What you can do now

You can install the right packages of LangChain.js 1.x and understand why there are five, load files into Document, split them and read in the metadata where they come from; you can write an embedding respecting the interface, search an in-memory index and read the scores; you can compose a chain with history and recognise the createRetrievalChain trap. To choose where to keep the vectors when the index grows, the next step is Vector Databases for Web Developers; for the call to the real model see Integrating the OpenAI and Anthropic APIs.

Frequently asked questions

Why can't langchain/chains/retrieval be imported any more?

With version 1 the historical LangChain code was moved into @langchain/classic. The new path is @langchain/classic/chains/retrieval, and the same goes for combine_documents, history_aware_retriever and vectorstores/memory.

Can I try the pipeline without an API key?

Yes: all you need is an embedding that extends Embeddings and a stand-in model, as in listings 2 and 5. It does not measure the quality of the answers, but it checks that the glue code works, that the metadata reach the prompt and that the chain with history rewrites the question when needed.

Chroma or Pinecone?

Chroma runs as a server you start yourself, suited to development and to those who want to keep the data on their own machine; Pinecone is a managed service, with a key and a cost to read on the price list. The choice has more to do with where you want to keep the data and who runs the service than with the quality of the search.

After the pipeline, the series goes on with a local model with Ollama, with the choice between fine-tuning and RAG, with AI agents and, to close, with AI in CI/CD.

Sources

The facts about the behaviour of the code come from runs made on 2026-11-12 with Node 24.11, @langchain/core 1.4.0, @langchain/classic 1.0.61, @langchain/textsplitters 1.0.2, langchain 1.6.5, in a temporary folder outside the repository. Listings 1, 2, 3, 5, 6 and 7 were run (listing 5 with identical output in two runs); listing 4 was only compiled with tsc, not run, because it requires keys and a server. No model was called.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects