Velamuvi AIAcademy
LangChain

Lesson 9 of 9 · Project

Project: RAG Chatbot With LangChain

Build a RAG chatbot with LangChain: embeddings, a retriever, standalone follow-up questions, cited answers, an honest 'I don't know' and trimmed chat history.

  • 8 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Combine documents, a splitter, embeddings and a retriever into a knowledge base
  • Rewrite follow-up questions into standalone questions before retrieval
  • Answer from retrieved context with citations, and admit when the answer isn't there
  • Keep a conversation history and trim it
  • Know how to extend the chatbot for production

What you'll build

A customer chatbot for Velamuvi Bikes, a made-up e-bike shop, that answers questions from the shop's policies. It must:

  • Answer only from the policies, and cite which policy it used.
  • Handle follow-up questions such as “And the frame?” that only make sense in context.
  • Say “I don't know” when the policies don't cover a question, instead of making something up.

It brings together everything in this course: chat models, prompt templates with history, output parsers, LCEL chains, retrievers and tracing.

The follow-up problem

Retrieval works on the text of the question. “How long is the battery warranty?” retrieves the warranty policy well. But the follow-up “And the frame?” contains no word about warranties at all, so searching for it alone finds nothing useful.

The fix is an extra step: before retrieving, ask the model to rewrite the latest question as a standalone question. Retrieval uses the rewritten question; the answer step still sees the conversation and the original wording.

The design in plain Python

Here's the whole flow with simple stand-ins for the two model calls, so you can run it and follow each step:

Try it yourselfPython
import math, re

# The chatbot's design in plain Python: rewrite follow-ups, retrieve, answer with a citation,
# and admit when the knowledge base has no answer. (Simple stand-ins replace the model calls.)
POLICIES = {
    "warranty.md": "Frames have a 5-year warranty. Batteries have a 2-year warranty, or 800 charge cycles.",
    "repairs.md": "Warranty repairs are free at partner workshops in Lisbon, Porto and Faro.",
    "returns.md": "You can return an unused bike within 30 days of delivery for a full refund.",
}
TOPICS = {"warranty": {"warranty"}, "frame": {"frame", "frames"}, "battery": {"battery", "batteries"},
          "repair": {"repair", "repairs", "repaired", "workshops"}, "city": {"lisbon", "porto", "faro"},
          "returns": {"return", "refund"}}

def words(t): return set(re.findall(r"[a-z]+", t.lower()))
def topics_of(t): return [name for name, ws in TOPICS.items() if words(t) & ws]
def embed(t):
    v = [len(words(t) & ws) for ws in TOPICS.values()]
    n = math.sqrt(sum(x * x for x in v)) or 1
    return [x / n for x in v]

def rewrite(question, last_topics):
    """Stand-in for the rewrite model: a follow-up borrows the topics of the previous question."""
    follow_up = question.lower().startswith(("and ", "what about")) or words(question) & {"it", "that", "they"}
    return f"{question} (context: {' '.join(last_topics)})" if follow_up and last_topics else question

def answer(standalone, question):
    q = embed(standalone)
    score, source = max((sum(a * b for a, b in zip(q, embed(t))), s) for s, t in POLICIES.items())
    if score < 0.5:
        return "I don't know: that isn't in my information. A colleague can help."
    sentences = re.split(r"(?<=\.) ", POLICIES[source])          # stand-in for the answer model:
    best = max(sentences, key=lambda s: len(set(topics_of(s)) & set(topics_of(question))))
    return f"{best} [{source}]"                                   # the most relevant sentence, cited

last_topics = []
for q in ["How long is the battery warranty?", "And the frame?", "Can I get it repaired in Porto?",
          "Do you sell helmets?"]:
    standalone = rewrite(q, last_topics)
    print(f"You: {q}\n     (searched for: {standalone})\nBot: {answer(standalone, q)}\n")
    last_topics = topics_of(q) or last_topics

Follow the four questions. The second and third are follow-ups, so the rewrite step adds context before searching. The last question isn't covered by any policy: the best match scores below the threshold, and the bot says it doesn't know.

The LangChain version

Here is the full chatbot with real components. It uses everything from lessons 2 to 7:

from langchain.chat_models import init_chat_model
from langchain.embeddings import init_embeddings
from langchain_core.documents import Document
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter

# ---- 1. The knowledge base ----
POLICIES = {
    "warranty.md": "Frames have a 5-year warranty. Batteries have a 2-year warranty, or 800 charge cycles, "
                   "whichever comes first. The warranty covers manufacturing faults, not crash damage.",
    "repairs.md": "Warranty repairs are free at our partner workshops in Lisbon, Porto and Faro. "
                  "Book a repair online; most repairs take 3 to 5 working days.",
    "returns.md": "You can return an unused bike within 30 days of delivery for a full refund.",
    "delivery.md": "Orders ship within 2 working days. Delivery to Portugal and Spain is free.",
}
docs = [Document(page_content=text, metadata={"source": name}) for name, text in POLICIES.items()]
chunks = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=40).split_documents(docs)
store = InMemoryVectorStore.from_documents(chunks, init_embeddings("openai:text-embedding-3-small"))
retriever = store.as_retriever(search_kwargs={"k": 2})

model = init_chat_model("anthropic:MODEL_NAME", temperature=0)

# ---- 2. Turn follow-up questions into standalone questions for the retriever ----
rewrite = ChatPromptTemplate.from_messages([
    ("system", "Rewrite the user's last question as a standalone question, using the conversation "
               "for context. Reply with the question only."),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
]) | model | StrOutputParser()

# ---- 3. Answer from the retrieved context, with citations ----
answer_chain = ChatPromptTemplate.from_messages([
    ("system", "You are the assistant for Velamuvi Bikes. Answer using only the context, cite sources "
               "in square brackets, and say you don't know if the context doesn't contain the answer."
               "\n\nContext:\n{context}"),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
]) | model | StrOutputParser()

def format_docs(docs):
    return "\n\n".join(f"[{d.metadata['source']}] {d.page_content}" for d in docs)

def chat(question, history):
    standalone = rewrite.invoke({"history": history, "question": question}) if history else question
    docs = retriever.invoke(standalone)
    answer = answer_chain.invoke({"context": format_docs(docs), "history": history, "question": question})
    history += [HumanMessage(question), AIMessage(answer)]
    del history[:-10]                                  # keep the last 5 exchanges
    return answer, standalone

# ---- 4. A conversation ----
history = []
for question in ["How long is the warranty on the frame?", "And on the battery?",
                 "Can I get it repaired in Porto?", "Do you sell helmets?"]:
    answer, standalone = chat(question, history)
    print(f"You: {question}\n     (searched for: {standalone})\nBot: {answer}\n")
Output
You: How long is the warranty on the frame?
     (searched for: How long is the warranty on the frame?)
Bot: Frames have a 5-year warranty [warranty.md].

You: And on the battery?
     (searched for: How long is the warranty on the battery?)
Bot: Batteries have a 2-year warranty or 800 charge cycles, whichever comes first [warranty.md].

You: Can I get it repaired in Porto?
     (searched for: Can I get my bike's battery repaired under warranty in Porto?)
Bot: Yes. Warranty repairs are free at our partner workshop in Porto, and most take 3 to 5 working days; you can book online [repairs.md].

You: Do you sell helmets?
     (searched for: Does Velamuvi Bikes sell helmets?)
Bot: I don't know: the information I have doesn't mention helmets. Our shop staff can tell you what accessories are in stock.

How it works

  1. Knowledge base. Each policy becomes a Document with its file name as the source. The splitter makes chunks, the embedding model turns them into vectors, and InMemoryVectorStore makes them searchable. The retriever returns the 2 best chunks per question.
  2. Rewrite chain. A prompt with the conversation history (MessagesPlaceholder) asks for a standalone question. It only runs when there is history; the first question is already standalone.
  3. Answer chain. The system message holds the rules (only the context, cite sources, admit not knowing) and the formatted context. The history goes in too, so the reply fits the conversation. temperature=0 keeps answers consistent.
  4. History. After each turn, the question and answer are appended as messages, and del history[:-10] keeps the last five exchanges, so the prompt can't grow without limit (see the Memory in AI Agents course).

Common mistakes

Practice exercise

Format retrieved documents for the chatbot's prompt, and build the list of sources to show under the answer.

Your solutionPython
docs = [("warranty.md", "Frames have a 5-year warranty."),
        ("repairs.md", "Repairs are free in Porto."),
        ("warranty.md", "Batteries have a 2-year warranty.")]

# 1) Print the context for the prompt: each doc as "[source] text", with a blank line between docs.
# 2) Then print "Sources: " followed by each source once, in the order they first appear,
#    separated by ", ".
Knowledge check

Why does the chatbot rewrite follow-up questions before retrieving?

Summary

  • The chatbot is a knowledge base (documents, chunks, embeddings, retriever) plus two chains: rewrite and answer.
  • Standalone questions make follow-ups retrievable.
  • The answer prompt enforces context only, citations and “I don't know”.
  • History is appended each turn and trimmed to keep prompts small.
  • For production: a vector database, streaming, session storage, tracing and a test set.

Course complete

You can now use LangChain's chat models, prompt templates and output parsers, compose them into LCEL chains with parallel steps, routing, retries and fallbacks, retrieve documents for RAG, give models tools and build agents with create_agent, trace everything with LangSmith, and put it all together into a chatbot that answers from your own documents with citations. Next: the LangGraph course shows how to build stateful agents as graphs.

Finished reading? Tick it off to track your progress.