LangChain.js: Building LLM Applications with TypeScript

Lesson 3 of 6

Retrieval-Augmented Generation with LangChain.js

LangChain.js ships the same RAG building blocks as its Python counterpart: text splitters, embeddings, vector stores, and retrievers, all typed and composable with .pipe().

Splitting text

TypeScript

Like its Python counterpart, RecursiveCharacterTextSplitter prefers splitting on paragraph and sentence boundaries before falling back to a fixed size, keeping chunks semantically coherent, chunkOverlap repeats a few characters between adjacent chunks so a fact near a boundary isn't cut cleanly in half.

Embedding and storing

TypeScript

This needs a real API key to compute embeddings, so it's read-only here. MemoryVectorStore.fromTexts takes the chunks, per-chunk metadata (here, just an id), and the embeddings model, embedding every chunk and keeping the vectors in memory for similarity search. .asRetriever({ k: 3 }) wraps it as a Runnable returning the 3 most similar chunks for a given query.

Wiring retrieval into a chain

TypeScript

Read-only, needs a real model and vector store. RunnableSequence.from([...]) is the explicit, array-based way to build a multi-step chain, the object in the first step runs both branches on the same input in parallel: retriever.pipe(formatDocs) turns the question into formatted context, while new RunnablePassthrough() forwards the original question unchanged, exactly mirroring the Python version's dictionary syntax.

WARNING

"Using only this context" in the prompt is what keeps the model grounded in your retrieved documents instead of answering from its own training data, drop that instruction and you've built a chatbot that ignores the very documents you retrieved.

📝 LangChain.js RAG Quiz

Passing score: 70%
  1. 1.What does RunnableSequence.from([...]) do?

  2. 2.new RunnablePassthrough() forwards its input unchanged, useful for passing the original question alongside retrieved context.

  3. 3.chunkOverlap repeats a few characters between adjacent chunks so a fact near a boundary isn't ____ in half.