Build a RAG app
Retrieve the passages that answer a question, ground a prompt in them, and know when to say "no answer".
Run itWhat you get: answer or refuse
| question | top_passage | score |
|---|---|---|
| what happens to my files when a project stops? | ByteRun projects keep their files when they stop. | 0.45 |
| how do I keep my API key private? | Store API keys as project secrets so they never appear in the notebook. | 0.41 |
| what is the capital of France? | (no match) | 0.00 |
The notebook
# Build a RAG app Retrieval-augmented generation answers a question from your own documents: **retrieve** the passages that matter, put them in a **prompt**, and let a model **answer** from them only. This notebook does all three on a small set of passages in `docs.csv` (14 short notes about ByteRun). Retrieval uses TF-IDF, which matches words rather than meaning, so you can see exactly why a passage ranked where it did. It runs here with no signup and no API key; add a key to get a real model answer.
import pandas as pd docs = pd.read_csv("docs.csv") print(f"Loaded {len(docs)} passages.") docs.head()## Retrieve Index the passages once, then score every passage against a question and keep the top `k`. The score is cosine similarity, from 0 (no shared words) to 1.
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity vec = TfidfVectorizer(stop_words="english") matrix = vec.fit_transform(docs["text"]) def retrieve(question, k=3): scores = cosine_similarity(vec.transform([question]), matrix)[0] top = scores.argsort()[::-1][:k] return docs.iloc[top].assign(score=scores[top].round(2))[["id", "topic", "text", "score"]] retrieve("what happens to my files when a project stops?")Look at the second row. It matches "project" and nothing else, so it scores well above zero even though it is not about files. TF-IDF cannot tell that "stops" and "stop" are the same word, or that "stops" relates to "idle". Swapping in embeddings is the usual fix; the rest of the notebook stays the same.
## Know when not to answer A question the passages do not cover still gets a "closest" passage, which is how a RAG app ends up answering confidently from the wrong text. Set a minimum score and refuse below it.
MIN_SCORE = 0.2 questions = [ "what happens to my files when a project stops?", "how do I keep my API key private?", "what is the capital of France?", ] rows = [] for q in questions: best = retrieve(q, k=1).iloc[0] answered = best["score"] >= MIN_SCORE rows.append({"question": q, "top_passage": best["text"] if answered else "(no match)", "score": best["score"]}) print(pd.DataFrame(rows).to_string(index=False))## Ground the prompt, then answer The model only sees what you put in the prompt, so tell it to use the passages and to say so when they are not enough. Without an API key this prints the prompt it would send, which is the part you control. To get a real answer, add an `ANTHROPIC_API_KEY` secret to a project on real compute (the browser kernel has no secrets and cannot reach the API) and re-run.
import os def build_prompt(question, k=3): hits = retrieve(question, k) hits = hits[hits["score"] >= MIN_SCORE] if hits.empty: return None context = "\n".join(f"[{row.id}] {row.text}" for row in hits.itertuples()) return ( "Answer using only the passages below. If they do not contain the answer, " "say you do not know. Cite the passage ids you used.\n\n" f"Passages:\n{context}\n\nQuestion: {question}" ) def answer(question): prompt = build_prompt(question) if prompt is None: print("No passage scored above MIN_SCORE, so there is nothing to answer from.") return key = os.environ.get("ANTHROPIC_API_KEY") try: import anthropic except ImportError: anthropic = None if not (key and anthropic): print("Prompt that would be sent (set ANTHROPIC_API_KEY on real compute for a model answer):\n") print(prompt) return reply = anthropic.Anthropic(api_key=key).messages.create( model="claude-sonnet-5-5", max_tokens=300, messages=[{"role": "user", "content": prompt}], ) print(reply.content[0].text) answer("how do I keep my API key private?")## Your turn 1. Ask about something `docs.csv` covers using different words than the passage (try "stored" instead of "keep"). What score do you get? 2. Raise and lower `MIN_SCORE`. Which questions flip between answered and refused? 3. Add your own passages to `docs.csv` and re-run from the top.
Runtime requirements
- Python
- Python 3.12 (in-browser) or the Python data science environment
- Packages
- scikit-learn, pandas
- Sample data
- docs.csv
- Environment
- Python data science ยท CPU
Browser or real compute
In your browser this notebook runs on a small Python with limited memory and no installs. A ByteRun project runs the same notebook on a full machine with your files saved, any package, and more memory when you need it.
Start the 60-day free trial with this template