Table of Contents
- What is RAG
- How RAG works
- Benefits of RAG
- Setup
- Architecture diagram
- Simple example: RAG from scratch
- Key concepts
- Common RAG challenges
- Conclusion
In one sentence
RAG (Retrieval-Augmented Generation) combines information retrieval with language generation to produce more accurate, context-aware responses — grounding the LLM in real, queryable data instead of relying on what it memorised during training.
What is RAG
RAG is a technique that combines information retrieval with language generation to provide more accurate and context-aware responses.
How RAG works
- Retrieval: find relevant documents from a knowledge base based on the query.
- Augmentation: combine the retrieved context with the original query.
- Generation: use an LLM to generate a response based on the augmented prompt.
Benefits of RAG
- Reduces hallucinations by grounding responses in real data.
- Allows using private or up-to-date information.
- More cost-effective than fine-tuning.
- Can access external knowledge without retraining.
Setup
# Install required packages
%pip install openaiArchitecture diagram
┌─────────────────────────────────────────────────────────────┐
│ User Query │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Query Encoder │
│ (Convert to embeddings) │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Vector Database (Chroma, etc.) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Doc 1 │ │ Doc 2 │ │ Doc 3 │ │
│ │ Embedding │ │ Embedding │ │ Embedding │ │
│ │ [0.1, ...] │ │ [0.3, ...] │ │ [-0.2,...] │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
└─────────┼─────────────────┼─────────────────┼───────────────┘
│ │ │
│ Similarity │ Similarity │ Similarity │
│ Search ───────►│ Search ───────►│ Search │
│ │ │ │
▼ ▼ ▼ │
┌─────────────────────────────────────────────────────────────┐
│ Retrieved Documents │
│ (Top K matches) │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Prompt Augmentation │
│ Combine query + retrieved context into prompt │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ LLM (OpenAI) │
│ (Generate response) │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Final Response │
└─────────────────────────────────────────────────────────────┘
Simple example: RAG from scratch
Let’s demonstrate RAG with a simple example using a custom implementation. Retrieval is intentionally naive — keyword matching instead of embeddings — so the retrieve → augment → generate flow is easy to follow before introducing a vector database.
import os
from typing import List, Dict
# Configuration
OPENAI_API_KEY = "[SECRET:openrouter-api-key]"
OPENAI_BASE_URL = "https://openrouter.ai/api/v1"
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEYfrom openai import OpenAI
# Initialize OpenAI client (compatible with any OpenAI-compatible API)
client = OpenAI(
api_key=OPENAI_API_KEY,
base_url=OPENAI_BASE_URL
)
# Sample knowledge base (documents)
KNOWLEDGE_BASE = [
"Real Madrid won the UEFA Champions League in 2016 after beating Atletico Madrid 5-3 in Milan.",
"Barcelona's 2018-19 La Liga title was powered by Lionel Messi, Luis Suarez, and Antoine Griezmann.",
"Bayern Munich secured the Bundesliga crown in 2020 with a dominant squad led by Robert Lewandowski.",
"Liverpool lifted the Champions League in 2019 after a thrilling 2-0 win over Tottenham Hotspur.",
"Manchester City won the Premier League in 2021-22, finishing with a record-setting 99 points.",
"Inter Milan claimed the 2010 and 2023 Serie A titles with a strong defensive identity.",
"Juventus remained a major force with titles in 2015, 2016, and 2017 in the Italian league.",
"Paris Saint-Germain won Ligue 1 in 2020 and 2021 with Neymar and Mbappe leading the attack.",
"Chelsea won the Champions League in 2021 after a dramatic 1-0 final against Manchester City.",
"Porto won the 2019-20 Portuguese league and remained one of Europe's most successful clubs.",
"Erling Haaland scored 36 goals in the 2022-23 Premier League season for Manchester City.",
"Kylian Mbappe became a world-class finisher with goals for PSG and Real Madrid in major finals.",
"Kevin De Bruyne controlled midfield with precision passing and crucial assists in title-winning runs.",
"Jude Bellingham was a key player for Real Madrid in 2023-24 with goals in big European matches.",
"Rodri was central to Manchester City's 2023 treble with dominant midfield play.",
"Vinicius Junior emerged as a top winger, scoring in the 2024 Champions League final.",
"Robert Lewandowski won the European Golden Shoe after a prolific spell at Bayern Munich.",
"Mohamed Salah became Liverpool's talisman, scoring decisive goals in domestic and European competitions.",
"Luka Modric remained a creative engine for Real Madrid, winning titles in his later years.",
"Thiago Silva brought leadership and experience during PSG and Chelsea's title pushes.",
"A 3-2 scoreline decided one of the most memorable title races in the 2022-23 Premier League.",
"The 2023 Champions League final ended in a 1-0 result, with a late goal deciding the winner.",
"Real Madrid beat Borussia Dortmund 2-0 in a key 2024 campaign match in Europe.",
"The 2021 final featured a tense 1-1 draw before Chelsea won on penalties.",
"Bayern Munich beat Paris Saint-Germain 1-0 in a dramatic 2020 knockout clash.",
"Manchester City won 4-1 against a top European rival in a historic 2023 quarterfinal.",
"Liverpool beat Barcelona 4-0 in 2017 after one of the most famous comebacks in Champions League history.",
"A late 3-3 draw between two elite clubs in 2022 showed how open European football had become.",
"Real Madrid overturned a 2-0 deficit to beat Manchester City in one of the greatest European ties.",
"The 2022 semifinal between Liverpool and Villarreal ended with a dramatic second leg and a final berth.",
"The 2015-16 season marked the rise of Real Madrid under Zinedine Zidane and Cristiano Ronaldo.",
"The 2016-17 campaign saw Chelsea defend their European crown with a disciplined tactical approach.",
"In 2017-18, Real Madrid won their third straight Champions League title after beating Liverpool.",
"In 2018-19, Liverpool reached the final but fell to six-time winners Real Madrid.",
"In 2019-20, Bayern Munich reached the final and showed the strength of German football.",
"In 2020-21, Chelsea's title run under Thomas Tuchel brought continental success back to London.",
"In 2021-22, Real Madrid won another Champions League after defeating Liverpool in Paris.",
"In 2022-23, Manchester City completed the treble with the Premier League, FA Cup, and Champions League.",
"In 2023-24, Real Madrid added another European title, proving their consistency at the highest level.",
"In 2024-25, European football remained unpredictable as clubs balanced spending, youth development, and tactical innovation.",
"The Premier League title race intensified with Manchester City, Arsenal, and Liverpool battling for the crown.",
"The Bundesliga remained highly competitive as Bayern Munich, Borussia Dortmund, and Leverkusen fought for trophies.",
"Serie A stayed dramatic with Inter Milan, Juventus, and Napoli challenging each year.",
"La Liga featured Real Madrid, Barcelona, and Atletico Madrid in a title race full of pace and physicality.",
"Ligue 1 saw PSG dominate domestically, while Marseille and Monaco challenged at times.",
"Ajax's 2018-19 run to the Champions League semifinal captured the imagination of European football fans.",
"Porto's historic 2011 triumph and later competitive runs highlighted the value of smart recruitment.",
"Benfica remained a respected Portuguese power, with talented young players often moving to larger leagues.",
"Atletico Madrid became a European threat with disciplined defending and quick transitions.",
"Borussia Dortmund's 2023 run showed how a dynamic young team could challenge elite clubs.",
"A standout 4-1 result in the league shook up the title race between top clubs in Europe.",
"A 1-0 derby win created huge momentum for a club chasing domestic history.",
"A late 2-1 comeback in Europe sent a team to the next stage and energized supporters.",
"A 5-0 thrashing by a European giant reminded fans of the gap between elite and chasing clubs.",
"A 3-1 away win in the knockout rounds gave a club a crucial psychological edge.",
"A penalty shootout in the final produced unforgettable scenes and a trophy in front of millions.",
"A 4-3 classic between two attacking sides became one of the defining matches of the decade.",
"A 2-2 draw in a continental clash created a tie that lasted long in memory.",
"A 1-1 semifinal ended with a nail-biting finish and a dramatic penalty sequence.",
"A 6-2 scoreline in a European tie reflected the explosiveness of modern football and elite attacking talent.",
"Cristiano Ronaldo remained one of the biggest names in world football with goals in Europe across the decade.",
"Karim Benzema shaped Real Madrid's attack with elegance, finishing, and leadership.",
"Sergio Busquets gave Barcelona control and experience during a long era of domestic dominance.",
"Virgil van Dijk became a symbol of Liverpool's defensive solidity and European resilience.",
"Alisson Becker delivered clutch saves and composure in crucial Champions League nights.",
"Thomas Muller remained a Bayern Munich icon, combining experience and efficiency in big games.",
"Declan Rice added power and passing quality to Arsenal's midfield and European ambitions.",
"Phil Foden developed into a premier winger and creator for Manchester City.",
"Federico Valverde emerged as a modern box-to-box star for Real Madrid.",
"Reece James became a key defender for Chelsea with physicality and leadership.",
"Inter Milan won the Champions League in 2010 and later returned to the top of Italian football in 2023.",
"Juventus remained a constant in Europe, blending star players with strong domestic success.",
"AC Milan revived their reputation with important Serie A and European results in the last decade.",
"Sevilla became a specialist in European knockout football, winning major continental competitions.",
"Bayer Leverkusen challenged Bayern Munich with a balanced, attacking and disciplined side.",
"RB Leipzig showcased a modern pressing style that produced strong European performances.",
"Napoli's title-winning squads brought a new energy to Italian football and European nights.",
"Atalanta impressed with their attacking flair and fearless approach against elite clubs.",
"Roma and Lazio kept Italian football competitive with passionate matches and ambitious squads.",
"Feyenoord and other Dutch clubs showed the power of academy talent and tactical creativity.",
"Championship history over the last decade shows how quickly the balance of power can shift between clubs.",
"European finals produced unforgettable stories, from dramatic comebacks to late goals and penalties.",
"Clubs with deep squads and strong scouting networks often won the biggest prizes in Europe.",
"El Clasico between Real Madrid and Barcelona remained a huge story for fans and media across the world.",
"Der Klassiker between Bayern Munich and Borussia Dortmund defined German football rivalries in the decade.",
"The North London derby between Arsenal and Tottenham highlighted local pride and elite competition.",
"The Old Firm between Celtic and Rangers still carried huge historical and emotional weight in Europe.",
"The Milan derby between AC Milan and Inter remained one of the most iconic rivalries in world football.",
"The Lisbon derby between Benfica and Sporting CP symbolized tradition, passion, and football heritage.",
"The historic rivalry between clubs across Spain, Italy, and England shaped the narrative of European football.",
"European football became more data-driven, with analytics influencing recruitment, tactics, and match preparation.",
"The last decade saw a new generation of managers use pressing, possession, and transitional play to outsmart rivals.",
"The rise of young talents such as Bellingham, Pedri, and Mbappe changed the face of elite competition.",
"Managers such as Pep Guardiola, Jurgen Klopp, Carlo Ancelotti, and Thomas Tuchel shaped major title races with distinct philosophies.",
"Fans celebrated dazzling goals, tactical battles, and emotional comebacks throughout Europe.",
"Tactical evolution brought more pressing, positional play, and aggressive pressing triggers in midfield.",
"The huge financial power of clubs in England, Spain, and Germany created a competitive environment at the top.",
"Data-driven scouting helped clubs find hidden gems and improve recruitment in domestic and continental competitions.",
"The Champions League remained the crown jewel of European football, with each season producing unforgettable drama.",
"These stories capture the essence of European football over the last ten years, blending player brilliance, club ambition, key scores, and championship history."
]
class SimpleRAG:
def __init__(self, knowledge_base: List[str]):
self.knowledge_base = knowledge_base
def retrieve(self, query: str, top_k: int = 5) -> List[str]:
"""
Simple retrieval: find documents that contain query keywords
In production, you'd use embeddings and vector search
"""
query_words = query.lower().split()
# Score each document by keyword matching
scores = []
for doc in self.knowledge_base:
doc_lower = doc.lower()
score = sum(1 for word in query_words if word in doc_lower)
scores.append((doc, score))
# Sort by score and return top_k documents
scores.sort(key=lambda x: x[1], reverse=True)
return [doc for doc, score in scores[:top_k] if score > 0]
def generate(self, query: str, context: List[str]) -> str | None:
""" Generate response using the retrieved context """
context_text = "\n".join(f"Context {i+1}: {doc}" for i, doc in enumerate(context))
prompt = f"""
Use the following context to answer the question.
Context:
{context_text}
Question: {query}
Answer:
"""
response = client.chat.completions.create(
model="openai/gpt-oss-120b",
messages=[
{"role": "system", "content": "You are a helpful assistant that answers based on the provided context."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=500
)
return response.choices[0].message.content
def query(self, question: str, top_k: int = 5) -> Dict:
"""
Main RAG method: retrieve relevant documents and generate response
"""
# Step 1: Retrieve relevant documents
retrieved_docs = self.retrieve(question, top_k)
# Step 2: Generate response
answer = self.generate(question, retrieved_docs)
return {
"question": question,
"retrieved_documents": retrieved_docs,
"answer": answer
}# Create RAG instance
rag = SimpleRAG(KNOWLEDGE_BASE)
# Test with a query
result = rag.query("What is the best club ?")
print("="*80)
print(f"Question: {result['question']}")
print("="*80)
print("\nRetrieved Documents:")
for i, doc in enumerate(result['retrieved_documents'], 1):
print(f" {i}. {doc}")
print("\n" + "="*80)
print("Answer:")
print("="*80)
print(result['answer'])# Try another query
result2 = rag.query("How does pandas relate to Python?")
print("="*80)
print(f"Question: {result2['question']}")
print("="*80)
print("\nRetrieved Documents:")
for i, doc in enumerate(result2['retrieved_documents'], 1):
print(f" {i}. {doc}")
print("\n" + "="*80)
print("Answer:")
print("="*80)
print(result2['answer'])Why does the second query fail?
The keyword-matching retriever has no notion of meaning — “pandas” and “Python” score zero against every football document, so the LLM receives empty context and falls back on its own knowledge (or hallucinates). This is exactly the gap embeddings and vector similarity search close.
Key concepts
1. Embeddings
- Vector representations of text.
- Capture semantic meaning.
- Allow similarity search.
2. Vector Database
- Stores embeddings efficiently.
- Performs similarity search (ANN — Approximate Nearest Neighbors).
- Examples: Chroma, FAISS, Pinecone, Weaviate.
3. Prompt Engineering
- Context injection.
- Instruction tuning.
- Few-shot learning.
Common RAG challenges
- Chunking strategy: how to split documents optimally.
- Retrieval quality: ensuring relevant documents are found.
- Context window limits: managing token limits.
- Hallucination control: ensuring the LLM sticks to the provided context.
- Hybrid search: combining keyword and vector search.
Conclusion
RAG is a powerful technique that combines the strengths of information retrieval with language generation. It provides a flexible way to:
- Add domain-specific knowledge without retraining.
- Incorporate up-to-date information.
- Ground responses in verifiable sources.
- Reduce hallucinations.
With libraries like LangChain and vector databases, implementing RAG has become accessible for developers.