AI Hints
Home›RAG Tutorial›Conversations and Agents
RAG · Lesson 82 of 120

Conversational RAG

Follow-up questions.

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

Real customers have conversations. They ask a question, then follow up with, and how much for a week? The follow up only makes sense with the earlier question. Plain RAG treats every question alone, and gets lost.

Conversational RAG
From the video: Conversational RAG
  • Customers follow up
  • Needs the history
  • Plain RAG gets lost

A follow-up goes wrong

The first question is about renting in York. The follow up just says, and how much for a week. We search with the follow up alone, as plain RAG would. Run it. The top two results are about finance and servicing, not renting.

follow_up.pypython
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))
first = "Can I rent an e-bike in York?"
follow_up = "And how much for a week?"

hits = index.search(follow_up)
print("searched:", [c["source"] for s, c in hits])
Output
searched: ['finance.md', 'servicing.md', 'rentals.md']
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]

Conversational RAG

Keep the chat history. Use it to turn the follow up into a standalone question. Search with that. Answer, with the history in the prompt. And add the new turn to the history.

  1. History
  2. Condense
  3. Search
  4. Answer
  5. Save turn
Conversational RAG
From the video: Conversational RAG

Summary

Follow ups need the conversation history, or search gets lost. Next, condensing the question.

Key takeaways
  • Follow-ups
  • Need history
  • Plain RAG fails
Next up: Condensing the Question — stand-alone queries