Google Gen AI Python SDK
The Google Gen AI Python SDK is the google-genai package, imported as from google import genai, that Python apps use to call Gemini with generateContent. Pointed at the Spanway gateway, the app keeps the Gemini request format while the gateway checks a virtual key, applies its budget and rate limit, records the cost and sends the request to the deployment behind the public model name. That deployment can be Gemini on Google AI Studio or Vertex AI, or a model from another provider, such as Claude, translated to and from the Gemini format.
A real-world scenario
A media team tags thousands of images a day with a Python worker built on client.models.generate_content. Each engineer used to test with a personal Google API key, and nobody knew what the worker cost. The admin creates a key named image-tagger with a daily budget and puts the public name gemini-3.8-flash in front of the company's Vertex AI project. The team sets three environment variables and the worker runs unchanged. When the worker's budget is reached for the day, it gets a clear 422 instead of running on, and the Logs page shows which images cost the most.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - A model registered on the gateway under a public name, for example
gemini-3.8-flash. - Python 3.11 or later and the SDK, installed with
pip install --upgrade google-genai.
Make a key for this app
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Details, set Key Name to
image-taggerand leave Key Type on AI APIs. - In Models, pick every public name the worker calls, for example
gemini-3.8-flash, plus any cheaper model it uses for retries or simple cases. - Open Optional Settings, set Max Budget (USD) with Reset Budget, for example 40 USD daily, and a Requests per minute Limit (RPM), for example 300. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (
Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage. - Click Create Key and copy the key. It is shown once.
The same key from the API:
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "image-tagger", "key_type": "llm_api", "models": ["gemini-3.8-flash"], "max_budget": 40, "budget_duration": "24h", "rpm_limit": 300}'
Steps
-
Check the key and the model names. The gateway has no Gemini model list route, so use the OpenAI one.
curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY" -
Set the base URL to the gateway address without any version, and set the API version to
v1beta. The SDK builds/<version>/models/<model>:generateContentitself, and the gateway serves thev1betaform. From version 3 the SDK defaults tov1, which the gateway does not serve forgenerateContent, so the version setting is required.export GOOGLE_GEMINI_BASE_URL="https://gateway.example.com"export GOOGLE_GENAI_API_VERSION="v1beta"export GEMINI_API_KEY="sk-...your virtual key..." -
Make sure
GOOGLE_API_KEYis not set in the same environment. The SDK prefers it overGEMINI_API_KEY, so a real Google key there would be sent to the gateway and rejected with 401. -
Keep
client = genai.Client()as it is, or pass the same values in code as shown below. Values in code win over the environment. -
Use a public model name from step 1 as
model, and find the request on Logs (/ui/logs).
The SDK sends the key in the x-goog-api-key header, which the gateway reads. A base URL that ends in /v1beta makes the SDK call /v1beta/v1beta/..., which fails with 404.
Configuration
import os
from google import genai
from google.genai import types
client = genai.Client(
api_key=os.environ["GEMINI_API_KEY"],
http_options=types.HttpOptions(
base_url="https://gateway.example.com",
api_version="v1beta",
headers={"x-spanway-tags": "app:image-tagger"},
),
)
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="Explain a model group in one sentence.",
)
print(response.text)
headers in HttpOptions sends gateway request headers such as x-spanway-tags, x-spanway-session-id and x-spanway-timeout with every call, see calling the gateway. The async client is client.aio, for example await client.aio.models.generate_content(...).
Expected result
The script prints the answer, and response.usage_metadata holds the token counts the gateway recorded. The response headers are on response.sdk_http_response.headers:
headers = response.sdk_http_response.headers
print(headers.get("x-spanway-call-id"), headers.get("x-spanway-model-group"), headers.get("x-spanway-routing-reason"))
A run against a test gateway printed this.
77733c45-3064-4163-86f7-0ab0a72aa5da gemini-3.8-flash strategy=simple-shuffle
x-spanway-call-id is the id to search for on Logs. x-spanway-model-id names the deployment that answered, x-spanway-attempts counts provider calls and x-spanway-response-cost is the call's cost, see routing decision headers.
On Logs (/ui/logs), click Filters, pick Key Alias = image-tagger and click Apply Filters.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | for chunk in client.models.generate_content_stream(model=..., contents=...): print(chunk.text) | The SDK calls :streamGenerateContent?alt=sse, which the gateway serves for every model behind the name. The last chunk can carry only usage and no text. |
| Function calling | config=types.GenerateContentConfig(tools=[...]) with function declarations or Python functions. | Function declarations and function responses are translated when another provider answers. |
| Images | types.Part.from_bytes(data=..., mime_type="image/png") in contents. | Inline data parts are translated for other providers. The model behind the name must accept images. |
| Structured output | response_mime_type="application/json" with response_schema. | Translated for other providers. |
| Context caching | cached_content in the config. | It names a cache stored at Google, so use it only with a public name that points at Gemini deployments. |
| Thinking | thinking_config=types.ThinkingConfig(...) in the config. | Honoured by Gemini deployments. When another provider answers, it is not translated, so set the reasoning level on that deployment instead. |
| Safety settings | safety_settings in the config. | Honoured by Gemini deployments only. |
| Token counting | client.models.count_tokens(model=..., contents=...) | Served at :countTokens, answers total_tokens. |
| Model list | client.models.list() | Not served. The SDK gets 404. Use GET /v1/models instead. |
The SDK does not retry on its own. To retry 408, 429 and 5xx answers, set retry_options=types.HttpRetryOptions(attempts=3) in HttpOptions. The gateway also has its own retries and fallbacks, so keep the SDK's attempts low.
Errors
Errors the gateway raises come back in the OpenAI shape {"error": {"message": "...", "type": "...", "param": null, "code": "400"}}, with no Google status field. The SDK raises errors.ClientError for any 4xx answer and errors.ServerError for any 5xx answer, both subclasses of errors.APIError. e.code is the HTTP status, e.message the gateway's text and e.details the whole body. Printed, the error reads <status> None. {...body...}, where None is the missing Google status.
| Case | Exception and e.code | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | ClientError 401 | Authentication Error, No api key passed in. | A proxy in between strips the x-goog-api-key header. Check that hop. |
| Wrong or deleted key | ClientError 401 | Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db. | Copy the key again, and check that GOOGLE_API_KEY does not hold a Google key. |
| Blocked key | ClientError 401 | Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin. | Ask the admin to open the key in Virtual Keys and click Unblock Key. |
| Expired key | ClientError 401 | Authentication Error - Expired Key. Key Expiry time <time> and current time <time> | Ask the admin to extend the key or issue a new one. |
| The key may not use the model | ClientError 403 | The requested model '<model>' is not available for this API key, or the model name is invalid. | Add the model to the key in Virtual Keys. |
| The model name is unknown | ClientError 400 | Invalid model name passed in model=<name> | The message starts with agenerate_content:. Use a name from GET /v1/models, typed exactly. |
| The budget is spent | ClientError 422 | Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max> | Wait for the reset or ask for a higher budget. |
| Over the key or team rate limit | ClientError 429 | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Slow down or ask for a higher limit, and set retry_options if the app should wait and retry. |
The SDK uses API version v1 | ClientError 405 | Method Not Allowed | SDK 3 defaults to v1. Set api_version="v1beta" or GOOGLE_GENAI_API_VERSION=v1beta. |
Wrong path, often a doubled /v1beta | ClientError 404 | Not Found | Use the bare gateway address as the base URL. client.models.list() also gets this 404. |
| The provider failed | ServerError 500 to 503 | The provider's own message, followed by the model group that failed | Retry later and ask for a fallback deployment. |
| Nothing listens at the address | ConnectError from the HTTP library | None. [Errno 111] Connection refused on Linux, [Errno 61] on macOS | Check the address, port and that the gateway runs. In Docker use host.docker.internal. The class comes from httpx2 on SDK 3 and httpx before. |
| TLS certificate not trusted | ConnectError | None. The text contains CERTIFICATE_VERIFY_FAILED | Install the company root certificate in the operating system, or set SSL_CERT_FILE to a PEM bundle before the client is created. |
See the client error reference for the same cases in every SDK.
Troubleshooting
- In
except errors.APIError as e:, loge.code,e.messageand, for a failed call, thex-spanway-call-idfrome.response.headers. - Open Logs (
/ui/logs), search for the call id or filter by Key Alias, and open the row for the status, the error, the deployment and the provider's answer. - If the request is not on Logs, it never reached the gateway. Turn on the HTTP library's debug log with
logging.basicConfig(level=logging.DEBUG)to see each URL the SDK calls. A 405 or a path with two versions shows at once. - Check which key the SDK picked up with
print(bool(os.environ.get("GOOGLE_API_KEY"))). If it is set, it wins overGEMINI_API_KEY. - Read
x-spanway-routing-reasonandx-spanway-attemptsfor retries and fallbacks, explained on routing decision headers.
The gateway also offers a Google AI Studio pass-through at https://gateway.example.com/gemini, which forwards every Gemini route to Google unchanged, the model list included. Use it when the app needs Gemini-only features, and the unified route on this page when the public name may point at any provider. More symptoms are in troubleshooting.
Rotation and removal
Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h, and deploy the new key in GEMINI_API_KEY before it ends. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}, which needs an Enterprise license. Without one, create a new key, switch the app and delete the old key.
Block Key (POST /key/block) stops the app at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent. To take the app off the gateway, unset GOOGLE_GEMINI_BASE_URL and set a Google API key again.
Related
- Google Gen AI JavaScript SDK for the same steps in JavaScript and TypeScript.
- Google generateContent for every request field the gateway accepts.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.