RAG · Lesson 87 of 120
RAG with LangGraph
A small graph.
As RAG gets more steps, like grading and retrying, plain code gets messy. LangGraph lets us draw the steps as a graph, with nodes for each step, and edges that can loop back.

- More steps
- Messy code
- Draw it as a graph
A two-node graph
State holds the question, the chunks, and the answer. The retrieve node fills the chunks. The generate node writes the answer. Edges run from start, to retrieve, to generate, to the end. Run it. The graph answers from the York store page.
rag_graph.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from rag_kit import load_docs, make_chunks, Index
from llm import answer
index = Index(make_chunks(load_docs()))
class State(TypedDict):
question: str
chunks: list
answer: str
retrieve = lambda s: {"chunks": [c for _, c in index.search(s["question"])]}
generate = lambda s: {"answer": answer(s["question"], s["chunks"])}
g = StateGraph(State).add_node("retrieve", retrieve).add_node("generate", generate)
g.add_edge(START, "retrieve"); g.add_edge("retrieve", "generate"); g.add_edge("generate", END)
print(g.compile().invoke({"question": "When is the York shop open?"})["answer"])Output
Based on the provided context, the York shop is open Monday to Saturday, 9am to 5:30pm, and is closed on Sunday.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Growing the graph
Start with retrieve and generate. Add a grade node after retrieve. Add a conditional edge that loops to a rewrite node when grading fails. And a check node before the end.
- Retrieve
- Grade
- Rewrite loop
- Generate
- Check

Summary
LangGraph turns RAG steps into nodes and edges, so grading and retries stay tidy. Next, tables and numbers.
Key takeaways- State
- Nodes
- Edges
Next up: Tables and Numbers — structured data