Google Generative AI API error: "User location is not supported for the API use."

7.1k views Asked by At

I'm trying to use the Google Generative AI gemini-pro model with the following Python code using the Google Generative AI Python SDK:

import google.generativeai as genai
import os

genai.configure(api_key=os.environ['GOOGLE_CLOUD_API_KEY'])

model = genai.GenerativeModel('gemini-pro')
response = model.generate_content('Say this is a test')

print(response.text)

I'm getting the following error:

User location is not supported for the API use.

I've searched the official documentation and a few Google GitHub repositories for a while but haven't found any location restrictions stated for API usage. I live in Austria, Europe.

Full traceback:

Traceback (most recent call last):
  File "C:\Users\xxxxx\Desktop\gemini-pro.py", line 7, in <module>
    response = model.generate_content('Say this is a test')
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\google\generativeai\generative_models.py", line 243, in generate_content
    response = self._client.generate_content(request)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\google\ai\generativelanguage_v1beta\services\generative_service\client.py", line 566, in generate_content
    response = rpc(
  File "C:\Users\xxxxx\AppData\Roaming\Python\Python310\site-packages\google\api_core\gapic_v1\method.py", line 131, in __call__
    return wrapped_func(*args, **kwargs)
  File "C:\Users\xxxxx\AppData\Roaming\Python\Python310\site-packages\google\api_core\retry.py", line 372, in retry_wrapped_func
    return retry_target(
  File "C:\Users\xxxxx\AppData\Roaming\Python\Python310\site-packages\google\api_core\retry.py", line 207, in retry_target
    result = target()
  File "C:\Users\xxxxx\AppData\Roaming\Python\Python310\site-packages\google\api_core\timeout.py", line 120, in func_with_timeout
    return func(*args, **kwargs)
  File "C:\Users\xxxxx\AppData\Roaming\Python\Python310\site-packages\google\api_core\grpc_helpers.py", line 81, in error_remapped_callable
    raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.FailedPrecondition: 400 User location is not supported for the API use.

EDIT

I finally found the "Available regions". It's the last item in the sidebar. As of today, Austria is not on the list. I clicked through Google websites, and there were no location restrictions stated. At least on the official Gemini webpage, they could have added an asterisk somewhere to indicate that it is not available everywhere in the world.

The Gemini API and Google AI Studio are available in the following countries and territories:

Algeria American Samoa Angola Anguilla Antarctica Antigua and Barbuda Argentina Armenia Aruba Australia Azerbaijan The Bahamas Bahrain Bangladesh Barbados Belize Benin Bermuda Bhutan Bolivia Botswana Brazil British Indian Ocean Territory British Virgin Islands Brunei Burkina Faso Burundi Cabo Verde Cambodia Cameroon Caribbean Netherlands Cayman Islands Central African Republic Chad Chile Christmas Island Cocos (Keeling) Islands Colombia Comoros Cook Islands Côte d'Ivoire Costa Rica Curaçao Democratic Republic of the Congo Djibouti Dominica Dominican Republic Ecuador Egypt El Salvador Equatorial Guinea Eritrea Eswatini Ethiopia Falkland Islands (Islas Malvinas) Fiji Gabon The Gambia Georgia Ghana Gibraltar Grenada Guam Guatemala Guernsey Guinea Guinea-Bissau Guyana Haiti Heard Island and McDonald Islands Honduras India Indonesia Iraq Isle of Man Israel Jamaica Japan Jersey Jordan Kazakhstan Kenya Kiribati Kyrgyzstan Kuwait Laos Lebanon Lesotho Liberia Libya Madagascar Malawi Malaysia Maldives Mali Marshall Islands Mauritania Mauritius Mexico Micronesia Mongolia Montserrat Morocco Mozambique Namibia Nauru Nepal New Caledonia New Zealand Nicaragua Niger Nigeria Niue Norfolk Island Northern Mariana Islands Oman Pakistan Palau Palestine Panama Papua New Guinea Paraguay Peru Philippines Pitcairn Islands Puerto Rico Qatar Republic of the Congo Rwanda Saint Barthélemy Saint Kitts and Nevis Saint Lucia Saint Pierre and Miquelon Saint Vincent and the Grenadines Saint Helena, Ascension and Tristan da Cunha Samoa São Tomé and Príncipe Saudi Arabia Senegal Seychelles Sierra Leone Singapore Solomon Islands Somalia South Africa South Georgia and the South Sandwich Islands South Korea South Sudan Sri Lanka Sudan Suriname Taiwan Tajikistan Tanzania Thailand Timor-Leste Togo Tokelau Tonga Trinidad and Tobago Tunisia Türkiye Turkmenistan Turks and Caicos Islands Tuvalu Uganda United Arab Emirates United States United States Minor Outlying Islands U.S. Virgin Islands Uruguay Uzbekistan Vanuatu Venezuela Vietnam Wallis and Futuna Western Sahara Yemen Zambia Zimbabwe

4

There are 4 answers

4
knutk On BEST ANSWER

I've looked at multiple sources and all signs point to the same issue: You're likely in a location where the generative AI isn't supported. While you're using the new Gemini Pro, the API is very similar to the previous iteration "PaLM", and they likely have the same regional limitations.

https://www.googlecloudcommunity.com/gc/AI-ML/When-has-europe-access-to-PALM-and-Makersuite/m-p/644100

Error message (FailedPrecondition: 400 User location is not supported for the API use.) when using the 51GB Google Colab runtime and Palm API

EU tends to have stringent laws and regulations around new technology, so it usually takes longer for these things to roll out there to give companies time to work out the legal boundaries. (E.g does our AI produce copyrighted works when prompted).

1
Olivier Simard-Hanley On

There is a way to use another regional endpoint through the VertexAI library if your user location is not supported. It seems the google.generativeai does not let you select a region the same way, although customizing the API endpoint might be key.

# Drawn from https://cloud.google.com/vertex-ai/docs/generative-ai/migrate/migrate-palm-to-gemini
import os
import json

import vertexai
from vertexai.preview.generative_models import GenerativeModel
from google.oauth2.service_account import Credentials
from dotenv import load_dotenv

load_dotenv()

PROJECT = "..."
LOCATION = "us-central1"

# Import credentials 
service_account_json_string = os.getenv('GCP_SERVICE_ACCOUNT_JSON')
service_account_info = json.loads(service_account_json_string)
google_credentials = Credentials.from_service_account_info(service_account_info)


# Initialize Vertex AI
vertexai.init(project=PROJECT, location=LOCATION, credentials=google_credentials)

# Start prediction
model = GenerativeModel("gemini-pro")

responses = model.generate_content("The sun's colour is ", stream=True)

for response in responses:
    print(response.text)
1
Extender On

I was able to use Gemini Pro from EU (code is Node.JS, not Python, sorry). I believe API_ENDPOINT is the key:

import { JWT } from "google-auth-library";
import dotenv from "dotenv";
dotenv.config({ override: true });

const API_ENDPOINT = "us-central1-aiplatform.googleapis.com";
const URL = `https://${API_ENDPOINT}/v1beta1/projects/${process.env.GOOGLE_KEY}/locations/us-central1/publishers/google/models/gemini-pro:streamGenerateContent`;

export const getIdToken = async () => {
    const client = new JWT({
        keyFile: "./google.json",
        scopes: [
            "https://www.googleapis.com/auth/cloud-platform",
        ],
    });
    const idToken = await client.authorize();
    return idToken.access_token;
};

export const getTextGemini = async (prompt, temperature) => {
    const headers = {
        Authorization: `Bearer ` + (await getIdToken()),
        "Content-Type": "application/json",
    };

    const data = {
        contents: [
            {
                role: "user",
                parts: [
                    {
                        text: prompt,
                    },
                ],
            },
        ],
        generation_config: {
            maxOutputTokens: 2048,
            temperature: temperature || 0.5,
            topP: 0.8,
        },
    };

    const response = await fetch(URL, {
        method: "POST",
        headers,
        body: JSON.stringify(data),
    });

    if (!response.ok) {
        console.error(response.statusText);
        throw new Error("Request failed " + response.statusText);
    }

    const result = await response.json();
    return result.map((r) => r?.candidates?.[0]?.content?.parts?.[0]?.text).join("");
};
0
anjhon On

Using a proxy will, the node of the proxy selects the United States and is set in the code to use this proxy when requested.

import os
os.environ["http_proxy"] = 'http://localhost:7890'
os.environ["https_proxy"] = 'http://localhost:7890'