AI Hints
Home›LangChain Tutorial›Your First RAG Chain
LangChain · Lesson 70 of 120

Your First RAG Chain

Retrieve then answer.

⏱ 2 min read▶ Video at 1:19:17🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

We have every piece. Documents, chunks, embeddings, a vector store, and a retriever. Now we connect them to a model, and build a chain that answers from the shop's real policies.

Your First RAG Chain
From the video: Your First RAG Chain
  • All the pieces are ready
  • Connect them to a model
  • Answers from real policies

The RAG chain

The retriever finds three chunks. Format docs joins their text into one block. The dictionary at the start runs two things side by side. The context comes from the retriever, and the question passes straight through. Then the prompt, the model, and the parser, just like before. Run it. This time the answer is the real price, five pounds ninety nine, taken from the shipping policy.

rag_chain.pypython
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from shop_kb import build_store

retriever = build_store().as_retriever(search_kwargs={"k": 3})
model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_template(
    "Answer using only this context:\n{context}\n\nQuestion: {question}")

def format_docs(docs):
    return "\n\n".join(d.page_content for d in docs)

chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}
         | prompt | model | StrOutputParser())
print(chain.invoke("How much is express delivery?"))
Output
Express delivery costs £5.99.
Also uses kb/shipping.md
# Shipping
Standard delivery in the UK takes 3 to 5 working days and costs £2.99.
Delivery is free on orders over £25.
Express delivery arrives the next working day if you order before 2pm, and costs £5.99.
We ship to Ireland and France in 5 to 8 working days for £7.50.
Every order gets a tracking link by email once it leaves our warehouse.
Also uses kb/returns.md
# Returns and refunds
You can return any book within 30 days of delivery for a full refund.
Books must be unread and in the condition you received them.
Damaged or faulty books can be returned at any time, and we pay the return postage.
Refunds go back to the original payment method within 5 working days of us receiving the book.
To start a return, reply to your order confirmation email.
Also uses kb/gift_cards.md
# Gift cards
Riverside Books gift cards come in values from £10 to £100.
Gift cards never expire and can be used online or in our shop.
A gift card can be used across several orders until the balance is spent.
Gift cards cannot be exchanged for cash.
Also uses kb/loyalty.md
# Riverside Readers loyalty club
Joining the Riverside Readers club is free.
Members earn one point for every pound they spend.
100 points can be swapped for a £5 voucher.
Members get early access to signed editions and a birthday discount of 10 percent.
Also uses kb/shop.md
# About the shop
Riverside Books has one physical shop, at 12 Mill Lane, Bath.
The shop is open from 9am to 6pm Monday to Saturday, and 11am to 4pm on Sunday.
We sell new and second-hand books, and run a children's story time every Saturday at 10am.
You can contact us at hello@riverside-books.example or on 01225 000 000.
Also uses shop_kb.py
from pathlib import Path
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="kb"):
    return [Document(p.read_text(), metadata={"source": p.name})
            for p in sorted(Path(folder).glob("*.md"))]

def build_store(folder="kb"):
    splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=40)
    chunks = splitter.split_documents(load_docs(folder))
    embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
    return InMemoryVectorStore.from_documents(chunks, embeddings)

What happens inside

Here's the journey of one question. The question goes to the retriever, which returns the closest chunks. The chunks and the question fill the prompt. The model reads the prompt, and writes an answer based on the chunks.

  1. Question
  2. Retriever
  3. Fill prompt
  4. Model
  5. Answer
What happens inside
From the video: What happens inside

Summary

A RAG chain retrieves context, fills the prompt with it and the question, and lets the model answer. Next, writing a better prompt for RAG.

Key takeaways
  • retriever | format_docs
  • RunnablePassthrough
  • prompt | model | parser
Next up: The RAG Prompt — grounding the model