AI Hints
Home›RAG Tutorial›Chains and Context
RAG · Lesson 46 of 120

A RAG Chain

LangChain pipes.

⏱ 2 min read▶ Video at 46:15🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

LangChain lets us join the steps of RAG with pipes. Retrieve, fill the prompt, call the model, and read the text. The whole thing becomes one object we can invoke.

A RAG Chain
From the video: A RAG Chain
  • Join steps with pipes
  • One object
  • Invoke it

RAG as a chain

Retrieve wraps our index search, and joins the chunk text. The first step sends the question to retrieve, and passes it through unchanged. Then the prompt template, the model, and the output parser. Run it. The chain answers from the rentals page.

rag_chain.pypython
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from rag_kit import load_docs, make_chunks, Index
from llm import llm, PROMPT

index = Index(make_chunks(load_docs()))
retrieve = RunnableLambda(lambda q: "\n\n".join(c["text"] for s, c in index.search(q)))

chain = (
    {"context": retrieve, "question": RunnablePassthrough()}
    | ChatPromptTemplate.from_template(PROMPT)
    | llm
    | StrOutputParser()
)
print(chain.invoke("Which stores rent out bikes?"))
Output
Based on the context, bikes can be rented from the Leeds and York stores.
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()

Through the chain

The question goes in. Retrieve finds the context. The template builds the prompt. The model writes. And the parser returns plain text.

  1. Question
  2. Retrieve
  3. Prompt
  4. Model
  5. Text
Through the chain
From the video: Through the chain

Summary

A RAG chain pipes retrieval, the prompt, the model, and a parser into one object. Next, formatting the context.

Key takeaways
  • RunnableLambda
  • RunnablePassthrough
  • Pipes
Next up: Formatting Context — numbered chunks