A Retrieval-Augmented Generation chatbot that answers questions from your own documents — PDFs, text files, anything — using LangChain, ChromaDB, and the free Gemini API.
LangChain can load PDFs, text files, and web pages. Split them into overlapping chunks.
from langchain_community.document_loaders import PyPDFLoader, TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
# Load a PDF (swap for TextLoader("notes.txt") for plain text)
loader = PyPDFLoader("handbook.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = splitter.split_documents(docs)
print(f"Split into {len(chunks)} chunks")
Split into 84 chunks
Embed the chunks locally with a HuggingFace model and store in ChromaDB.
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = Chroma.from_documents(chunks, embeddings, persist_directory="./chroma_db")
print("Vector store built and saved.")
Vector store built and saved.
Connect the retriever to Gemini for context-aware answers.
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains import RetrievalQA
import os
os.environ["GOOGLE_API_KEY"] = "YOUR_GEMINI_API_KEY"
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.2)
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=retriever,
return_source_documents=True,
)
Ask questions and see which source chunks backed the answer.
questions = [
"What is the refund policy?",
"How do I reset my password?",
]
for q in questions:
result = qa_chain({"query": q})
print(f"Q: {q}")
print(f"A: {result['result']}\n")
print("Sources:")
for doc in result["source_documents"]:
print(f" - Page {doc.metadata.get('page','?')+1}: {doc.page_content[:80]}...")
print()
Q: What is the refund policy? A: Refunds are available within 30 days of purchase for unused accounts. Sources: - Page 12: Refunds and Cancellations. All refund requests must be submitted within...
You built the most in-demand AI architecture of 2025. The same pattern powers enterprise document chatbots — swap in any document collection you own.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.