RAG (Retrieval-Augmented Generation) Tutorial with Python

While Large Language Models (LLMs) possess vast amounts of general knowledge from their pre-training corpora, they suffer from two critical limitations: they are completely blind to private corporate data, documentation, or real-time internal files, and they are prone to hallucinating plausible-sounding falsehoods when asked about domain-specific facts.

Fine-tuning models on private datasets is expensive, computationally heavy, and quickly becomes outdated. The industry-standard architecture to solve this is Retrieval-Augmented Generation (RAG). This comprehensive tutorial walks through building a complete, production-grade RAG pipeline from scratch in Python using LangChain, vector embeddings, and the OpenAI API.

1. What is RAG and How Does It Work?

At its core, RAG combines an information retrieval system with a generative LLM. Instead of asking the LLM to answer a prompt entirely from its internal memory, the system searches an external knowledge base for relevant context snippets and injects them directly into the prompt.

  • 1. Ingestion Phase: Raw documents (PDFs, Markdown files, or internal wikis) are loaded, split into smaller manageable chunks, converted into vector embeddings, and stored in a vector database.
  • 2. Retrieval Phase: When a user submits a query, the query is converted into an embedding vector, and a similarity search retrieves the top-k most relevant document chunks from the database.
  • 3. Generation Phase: The retrieved chunks are formatted into a prompt context template and passed to the LLM to synthesize an accurate, grounded answer.

2. Environment Setup and Dependencies

Before writing code, install the required packages including LangChain, OpenAI integrations, and an in-memory vector store like Chroma.

C
# Terminal installation command
pip install langchain langchain-openai chromadb python-dotenv

3. Implementing the RAG Pipeline in Python

Here is a complete, step-by-step Python script that initializes a vector store, indexes sample text data, sets up a retriever, and executes a grounded RAG query.

C
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_core.documents import Document

load_dotenv()

# 1. Prepare sample internal documents
docs = [
    Document(page_content="CodeCrown's internal deployment protocol requires all microservices to be deployed using Kubernetes and Helm charts."),
    Document(page_content="Database migrations on production PostgreSQL instances must be executed exclusively during off-peak maintenance windows (2 AM - 4 AM UTC)."),
    Document(page_content="API rate limiting is enforced via Redis caching layers, restricting client requests to 100 requests per minute per IP address.")
]

# 2. Split documents into manageable chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
splits = text_splitter.split_documents(docs)

# 3. Initialize embeddings and store chunks in Chroma vector database
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 2})

# 4. Initialize LLM and Prompt Template
llm = ChatOpenAI(model="gpt-4o", temperature=0.2)

template = """
Answer the question based strictly on the following context:
{context}

Question: {question}

If you do not know the answer based on the context, state that you cannot find the information.
"""
prompt = ChatPromptTemplate.from_template(template)

# 5. Build the RAG Chain using LCEL (LangChain Expression Language)
format_docs = lambda docs: "\n\n".join(doc.page_content for doc in docs)

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

# 6. Execute a RAG Query
response = rag_chain.invoke("What are the rules for deploying microservices at CodeCrown?")
print("RAG Response:\n", response)

Conclusion

Implementing a Retrieval-Augmented Generation (RAG) pipeline bridges the gap between static LLM pre-training and dynamic, private enterprise data. By combining document chunking, vector embeddings in Chroma, and contextual prompt injection, developers can eliminate hallucinations and deliver highly accurate, grounded AI applications.