RAG with LangChain and LangGraph

Build a retrieval chain and a stateful RAG graph with LangChain's ecosystem.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 17 · Lesson 1 of 4 · Intermediate

RAG with LangChain and LangGraph

Build a retrieval chain and a stateful RAG graph with LangChain's ecosystem.

LangChain is the most widely used framework for LLM applications. It provides standard interfaces for models, embeddings, vector stores, retrievers and prompts, plus hundreds of integrations. LangGraph, from the same team, builds stateful workflows and agents as graphs. This lesson rebuilds the tutorial's basic RAG pipeline with LangChain, then a self-correcting RAG loop with LangGraph.

pip install langchain langchain-anthropic langchain-huggingface langchain-chroma langchain-community langchain-text-splitters langgraph sentence-transformers
Versions

LangChain moves quickly. The code below uses the current split-package layout (langchain-core, langchain-anthropic and so on). If an import fails, check the LangChain documentation for your installed version.

Basic RAG with LangChain

lc_rag.py
from langchain_anthropic import ChatAnthropic
from langchain_chroma import Chroma
from langchain_community.document_loaders import DirectoryLoader, TextLoader
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

# 1. Load and split
docs = DirectoryLoader("docs", glob="*.txt", loader_cls=TextLoader,
                       loader_kwargs={"encoding": "utf-8"}).load()
splits = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100).split_documents(docs)

# 2. Embed and store
embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5",
                                   encode_kwargs={"normalize_embeddings": True})
vectorstore = Chroma.from_documents(splits, embeddings, persist_directory="lc_chroma")
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

# 3. Prompt and model
prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer using only the sources. Cite the source file in brackets. "
               "If the sources do not contain the answer, say you don't know."),
    ("human", "<sources>\n{context}\n</sources>\n\nQuestion: {question}"),
])
llm = ChatAnthropic(model="claude-opus-5-5", max_tokens=2000)

def format_docs(documents) -> str:
    return "\n\n".join(f'<source file="{d.metadata["source"]}">\n{d.page_content}\n</source>'
                       for d in documents)

# 4. Compose the chain with the LangChain Expression Language (LCEL)
chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)
print(chain.invoke("Can I claim my home internet bill?"))

The | operator pipes the output of each step into the next. Every component is swappable: replace Chroma with PGVector or QdrantVectorStore, or the retriever with an EnsembleRetriever that combines BM25 and vectors for hybrid search.

Streaming

for piece in chain.stream("What is the hotel limit in metro cities?"):
    print(piece, end="", flush=True)

A self-correcting RAG graph with LangGraph

Chains run straight through. LangGraph adds state, branches and loops, which is what the self-correcting pipeline from Self-RAG, CRAG and Adaptive RAG needs: retrieve, grade, rewrite and retry if the documents are poor, then generate.

lg_rag.py
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel

class State(TypedDict):
    question: str
    query: str
    documents: list
    answer: str
    attempts: int

class Grade(BaseModel):
    relevant: bool

grader = llm.with_structured_output(Grade)

def retrieve(state: State) -> dict:
    return {"documents": retriever.invoke(state["query"]), "attempts": state["attempts"] + 1}

def route_after_retrieval(state: State) -> str:
    verdict = grader.invoke(f"Question: {state['question']}\n\nDocuments:\n"
                            f"{format_docs(state['documents'])}\n\nDo these documents answer the question?")
    if verdict.relevant or state["attempts"] >= 3:
        return "generate"
    return "rewrite"

def rewrite(state: State) -> dict:
    better = llm.invoke(f"Rewrite this as a better search query for a company policy index. "
                        f"Output only the query.\n\n{state['question']}").content
    return {"query": better}

def generate(state: State) -> dict:
    answer = (prompt | llm | StrOutputParser()).invoke(
        {"context": format_docs(state["documents"]), "question": state["question"]})
    return {"answer": answer}

graph = StateGraph(State)
graph.add_node("retrieve", retrieve)
graph.add_node("rewrite", rewrite)
graph.add_node("generate", generate)
graph.add_edge(START, "retrieve")
graph.add_conditional_edges("retrieve", route_after_retrieval, {"generate": "generate", "rewrite": "rewrite"})
graph.add_edge("rewrite", "retrieve")
graph.add_edge("generate", END)
app = graph.compile()

result = app.invoke({"question": "wfh internet money?", "query": "wfh internet money?", "attempts": 0})
print(result["answer"])

LangGraph also provides persistence (checkpointers that save state between turns, which gives you conversation memory), human-in-the-loop interrupts and streaming of intermediate steps. Its prebuilt agent helpers turn a model and a list of tools into a tool-calling agent, the framework equivalent of Agentic RAG.

Sampling parameters

Current Claude models reject temperature, top_p and top_k. If any framework integration returns an error that mentions one of these, upgrade the integration package or stop passing the parameter.

Key takeaways

  • LangChain gives standard, swappable components: loaders, splitters, embeddings, vector stores, retrievers, prompts and models.
  • LCEL composes them into chains with the | operator, with streaming built in.
  • LangGraph adds state, branches and loops for self-correcting and agentic RAG.
  • Pin versions, because framework APIs change often.