AI Hints
Home›RAG Tutorial›Routing and Practice
RAG · Lesson 67 of 120

Routing

Which source to search.

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

Northwind has two knowledge sources. The help centre, and the Volt Pro manual. And some messages, like hello, need no search at all. A router decides where each question should go.

Routing
From the video: Routing
  • Help centre
  • Volt Pro manual
  • No search

A simple router

Route has one field, with only three allowed values. The model reads the question, and picks one. Run it. The delivery question goes to the help centre. The assist mode question goes to the manual. And hello needs no search.

router.pypython
from typing import Literal
from pydantic import BaseModel
from llm import llm

class Route(BaseModel):
    source: Literal["help_centre", "volt_manual", "none"]

router = llm.with_structured_output(Route)
for q in ["How much is UK delivery?",
          "How do I change the assist mode on my Volt Pro?",
          "Hello there!"]:
    print(router.invoke(f"Pick where to search for: {q}").source, "<-", q)
Output
help_centre <- How much is UK delivery?
volt_manual <- How do I change the assist mode on my Volt Pro?
none <- Hello there!
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()

Routing tips

Describe each source clearly in the prompt. Keep the choices few. Add a none option, for chit chat. And when the router is unsure, searching both sources is a safe fallback.

keyvalue
Describeeach source
Keepfew choices
nonefor chit-chat
Unsuresearch both

Summary

A router sends each question to the right source, or skips search when it isn't needed. Next, practice fixing a bad retriever.

Key takeaways
  • Literal choices
  • Right source
  • Skip search
Next up: Practice: Fix a Bad Retriever — step by step