DEV Community

Santiago Alvarez
Santiago Alvarez

Posted on Edited on

RAG notes

Day Topic Example Status
1 Talking to an LLM from code Classifying emails by category and urgency ✅ Code
2 Roles, examples and delimiters in prompts Translating technical language into plain language ✅ Code
3 Structured output with JSON, validated with Pydantic Turning a chat order into a table ✅ Code
4 Images with vision models Scanning a receipt and returning a JSON with the products and the total ✅ Code
5 Embeddings: meaning as numbers Assigning a topic to each news headline ✅ Code
6 RAG, simple structure RAG over my notes with citations and threshold filter 📍 You're here

Day 6: RAG over my notes with citations and a threshold filter

RAG (Retrieval-Augmented Generation) means: first find the relevant information, then give it to the model so it answers using only that information.

Today I built a RAG over my project's notes. Something that caught my attention is that Day 5 was a really good introduction to today's lesson. The search works the same way: on Day 5, I picked the topic closest to each headline; today, I pick the paragraphs closest to each question. The difference is that the model doesn't have complete freedom to say whatever it wants. It can only answer with what's in my notes.

The goal: ask questions about my project and get answers based only on my notes, with a citation showing where each answer came from. To do that, I configured the instructions and specified the output format I need.

Step 1: Retrieve

The following function is similar to the one from Day 5. It calculates the similarity between the question and every paragraph with cos_sim, and keeps the top two. It also adds a filter: if the best score is not higher than 0.20, it returns None. Otherwise, it returns a list of tuples with the paragraph number and its text.

def retrieve(question: str, top_k: int = 2) -> list[tuple[int, str]] | None:
    """Return the paragraphs (number and text) that best answer the question."""
    question_embedding = embedder.encode(question)
    scores = util.cos_sim(question_embedding, note_embeddings)[0]
    best = scores.argsort(descending=True)[:top_k]  # the 2 most relevant paragraphs

    winner = best[0]
    winner_score = scores[winner]

    if winner_score > THRESHOLD:
        return [(i, notes_list[i]) for i in best]
    else:
        return None
Enter fullscreen mode Exit fullscreen mode

Step 2: Generate

The answer() function validates what it gets from retrieve(). The first condition avoids calling the LLM with no context: if chunks is None, it returns right away. That saves an API call and stops the model from making up an answer.

def answer(question: str) -> str:
    chunks = retrieve(question)

    # No relevant notes: don't call the model at all
    if chunks is None:
        return 'Not in my notes'

    context = "\n".join(f"- [{int(i)}] {chunk}" for i, chunk in chunks)
    prompt = f'<context>\n{context}\n</context>\n\n<question>{question}</question>'

    response = client.models.generate_content(
        model=llm_model,
        contents=prompt,
        config=types.GenerateContentConfig(
            system_instruction=SYSTEM_INSTRUCTION,
            temperature=0,
        ),
    )
    return response.text.strip()
Enter fullscreen mode Exit fullscreen mode

Two details make this work:

  • Each paragraph goes with its number ([3]), so the model can cite where the answer came from.
  • <context> and <question> are delimiters, the same idea as Day 2: the model knows exactly which part is my notes and which part is the question.

SYSTEM_INSTRUCTION = """Answer the question using ONLY the notes inside .
Cite the paragraph number where the answer comes from.
Use this format: "Paragraph [number]: [answer]"
If the answer is not in the context, reply exactly: "Not in my notes." """

Results

Questions answered with paragraph citations, and one returning "Not in my notes"

What I learned

  • RAG helps me work only with the data that has the highest similarity, and it keeps the model limited to the data I provide, so it reduces hallucinations.
  • With the condition if chunks is None, the model isn't called when there are no relevant notes. That saves an API call and stops it from making up an answer.

👉 Full code: day1_rag_notes.py

Top comments (0)