Free lesson · GenAI Agent Engineering

Install Gemini SDK

You will set up the Google Gemini SDK. Install the google-generativeai package, initialize the client with your API key, and verify the connection works.

Course: LLM Foundations for Agent Builders · Chapter 6 · Your First LLM Call

Free to read — no subscription required.

Introduction

When you start wiring a service to Gemini, the first failure point isn't prompt design — it's a misconfigured SDK that fails to authenticate, leaks the API key into logs, or surfaces 401s that look like model errors. Teams that skip a clean install-and-init step end up constructing clients inside request handlers, scattering os.environ.get calls across the codebase, and losing a single place to fix credential issues. By the end of this lesson you'll be able to install the google-genai package, load an API key from environment variables, construct a genai.Client, and verify the connection with a minimal round-trip call.

Key Terminology

  • google-genai — the official Python client library for Gemini models and the only package you need to install for SDK-based access; it replaces the older google-generativeai package and uses a different import path.
  • genai.Client — the top-level SDK object that holds the API key, manages HTTP transport, and exposes models, chats, and other resource namespaces used for every API call in this lesson.
  • GEMINI_API_KEY — the environment variable convention the SDK and tutorials use to pass credentials; keeping it out of source code is the difference between a safe init and a leaked key.
  • python-dotenv — a development helper that loads a local .env file into os.environ so you can keep your key out of shell history without changing application code.
  • generate_content — the SDK method on client.models used here as a smoke test; one successful call confirms install, auth, and network path together.

Concepts

Package selection and install

Gemini's current Python SDK ships as google-genai on PyPI. Install it with pip install google-genai — do not install google-generativeai, which is the older library with a different import path and an incompatible client surface. For local development, install python-dotenv alongside it so you can keep GEMINI_API_KEY in a .env file instead of exporting it in your shell on every session.

Credential loading

The SDK reads no credentials implicitly. You pass the key explicitly to genai.Client(api_key=...). The canonical pattern is to read os.environ.get("GEMINI_API_KEY") and raise immediately if it is missing, so the client never sees a hard-coded string. Never log the key, never commit .env, and never accept a silent fallback — a missing key should fail at construction, not surface later as a confusing 401 inside a real feature.

Client construction as a factory

Construct the client once in a factory function (e.g. create_gemini_client) rather than at every call site. A factory gives you one place to add timeouts, retries, or test stubs later, and it keeps request handlers free of credential plumbing. Concrete mechanics are demonstrated in the Code Walkthrough.

Connection verification

After construction, run a minimal client.models.generate_content call against a cheap model (e.g. gemini-2.0-flash) with a one-word prompt. A successful response proves install, key, network, and model access in a single round-trip — much faster to diagnose than discovering a bad key inside your first real feature.

Loading diagram...

Code Walkthrough

Now that you understand package selection, credential loading, and the factory pattern, the following script assembles all four steps into a single runnable module.

Code snippetpython
1import os 2from dotenv import load_dotenv 3from google import genai 4 5load_dotenv() 6 7def create_gemini_client() -> genai.Client: 8 """Build a configured Gemini client or fail fast if the key is missing.""" 9 api_key = os.environ.get("GEMINI_API_KEY") 10 if not api_key: 11 raise ValueError( 12 "GEMINI_API_KEY not found. Set it in your environment or .env file." 13 ) 14 return genai.Client(api_key=api_key) 15 16def verify_connection(client: genai.Client) -> bool: 17 """Smoke-test the client with a minimal generate_content call.""" 18 try: 19 response = client.models.generate_content( 20 model="gemini-2.0-flash", 21 contents="Say 'connected' in one word.", 22 ) 23 print(f"Connection verified: {response.text.strip()}") 24 return True 25 except Exception as exc: 26 print(f"Connection failed: {exc}") 27 return False 28 29if __name__ == "__main__": 30 client = create_gemini_client() 31 verify_connection(client)

load_dotenv() runs at module import time so .env values are in os.environ before create_gemini_client executes. The factory raises ValueError immediately if GEMINI_API_KEY is absent — a missing key surfaces as a clear message at construction, not later as a confusing 401 inside a real feature. Wrapping client.models.generate_content in a try/except inside verify_connection lets a failed smoke test print a diagnostic and return False rather than crashing the caller, which makes the distinction between install failure, auth failure, and network failure visible at a glance.

Common failure modes and what they signal: if the script prints GEMINI_API_KEY not found, your .env file is not in the working directory or python-dotenv is not installed; a 401 or 403 response means the key is set but invalid; a network error points to egress restrictions rather than an SDK problem.

You'll know it works when the script prints Connection verified: connected (or a similar one-word reply) and exits with status 0.

Do's and Don'ts

Do's

  1. Do load the key from the environment — keep GEMINI_API_KEY in .env (gitignored) or a secret manager so the same code runs locally and in production without edits.
  2. Do construct the client in a factory function — one place to add timeouts, retries, or test doubles later, and request handlers stay free of credential plumbing.
  3. Do run a smoke-test call after init — a single generate_content round-trip catches install, auth, and network issues before they surface inside a real feature.

Don'ts

  1. Don't install google-generativeai — that's the older library; google-genai is the current SDK and the two are not interchangeable.
  2. Don't hard-code the API key in source — even for a quick demo, a committed key is a leaked key, and rotation becomes a code change instead of an env update.
  3. Don't swallow a missing-key error — fail fast at client construction; a silent fallback turns into a confusing 401 deep inside the first real API call.

This lesson is free to read. Its hands-on lab — real code, in a cloud IDE — is part of the GenAI Agent Engineering subscription.

From · cancel anytime

More free lessons in LLM Foundations for Agent Builders

All free lessons in GenAI Agent Engineering