AI Hints
Home›RAG Tutorial›Monitoring and Feedback
RAG · Lesson 103 of 120

Monitoring

Log questions and misses.

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

Once RAG is live, real customers ask questions you never imagined. Monitoring logs every question, what was retrieved, and how well it matched. Weak matches show you what's missing from your documents.

Monitoring
From the video: Monitoring
  • Real questions
  • Log everything
  • Find the gaps

Logging each question

For every question, we log the time, the question, the top source, and the top score. A score below zero point four is flagged as a possible miss. Run it. The skateboard question is flagged. It's a gap in our documents.

monitor.pypython
import json, time
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))

def log(q):
    score, top = index.search(q, 1)[0]
    entry = {"time": int(time.time()), "question": q, "source": top["source"],
             "score": score, "possible_miss": score < 0.4}
    open("questions.jsonl", "a").write(json.dumps(entry) + "\n")

for q in ["How much is UK delivery?", "Do you sell skateboards?", "When is York open?"]:
    log(q)
for line in open("questions.jsonl"):
    e = json.loads(line); print(e["possible_miss"], e["score"], e["question"])
Output
False 0.67 How much is UK delivery?
True 0.34 Do you sell skateboards?
False 0.52 When is York open?
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]

What to watch

Watch the share of possible misses, and which topics they're about. Watch latency, and cost per question. And read a sample of real questions every week. They're the best source of new test cases.

keyvalue
Missesshare and topics
Latencyper question
Costper question
Weeklyread real questions

Summary

Log every question with its top score, and review the weak matches to find gaps. Next, feedback.

Key takeaways
  • Log questions
  • Flag low scores
  • Find gaps
Next up: Feedback — thumbs up and down