Chapter 8 of 1135 min
Ask the AI
- Load
- Chunk
- Embed
- Search
- Ask the AI
- App
In this chapter you will:
- get a free Gemini API key, and keep it secret
- build a prompt from the question and the chunks your search found
- get an answer, with its source, from a language model
This is the chapter where your program becomes a RAG app.
How it fits together
Your search already finds the right passages. A language model is good at the other half: reading a few passages and writing a clear answer in plain language. So the last step is:
- Retrieve:
searchfinds the three best chunks. - Augment: put them into a prompt, with the question and instructions.
- Generate: send the prompt to the model, and show its answer.
Get a free API key
An API key is a password that lets your program use a service. Treat it exactly like one.
- Go to Google AI Studio and sign in with your Google account.
- Choose Get API key, then Create API key, and copy it.
The free tier is enough for this whole project. No card needed.
Keep the key out of your code
Never paste a key into rag.py. Code ends up on GitHub, and keys found there get stolen within minutes. Instead, keep it in a separate file that Git never saves.
Create a file called .env (with the dot) in the project folder, containing one line, with your own key after the =:
GEMINI_API_KEY=paste-your-key-hereRemember the .gitignore from chapter 2? It already lists .env. Check that Git really ignores it:
git status.env must not appear in the list. If it does, stop and check .gitignore before you commit anything.
Then install the two libraries this chapter needs:
pip install google-genai python-dotenvWrite answer
At the top of rag.py, add the new imports and one line that reads your .env file:
import os
from dotenv import load_dotenv
from google import genai
from sentence_transformers import SentenceTransformer
load_dotenv() # reads GEMINI_API_KEY from the .env file
model = SentenceTransformer("all-MiniLM-L6-v2")Then add this function to the end:
# Chapter 8: find the right chunks, then ask Gemini to answer from them
def answer(question, chunks, chunk_vectors):
found = search(question, chunks, chunk_vectors)
context = ""
for chunk in found:
context = context + "From " + chunk["source"] + ":\n" + chunk["text"] + "\n\n"
prompt = f"""Answer the question using only the handbook passages below.
If the answer is not in the passages, say that you don't know.
Say which file the answer comes from.
{context}
Question: {question}"""
client = genai.Client()
response = client.models.generate_content(model="gemini-flash-latest", contents=prompt)
return response.text- The loop builds
context: each found chunk, labelled with its file. - The prompt is a triple-quoted f-string, so it can span several lines and include
contextandquestion. - The three instructions matter. "Only the passages" stops the model answering from what it half-remembers. "Say you don't know" stops it inventing an answer. "Which file" makes it cite its source.
genai.Client()finds your key inGEMINI_API_KEYby itself.gemini-flash-latestalways points to Google's current fast model.
Use it
Replace main.py:
from rag import load_documents, split_into_chunks, embed_chunks, answer
documents = load_documents("data")
chunks = split_into_chunks(documents)
chunk_vectors = embed_chunks(chunks)
print("Ready. Ask about the Brightpath Studio handbook.")
while True:
question = input("\nYour question (press Enter to stop): ")
if question == "":
break
print()
print(answer(question, chunks, chunk_vectors))python main.pyAsk How many days off do I get a year? You should get an answer like:
You should see
You get 24 days of paid annual leave each calendar year. This comes from leave.txt.The exact words will differ, and may differ each time you ask: language models don't repeat themselves word for word. What matters is the 24 days and leave.txt.
Predict, then check
Ask What is the CEO's name? The handbook never mentions a CEO. What should your app say?
Show answerHide answer
That it doesn't know, or that the handbook doesn't say. That's the "say you don't know" instruction working. Without it, a model may invent a name. Try deleting that line from the prompt and asking again.
If you get an error: API key not valid means the key in .env is wrong (no quotes, no spaces). A 429 error means you've hit the free tier's limit for the minute or day: wait and try again.
Practice
Under each answer, print the files the passages came from, so you can check the AI's claim yourself. (Hint: in main.py, import search too, and loop over search(question, chunks, chunk_vectors) after printing the answer.)
Show a solution
from rag import load_documents, split_into_chunks, embed_chunks, search, answer
documents = load_documents("data")
chunks = split_into_chunks(documents)
chunk_vectors = embed_chunks(chunks)
print("Ready. Ask about the Brightpath Studio handbook.")
while True:
question = input("\nYour question (press Enter to stop): ")
if question == "":
break
print()
print(answer(question, chunks, chunk_vectors))
print("Sources:")
for chunk in search(question, chunks, chunk_vectors):
print("-", chunk["source"])This searches twice per question (once inside answer, once here). That's fine for learning; chapter 11 has a neater way to show sources in the app.
Save your progress
git add .
git commit -m "Chapter 8: ask the AI"Run git status once more first, and check .env isn't in the list.
Stuck, or want to compare? The finished code for this chapter is tagged ch08: run git diff ch08, or see it on GitHub.