Agentic AI

A Simple RAG App

The whole module in one Python file: a PDF as the documents, Gemini for the embeddings and the answers, FAISS as the store. Read the script to revise; press Explain on it for every step explained, enough to understand RAG from this page alone.

Concept + code Python 3.12 Needs GOOGLE_API_KEY

Lessons 6.1 to 6.7 met the tools one at a time: four model providers, five loaders, four splitters, four embedding classes, two vector stores. This lesson picks one of each and puts them in one script, so the pipeline can be read, run and remembered as a whole; it is the page to come back to for the syntax. Each class in the script has its box in the map below.

Index once, ask many times

The objects of a RAG app in LangChain, and the lesson that covers each one.

The two phases of a RAG app Top row, run once to build the index: WebBaseLoader loads documents, RecursiveCharacterTextSplitter cuts them into chunks, OpenAIEmbeddings turns the chunks into vectors, and FAISS stores them. Bottom row, run for each question: the retriever embeds the question with the same embeddings model and searches the FAISS index for the 4 nearest chunks; create_stuff_documents_chain puts the chunks and the question into the prompt; ChatOpenAI writes the answer. once, to build the index load · 6.4 WebBaseLoader split · 6.5 RecursiveCharacter TextSplitter embed · 6.6 OpenAIEmbeddings store · 6.7 FAISS docs chunks vectors embeds the question with the same model searches the index for each question question retrieve · 6.7 as_retriever() stuff into the prompt · 6.8 create_stuff_ documents_chain generate · 6.1 ChatOpenAI answer 4 chunks
  1. Once: the loader reads the page, the splitter cuts it into chunks, the embeddings model turns each chunk into a vector, and FAISS stores the vectors with their chunks.
  2. For each question: the retriever embeds the question with the same model and takes the 4 nearest chunks; the stuff chain puts them in {context} and the question in {input}; the chat model writes the answer.
  3. The result: create_retrieval_chain returns all three, {"input": …, "context": […], "answer": …}: the question, the 4 chunks and the answer.

Observe: only the bottom row runs for each question: one embedding call and one call to the chat model. The top row runs again only when the documents or the embeddings model change.

Before you run it

  • GOOGLE_API_KEY in your .env file, created in Google AI Studio (lesson 6.1).
  • attention.pdf in the project folder.
  • The packages of lesson 6.1's requirements.txt; the script uses langchain-google-genai, langchain-community, langchain-text-splitters, langchain-classic, faiss-cpu and pypdf.

The script

rag_app.pyPython
"""Answer questions about a PDF with Gemini: load, split, embed, store, retrieve, answer."""
import sys

from dotenv import load_dotenv
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

load_dotenv()  # GOOGLE_API_KEY from .env

# 1. Model: messages in, an AIMessage out (lesson 6.1)
llm = ChatGoogleGenerativeAI(model="gemini-3.5-flash-lite", temperature=0)

# 2. Load: one Document per page (lesson 6.4)
docs = PyPDFLoader("attention.pdf").load()

# 3. Split: chunks of up to 1,000 characters, each repeating up to 200 of the last (lesson 6.5)
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = splitter.split_documents(docs)

# 4. Embed: one vector per chunk, and later per question, from the same model (lesson 6.6)
embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")

# 5. Store and retrieve: FAISS keeps the vectors; the retriever returns the 4 nearest chunks (lesson 6.7)
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
print(f"Indexed {len(chunks)} chunks from {len(docs)} pages")

# 6. Prompt and chain: stuff the chunks into {context}, the question into {input} (explained below)
prompt = ChatPromptTemplate.from_template(
    """Answer the question using only the context below.
If the context does not contain the answer, say you don't know.

<context>
{context}
</context>

Question: {input}"""
)
document_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, document_chain)

if __name__ == "__main__":
    question = " ".join(sys.argv[1:]) or "What is multi-head attention?"
    response = rag_chain.invoke({"input": question})
    print(response["answer"])
    print("Sources: pages", ", ".join(doc.metadata["page_label"] for doc in response["context"]))

The embedding model name is Google's at the time of writing, and the chat model is the one of lesson 6.1: check both in Google's model list VERIFY, since Google retires older models. Any current Gemini chat model works in step 1; changing the embedding model means building the index again.

Run it

Terminalzsh
python rag_app.py "What is multi-head attention?"
OutputIllustrative · the counts are real; the answer and the sources vary per run
Indexed 52 chunks from 15 pages
Multi-head attention runs several attention functions ("heads") in parallel, each on its own learned projection of the queries, keys and values, and concatenates their outputs. This lets the model attend to information from different representation subspaces at different positions; the Transformer uses 8 heads.
Sources: pages 4, 4, 5, 2
Terminalzsh
python rag_app.py "Who won the 2018 World Cup?"
OutputIllustrative
Indexed 52 chunks from 15 pages
I don't know.
Sources: pages 12, 1, 11, 13

The retriever always returns four chunks, even for a question the paper can't answer; the prompt is what keeps the model from answering from memory. Every run embeds all 52 chunks again before the first question: fine for one paper, slow and costly for a library of them (practice).

Swap one piece

Every loader returns Documents, every splitter takes and returns them, every embeddings class has embed_documents and embed_query, every vector store has as_retriever, and every chat model has invoke. That shared interface is why each alternative in the module changes one line of the script:

Step In the script Alternatives
Model ChatGoogleGenerativeAI(...) ChatOpenAI(model="gpt-4o"), ChatGroq(model=...) (6.1), ChatOllama(model="qwen3.5") (6.2)
Load PyPDFLoader("attention.pdf") TextLoader, WebBaseLoader, ArxivLoader, WikipediaLoader (6.4)
Split RecursiveCharacterTextSplitter(...) CharacterTextSplitter (6.5); HTMLHeaderTextSplitter, RecursiveJsonSplitter (6.5)
Embed GoogleGenerativeAIEmbeddings(...) OpenAIEmbeddings, OllamaEmbeddings, HuggingFaceEmbeddings (6.6)
Store FAISS.from_documents(...) Chroma.from_documents(..., persist_directory=...) (6.7)
Chain create_retrieval_chain(...) An LCEL chain (module 07); an agent with a retriever tool (15.2)

Practice

Practice 1Index once. Save the FAISS index to a folder on the first run and load it on later runs, so only the first run embeds the chunks.Show solution
rag_app.py (step 5, changed)Python
from pathlib import Path

index_dir = Path("faiss_attention")
if index_dir.exists():
    vectorstore = FAISS.load_local(index_dir, embeddings, allow_dangerous_deserialization=True)
else:
    vectorstore = FAISS.from_documents(chunks, embeddings)
    vectorstore.save_local(index_dir)
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

Loading and splitting can move into the else branch too, since only a new index needs them. The folder holds a pickle, which is safe here because the script wrote it (lesson 6.7); delete it when the PDF or the embedding model changes.

Practice 2Ask a web page. Point the script at LangSmith's documentation page on usage limits instead of the PDF, and print each source's address instead of a page number.Show solution
rag_app.py (changed lines)Python
from langchain_community.document_loaders import WebBaseLoader

docs = WebBaseLoader("https://docs.smith.langchain.com/tutorials/Administrators/manage_spend").load()

print("Sources:", sorted({doc.metadata["source"] for doc in response["context"]}))

Only the loader and the last line change: web pages have no page_label, but every loader sets source.