Create the Gemini Client
Read the API key from the environment and instantiate the Gemini client
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Keeping your API key out of source code
Never hardcode an API key in a Python file. If you commit that file to git, your key is exposed — even if you delete it later, it remains in the commit history.
The safe pattern: store the key in a .env file, load it with python-dotenv, and read it with os.getenv().
Create a .env file in your pdf-rag folder:
GEMINI_API_KEY=YOUR_API_KEYAdd .env to .gitignore so it is never committed:
echo ".env" >> .gitignoreLoad and read the key in Python:
import os
from dotenv import load_dotenv
from google import genai
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)load_dotenv() reads the .env file and adds its values to the environment. os.getenv() retrieves them by name.
Instructions
Complete the create_client function. The starter code provides the signature.
- Call
load_dotenv(). - Create a variable named
api_key. Assign itos.getenv("GEMINI_API_KEY"). - Create a variable named
client. Assign itgenai.Client(api_key=api_key). - Return
client.
import os
import pypdf
from dotenv import load_dotenv
from google import genai
def extract_text(pdf_path):
reader = pypdf.PdfReader(pdf_path)
pages = [page.extract_text() for page in reader.pages]
return "\n".join(pages)
def chunk_text(text, chunk_size=500, overlap=100):
chunks = []
for i in range(0, len(text), chunk_size - overlap):
chunks.append(text[i : i + chunk_size])
return chunks
def preview_chunks(chunks):
print(f"Total chunks: {len(chunks)}")
print(f"First chunk:\n{chunks[0]}")
def create_client():
# Step 1: Call load_dotenv()
# Step 2: Get API key from environment
# Step 3: Create Gemini client
# Step 4: Return client
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding