AI Hints
Home›RAG Tutorial›A First RAG App
RAG · Lesson 9 of 120

Your First RAG App

Under twenty lines.

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

Now we join the pieces. A retriever finds the best page, and the model answers from it. That's a complete RAG app, in under twenty lines.

Your First RAG App
From the video: Your First RAG App
  • Retriever
  • Plus model
  • A full RAG app

Retrieve, then generate

Retrieve picks the page with the most shared words. The prompt puts that page's text in as context, and tells the model to answer only from it. Then we ask whether next day delivery is available for bikes. Run it. The shipping page wins, and the answer is correct, it isn't.

first_rag.pypython
import re
from kb import load_docs
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
words = lambda t: set(re.findall(r"[a-z0-9]+", t.lower()))

def retrieve(question, docs):
    return max(docs, key=lambda d: len(words(question) & words(d["text"])))

question = "Is next-day delivery available for bikes? One sentence."
page = retrieve(question, load_docs())
print("Using:", page["source"])
prompt = f"Answer only from this text.\n\n{page['text']}\n\nQuestion: {question}"
print(llm.invoke(prompt).text.strip())
Output
Using: shipping.md
Next-day delivery is not available for bikes.
Also uses kb.py
from pathlib import Path

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

What we built

Our app retrieves one whole page, adds it to a prompt, and generates an answer. It already beats the model alone. But one page might be too long, or the wrong page. The next sections fix that, with chunks, and search by meaning.

keyvalue
Retrievebest page
Augmentpage in the prompt
Generategrounded answer
Nextchunks and meaning

Summary

A first RAG app retrieves the best page, and lets the model answer from it. Next, what happens when retrieval goes wrong.

Key takeaways
  • retrieve()
  • Prompt with context
  • llm.invoke
Next up: When RAG Goes Wrong — wrong facts in, wrong answer out