Make a Gemini Interactions request through the official Python SDK with an environment-loaded credential and a timeout. Inspect output, usage and the deliberate wrong-model failure separately.

What you’ll build

The current Google quickstart uses google-genai and client.interactions.create. This sample follows that path with a small text request. Official documentation.

The program establishes a narrow Interactions baseline: an authorized project credential, a documented model, a short text input and visible output plus usage. It does not add media, grounding or a persistent conversation. That limited scope is useful because later failures can be compared against a request whose moving parts are understood.

Define the acceptance target before running it. A completed response establishes basic access and result handling. An understandable answer shows that the text output was read correctly. Neither proves the quality of a future document or image application. Keep that broader evaluation as a separate next step rather than presenting the demonstration as a production benchmark.

Prerequisites

Follow the Gemini key guide and verify the project can access the selected model.

Create a dedicated working directory and verify the Python interpreter used by your terminal. Keep the script and safe test fixtures together. Avoid using a session that already contains credentials or client objects from another Google project, since hidden state makes a failed example harder to explain.

Configure the intended authorization key through protected environment settings and check its presence without printing its value. Confirm the project can access the selected model and that the intended inference use is authorized. Record the project owner and stop procedure before connecting any scheduled execution.

Install SDK

python -m pip install --upgrade google-genai

Install google-genai in the environment that will execute the program. If an import fails, inspect the interpreter and package location before changing the API configuration. Avoid naming a local file google.py or genai.py, which can shadow the package path and create an apparent SDK failure unrelated to the service.

After the example succeeds, record the package version used. A maintained application should make dependency updates reviewable and rerun its important request fixtures after an update. The fresh-install command is convenient for this tutorial, while a deployed project needs its own reproducible dependency policy.

Full script

import os
import sys
from google import genai
from google.genai import types

model = os.environ.get("GEMINI_MODEL", "gemini-3.8-flash")
if "--bad-model" in sys.argv:
    model = "ai-api-hub-invalid-model"
client = genai.Client(
    api_key=os.environ["GEMINI_API_KEY"],
    http_options=types.HttpOptions(timeout=30000),
)
try:
    result = client.interactions.create(
        model=model, input="Explain multimodal input in a short sentence.", store=False
    )
    print(result.output_text)
    print(result.usage)
except Exception as exc:
    print(type(exc).__name__)
    print(str(exc))
    raise SystemExit(1)
finally:
    client.close()

Read the explicit project-key environment variable and model selection before execution. The bad-model branch changes only the identifier, leaving access and the basic input shape unchanged. This makes the deliberate failure easier to interpret than an example that changes multiple parts of the request at once.

The HTTP options include a timeout so the diagnostic program has a defined wait boundary. The script prints output separately from usage and closes the client afterward. Keep that separation when recording evaluation results: content quality, resource use and request completion are different observations. If extending the program, review the response handling for the new media or stateful feature rather than assuming it behaves like the text-only example.

Expected output

This is schematic output, not a captured API result. The actual usage object and wording depend on your request.

A brief explanation of multimodal input.
A usage object returned by the service.

The example output is schematic and is not an observed provider result. Your response will have service-generated metadata and model-generated wording. Judge whether the result satisfies the small task rather than requiring an exact match to the illustrative sentence.

Save the model identifier, interface, prompt revision, SDK version and returned usage with the result. Remove sensitive input before sharing diagnostics. If the program prints an exception instead of an answer, investigate it as a failed request or result-processing condition. The presence of terminal output alone is not a successful model call.

One deliberate error and its fix

python first_google.py --bad-model

The branch sends ai-api-hub-invalid-model instead of the normal model identifier. Keep the credential configured so the request reaches model validation. The script exposes the returned rejection and stops; restore the ordinary command to use the supported model again.

The following error-field excerpt was captured on 2026-09-12 15:53 UTC from an authorized HTTP request to the same provider interface. It used harmless connection-validation input and small output settings. This records the provider’s rejection; it does not claim that the Python SDK example itself was executed.

These are normalized captured fields with the message preserved verbatim. They are not a reconstructed full provider response envelope. Empty fields and request identifiers are omitted.

{
  "http_status": 404,
  "code": "not_found",
  "message": "Model 'ai-api-hub-invalid-model' not found. Did you mean 'gemini-3.1-flash-lite-image'? Please verify the model name against the supported list: https://ai.google.dev/gemini-api/docs/models"
}

Fix the deliberate error by restoring a current accessible model identifier. Do not resend the invalid identifier in a retry loop. If the ordinary request also fails, inspect that response independently because permission, funding and request validation can fail at different stages. Official error reference.

Keep the missing-key startup check as an additional local configuration guard. It tests whether the process can read its environment; it does not establish that the provider accepted the key or evaluated the requested model.

What this request costs

Interactive tool

Estimate your API costs

Your text and estimates stay in this browser. No API requests are sent to model providers.

Loading verified model records…

Use the returned usage with the Gemini cost calculator.

Keep the returned usage attached to the exact model and text-only request path used here. If you introduce image input, generated media, grounding or another hosted feature, inspect the corresponding charge categories before reusing the original estimate. Do not force a media charge into a text-token assumption merely because the calculator has convenient token fields.

Collect representative application fixtures before forecasting ongoing usage. Include accepted and rejected outcomes, and record any repair work needed for a useful result. Keep conservative assumptions for cases not yet measured. The calculator can explain those assumptions, but it cannot establish billing evidence for a workload that has not been evaluated.

Next steps

Add a representative evaluation before introducing media, state or tools. Consult Gemini errors if the request fails, and check interface support before adopting cache or batch features.

Add an application-specific evaluation pack before expanding the feature set. Keep the original text request as a diagnostic baseline, then introduce the needed input type or conversation behavior deliberately. Verify media preparation and result parsing alongside the model call so an apparent quality change can be traced to the correct layer.

Check interface eligibility before adopting explicit caching or batch processing. Before unattended operation, define retry ownership, protected logging and a clear stop condition. Document authorization-key rotation and project ownership. Another maintainer should be able to reproduce the normal path, explain the deliberate failure and identify which parts of the intended application remain untested.

Last verified · Source ↗

Frequently asked questions

Which Gemini client does the tutorial use?
The official google-genai Python package and its Interactions interface. Official documentation.
Do separate keys create separate project capacity?
No. The rate-limit documentation applies quotas per project. Official documentation.
Where should I inspect model availability?
Use the current model catalog and the access available to your project. Official documentation.
Can I assume a free tier covers every modality?
No. Check the specific model and feature columns in the pricing reference. Official documentation.
How do I troubleshoot a key that used to work?
Inspect key type, restrictions and project access in the current API-key guide. Official documentation.

Sources

Last verified · Source ↗