Gemini API Getting Started with Python: google-genai Guide for 2026

The Gemini API gives developers programmatic access to Google’s Gemini models, and for Python the route in 2026 is the google-genai SDK. Google’s lineup has moved quickly: the Gemini 3.x family is established, and Gemini 4 Argon arrived as the new flagship in October. This guide takes you from an empty folder to a working application: getting an API key, installing the right package, making your first request, choosing a model, streaming, chat, structured output, token counting, and the mistakes that trip up beginners.

Get an API Key

Sign in to Google AI Studio with a Google account and create an API key. Store it as an environment variable named GEMINI_API_KEY, which the SDK reads automatically, and never paste it into source code or commit it to a repository. Google offers a free tier for some models, which is excellent for learning and prototyping, but free-tier availability, limits, and the way data may be used differ by model and by region, so read the current pricing and terms pages before building anything you plan to ship. For production workloads you will normally enable billing on a paid tier.

Install the Right Package

This is the most common source of confusion. Google has had two Python libraries. The older one, google-generativeai, is a legacy package that does not support newer Gemini features, and many tutorials still show it. The current one is google-genai, which supports the latest models and features and also works with Vertex AI. Install the new one and remove the old one from your project if you migrated.

pip install -U google-genai
export GEMINI_API_KEY="your-api-key"

The package name has a hyphen, while the import is from google import genai. If a tutorial begins with import google.generativeai as genai, it is describing the legacy library.

Your First Request

Create a client and call generate_content on its models interface with a model ID and your prompt. The response object has a text property containing the generated answer.

from google import genai

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Explain how embeddings work in three sentences.",
)
print(response.text)

The model ID in this example follows Google’s current documentation, but identifiers change as new models arrive and older ones are retired, so check the models page before hard-coding one. At the time of writing, Google’s deprecations page recommends its 3.8 Flash and 3.5 Flash-Lite models for new projects, and keep the ID in configuration rather than scattered through your code.

Choosing a Model

Google offers models in tiers. A flagship reasoning model handles the hardest tasks such as complex coding, scientific reasoning, and long multi-step agent work. A fast general-purpose Flash model covers most everyday needs at lower cost and latency. A Flash-Lite model targets high-volume, low-cost work such as classification and extraction. Start with the middle tier, build a small test set from your real inputs, and only move up if quality demands it or down if you can save money without losing accuracy.

Figure 1 — Gemini model tiers and when to use them

Tier Example model ID Best for Flagshipgemini-4-argonHard reasoning, coding, agents Flashgemini-3.8-flashEveryday apps, balanced cost Flash-Litegemini-3.1-flash-liteHigh-volume, low-cost tasks

These identifiers come from Google’s documentation at the time of writing. Model names and availability change often, so confirm them on the models page.

Controlling Reasoning Effort

Current Gemini models can think before answering, and the API lets you influence how much. Gemini 3 models expose a thinking level setting that trades speed and cost against depth, with lower levels for simple, latency-sensitive requests and higher levels for hard problems. Earlier models used a numeric thinking budget instead, so the parameter you use depends on the model. Thinking tokens count toward usage, which is one reason a seemingly short answer can cost more than you expect. Check the model’s page for the exact parameter names and defaults before tuning.

Streaming Responses

For chat interfaces, stream the answer so users see text immediately. Use generate_content_stream, which returns an iterator of chunks, each with a text property.

for chunk in client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="Write a short product description for a smart water bottle.",
):
    print(chunk.text, end="")

Multi-Turn Chat

For conversations, create a chat session that keeps the history for you. Each send_message call includes the earlier turns automatically.

chat = client.chats.create(model="gemini-3.8-flash")
print(chat.send_message("Suggest three names for a hiking app.").text)
print(chat.send_message("Make them shorter.").text)

If you manage history yourself instead of using a chat object, remember that Gemini 3 models use thought signatures to preserve reasoning context across calls. Google’s guidance is to pass back the full, unmodified conversation history, including those signatures, in the contents parameter. Stripping or rewriting model turns can degrade multi-step behaviour, particularly with function calling.

System Instructions and Configuration

Settings such as the system instruction and output length go in a GenerateContentConfig object from the types module. A system instruction sets the persona and rules that apply to the whole conversation.

from google.genai import types

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Summarise the benefits of unit testing.",
    config=types.GenerateContentConfig(
        system_instruction="You are a concise technical writer.",
        max_output_tokens=300,
    ),
)

Be cautious about sampling parameters. Google’s guidance for newer reasoning-oriented models has been to leave settings such as temperature at their defaults unless you have a measured reason to change them, because altering them can affect reasoning quality.

Structured Output

When your code needs data rather than prose, ask for JSON that matches a schema. Define a Pydantic model, set the response MIME type to JSON, and pass the model as the response schema. The SDK returns the JSON text, and you can read a parsed object from the response.

from pydantic import BaseModel
from google.genai import types

class Recipe(BaseModel):
    name: str
    ingredients: list[str]

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Give me a simple pancake recipe.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=Recipe,
    ),
)
print(response.parsed)

Newer Gemini 3 models also let you combine structured output with built-in tools such as grounding with Google Search and function calling, which is useful for agents that must return predictable data after looking something up.

Images, Audio, Video, and Documents

Gemini is multimodal by design. You can pass images, audio, video, and PDFs in the contents list alongside text. Small files can be sent inline, while larger media should be uploaded with the Files API and then referenced in the request. Multimodal prompts are priced and limited by tokens just like text, and video and audio consume many tokens, so measure before running large jobs.

Counting Tokens and Managing Cost

Use the count_tokens method to see how large a request is before you send it, which prevents surprise bills and context errors. Read the usage metadata on each response to log input, output, and thinking tokens. Google’s newest flagship applies automatic caching to repeated prompt prefixes, so keep long, stable instructions at the start of the prompt and the variable part at the end. Batch and flex processing modes offer discounted pricing for work that can wait. Pricing and introductory offers change, and Google has described introductory rates for its newest model that are scheduled to end, so always confirm current rates on the pricing page rather than relying on an article.

Gemini API or Vertex AI

The same SDK works with both Google AI Studio’s Gemini API and Google Cloud’s Vertex AI. For Vertex AI you create the client with the Vertex option enabled and supply your Google Cloud project and location, then use the same generate_content calls. Choose the Gemini API for fast prototyping and simple billing, and Vertex AI when you need Google Cloud’s identity, networking, data governance, and enterprise controls.

Handling Errors and Rate Limits

Expect rate limit errors, especially on the free tier, and transient server errors during busy periods. Retry with exponential backoff and a small cap, avoid retrying invalid requests, and read the error message for which limit you hit. Keep your own timeout, and for large offline jobs prefer batch processing to avoid real-time limits.

Common Mistakes

  • Using the legacy package. Install google-genai, not google-generativeai, for current models and features.
  • Hard-coding model IDs. Keep them in configuration, since they change.
  • Ignoring thinking tokens. They count toward cost and latency.
  • Rewriting conversation history. Pass history back unmodified for Gemini 3 and later.
  • Committing API keys. Use environment variables or a secrets manager.
  • Skipping token counts. Check size before sending large documents or media.

Frequently Asked Questions

Is the Gemini API free?
Google offers a free tier for some models, with limits that vary by model and region. Paid tiers apply for higher usage and for production. Check the pricing page for current details.
Which Python package should I use?
Use google-genai. The older google-generativeai package is a legacy library that does not support newer features.
Which model should I start with?
Start with a Flash model for general use, test on your own examples, and move to the flagship only for tasks that need deeper reasoning.
Can I use Gemini with the OpenAI library?
Google offers an OpenAI-compatible endpoint, and various gateways expose Gemini that way, but the native SDK gives you the full feature set, including thinking controls and the Files API.

Last updated: November 2026. Gemini models, SDKs, and pricing change frequently, so confirm details in Google’s Gemini API documentation.

A Minimal Project Structure

As soon as your script grows beyond a single call, give it a little structure. Keep the client creation in one small module so that the API key, the default model, and any shared configuration live in a single place. Store model IDs and prompts in a configuration file or constants rather than inside functions, which makes it easy to test a different model without editing logic. Wrap each Gemini call in a function that logs the model, the token usage reported in the response metadata, the latency, and any error, so you have the data you need to control cost and diagnose problems. Add a few automated tests that send representative prompts and check the shape of the output, and run them whenever you change a prompt, a schema, or a model. These habits cost almost nothing at the start and prevent the confusion that appears when a prototype quietly becomes a production service.

Finally, pin the version of the google-genai package in your requirements file. The SDK is updated frequently as new models and features arrive, and pinning lets you upgrade deliberately, reading the release notes and rerunning your tests, instead of discovering a behaviour change after a routine reinstall.

Leave a Comment