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

回答 3 浏览 1231 2023-12-14

我正在尝试使用 Google Generative AI gemini-pro 模型和以下 Python 代码,使用 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)

我收到以下错误:

User location is not supported for the API use.

我搜索了官方文档和一些 Google GitHub 存储库,但没有发现任何针对 API 使用的位置限制。我住在欧洲奥地利。

完整回溯:

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.

编辑

我终于找到了"Available regions"。这是侧边栏中的最后一项。截至今天,奥地利尚未出现在名单上。我点击了谷歌网站,没有说明位置限制。至少在官方 Gemini 网页上,他们可以在某处添加一个星号来表明它不是世界各地均可使用。

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

Rok Benko 提问于2023-12-14
3 个回答
#1楼 已采纳
得票数 1

我查看了多个来源,所有迹象都指向同一问题:您可能处于不支持生成式人工智能的位置。当您使用新的 Gemini Pro 时,API 与之前的迭代“PaLM”非常相似,并且它们可能具有相同的区域限制。

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

欧盟往往对新技术有严格的法律和法规,因此这些东西通常需要更长的时间才能在那里推出,以便让公司有时间来确定法律界限。 (例如,我们的人工智能在出现提示时是否会生成受版权保护的作品)。

knutk 提问于2023-12-14
knutk 修改于2023-12-14
你是对的。我住在奥地利,API 尚不可用。我点击了谷歌网站,没有说明位置限制。至少在 Gemini 官方网页上,他们可以在某处添加一个星号来表明它并非在世界各地都可用。不管怎样,谢谢你的帮助。Rok Benko 2023-12-14
我来自捷克共和国,API 运行良好。Extender 2023-12-14
我想使用 Google Generative AI Python SDK。我现在测试了我的脚本,错误仍然出现。Rok Benko 2023-12-17
#2楼
得票数 1

我能够使用来自 EU 的 Gemini Pro(代码是 Node.JS,不是 Python,抱歉)。我相信 API_ENDPOINT 是关键:

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("");
};
Extender 提问于2023-12-14
我想使用 Google Generative AI Python SDK。我现在测试了我的脚本,错误仍然出现。它可能与 Python 或 Node.js 无关。这和你是否使用SDK有关。Rok Benko 2023-12-15
#3楼
得票数 0

如果您的用户位置不受支持,可以通过 VertexAI 库使用另一个区域端点。尽管自定义 API 端点可能是关键,但 google.generativeai 似乎不允许您以相同的方式选择区域。

# 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)
Olivier Simard-Hanley 提问于2023-12-15
我想使用 Google Generative AI Python SDK。我现在测试了我的脚本,错误仍然出现。Rok Benko 2023-12-17