Create the Gemini Client
Exit

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_KEY

Add .env to .gitignore so it is never committed:

echo ".env" >> .gitignore

Load 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.

  1. Call load_dotenv().
  2. Create a variable named api_key. Assign it os.getenv("GEMINI_API_KEY").
  3. Create a variable named client. Assign it genai.Client(api_key=api_key).
  4. Return client.