How to Build a RAG App with LangChain
In this article
Retrieval-Augmented Generation (RAG) lets you give an LLM access to your own documents, so it can answer questions with up‑to‑date, private information instead of relying only on its training data. With LangChain, you can assemble a working RAG pipeline in about 50 lines of Python. This guide walks you through building one from scratch, from loading documents to asking a question and getting a cited answer.
What You'll Need
- Python 3.9 or later installed.
- An OpenAI API key (or another LLM provider supported by LangChain).
- Basic familiarity with Python and the command line.
- A text file, PDF, or a folder of documents you want to query.
- Install the required packages:
pip install langchain langchain-openai langchain-community chromadb pypdf
Step-by-Step
- Set up your environment and API key. Create a new Python file, e.g.,
rag_app.py. Set your OpenAI key as an environment variable:export OPENAI_API_KEY="your-key-here"(on Windows:set OPENAI_API_KEY=your-key-here). Never hardcode the key in your script. - Import the required LangChain modules. At the top of your file, add:
from langchain_community.document_loaders import TextLoader, PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_community.vectorstores import Chroma from langchain.chains import RetrievalQA
- Load your documents. For a single text file:
loader = TextLoader("my_doc.txt"). For a PDF:loader = PyPDFLoader("my_doc.pdf"). Then load:documents = loader.load(). If you have multiple files, loop over them and concatenate the lists. - Split the documents into chunks. RAG works best when each chunk is small enough for the LLM’s context window. Use:
text_splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50 ) chunks = text_splitter.split_documents(documents)The overlap helps preserve context across chunk boundaries. - Create embeddings and a vector store. Embeddings convert text into numerical vectors. Store them in Chroma (a lightweight, local vector DB):
embeddings = OpenAIEmbeddings() vectorstore = Chroma.from_documents(chunks, embeddings)
This step will call the OpenAI API and may take a few seconds depending on document size. - Set up the LLM. Choose a model that works well for Q&A, e.g.,
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0). Lower temperature makes answers more factual. - Build the RAG chain. Use LangChain’s
RetrievalQAto combine the retriever and the LLM:qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=vectorstore.as_retriever() ) - Ask a question. Run
response = qa_chain.invoke("What is the main topic of the document?")and print the answer. That’s it – you have a working RAG app. - Add source citations (optional but recommended). To see which chunks were used, modify the chain to return source documents:
qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=vectorstore.as_retriever(), return_source_documents=True ) result = qa_chain.invoke({"query": "Your question"}) print(result["result"]) print(result["source_documents"])
Common Mistakes
- Chunk size too large or too small. Very large chunks (e.g., 2000+ tokens) may exceed the LLM’s context or dilute the relevance; very small chunks (e.g., 50 tokens) lose meaning. Stick to 300–800 tokens.
- Not using an overlap. Without overlap, a sentence may be split across chunks, causing the model to miss context.
- Forgetting to set the API key. The most common error is a missing
OPENAI_API_KEYenvironment variable, resulting in an authentication error. - Using the wrong loader for the file type.
TextLoadercannot read PDFs; usePyPDFLoaderfor PDFs andDocx2txtLoaderfor Word files. - Storing the vector store every time. Re‑embedding the same documents on every run wastes time and money. Save the vector store to disk after the first run and load it later.
Tips
- Persist your vector store. After creating the store, add
vectorstore.persist()(Chroma does this automatically if you give a persist directory:Chroma.from_documents(chunks, embeddings, persist_directory="./chroma_db")). Then on later runs, load withChroma(persist_directory="./chroma_db", embedding_function=embeddings). - Experiment with chunk size and overlap. The ideal values depend on your document type. For code, smaller chunks work better; for long prose, larger ones.
- Use a better retriever if needed. For more accurate retrieval, try
vectorstore.as_retriever(search_type="mmr", search_kwargs={"k": 4})to get diverse, relevant chunks. - Add a system prompt. You can customize the prompt to instruct the model to say “I don’t know” when the answer isn’t in the documents, reducing hallucinations.
- Cache embeddings. If you’re iterating, consider using a local embedding model like
sentence-transformersto avoid API costs, though OpenAI embeddings are simple to start with.
Troubleshooting
- “AuthenticationError” or “Incorrect API key”. Check that
OPENAI_API_KEYis set correctly in your shell. Runecho $OPENAI_API_KEY(Mac/Linux) orecho %OPENAI_API_KEY%(Windows) to verify. Ensure the key is active and has quota. - “ModuleNotFoundError: No module named 'langchain_community'”. You may have an older version of LangChain. Install the latest:
pip install --upgrade langchain langchain-community. - “RateLimitError” from OpenAI. You’re hitting API rate limits. Add a delay between requests or use a model with higher rate limits. For testing, use
gpt-4o-miniwhich is faster and cheaper. - Empty or irrelevant answers. The retriever may not be finding good chunks. Increase
kin the retriever (e.g.,as_retriever(search_kwargs={"k": 5})) or adjust chunk size. Also, ensure your question is phrased clearly. - Very slow performance. Embedding many large documents takes time. Consider using a smaller embedding model, or reduce the number of documents initially.
- Chroma errors with “sqlite3.OperationalError”. This is common on some systems. Install
pysqlite3-binaryand add__import__('pysqlite3'); import sys; sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')at the top of your script.
Frequently Asked Questions
- What is RAG exactly? RAG combines a retrieval system (like a vector search over your documents) with a generative LLM. The model first finds relevant text chunks, then uses them as context to generate an answer, making the response grounded in your data.
- Can I use a free LLM instead of OpenAI? Yes. LangChain supports many providers, including local models via Ollama (e.g.,
llama3). You would replaceChatOpenAIwithChatOllamaand use a local embedding model likeOllamaEmbeddings. - How do I add more documents after building the vector store? Load the existing store, then call
vectorstore.add_documents(new_chunks)and persist again. This avoids re‑embedding everything. - What is the best chunk size? There’s no universal answer. For general text, 500 tokens with 50 overlap works well. For code, 200–300 tokens. Test on your data and evaluate answer quality.
- Do I need a vector database like Pinecone? No. Chroma runs locally and is perfect for small to medium document sets. For production with millions of documents, you’d switch to a scalable vector DB, but the LangChain interface remains the same.
- Why does my answer sometimes ignore the documents? This can happen if the retriever returns irrelevant chunks, or if the LLM’s instruction prompt doesn’t emphasize using the context. You can customize the prompt to force the model to rely on the provided context only.