非交互式后端调用Google Imagen API的认证问题求助
非交互式后端调用Imagen VQA API的认证解决方案
问题根源
- 401错误:用了不支持的令牌类型。
gcloud auth print-access-token拿的是用户OAuth令牌,这类令牌不适合非交互式后端场景,Vertex AI API只认服务账号令牌或者GCP环境的默认凭证。 - 403错误:你错误地把access token当成refresh token激活,导致权限无效;就算用户令牌有效,也大概率缺少Vertex AI Predict的核心权限。
正确的非交互式认证方案
方案1:后端在GCP环境(优先用这个)
如果你的后端跑在GCE、GKE、Cloud Function、Cloud Run这类GCP托管服务上,不用手动折腾令牌,直接用默认服务账号凭证:
import requests from google.auth import compute_engine from google.auth.transport.requests import Request # 获取默认服务账号凭证 credentials = compute_engine.Credentials() # 刷新凭证拿到有效token credentials.refresh(Request()) base64_string = base64_bytes.decode(ENCODING) VQA_PROMPT = "Describe the content of the image in great detail" payload = { "instances": [ { "prompt": VQA_PROMPT, "image": { "bytesBase64Encoded": base64_string } } ], "parameters": parameters } url = "https://us-central1-aiplatform.googleapis.com/v1/projects/gdg-demos/locations/us-central1/publishers/google/models/imagetext:predict" headers = { "Authorization": f"Bearer {credentials.token}", "Accept": "application/json; charset=utf-8", } json_data = requests.post(url, headers=headers, json=payload)
记得给运行后端的GCP服务默认账号配Vertex AI User(roles/aiplatform.user)或者Vertex AI Predictor(roles/aiplatform.predictor)权限。
方案2:后端在外部环境(非GCP)
得用服务账号密钥文件来认证:
- 去GCP控制台创建一个服务账号,下载JSON格式的密钥文件。
- 给这个服务账号分配
Vertex AI User或者Vertex AI Predictor权限。 - 代码里加载密钥文件拿凭证:
import requests from google.oauth2 import service_account from google.auth.transport.requests import Request # 加载本地的服务账号密钥文件 credentials = service_account.Credentials.from_service_account_file( "/path/to/your/service-account-key.json", scopes=["https://www.googleapis.com/auth/cloud-platform"] ) # 刷新凭证获取有效token credentials.refresh(Request()) base64_string = base64_bytes.decode(ENCODING) VQA_PROMPT = "Describe the content of the image in great detail" payload = { "instances": [ { "prompt": VQA_PROMPT, "image": { "bytesBase64Encoded": base64_string } } ], "parameters": parameters } url = "https://us-central1-aiplatform.googleapis.com/v1/projects/gdg-demos/locations/us-central1/publishers/google/models/imagetext:predict" headers = { "Authorization": f"Bearer {credentials.token}", "Accept": "application/json; charset=utf-8", } json_data = requests.post(url, headers=headers, json=payload)
嫌写路径麻烦的话,也可以设置环境变量GOOGLE_APPLICATION_CREDENTIALS指向密钥文件路径,代码能自动加载:
import requests from google.auth import default from google.auth.transport.requests import Request # 自动从环境变量读取凭证 credentials, project_id = default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) credentials.refresh(Request()) # 后续请求代码和上面一样
必做权限检查
不管用哪种方案,都要确认:
- 所用的服务账号有
aiplatform.predictions.create权限(上面提到的两个角色已经包含这个权限) - 项目
gdg-demos已经启用了Vertex AI API
内容的提问来源于stack exchange,提问作者Csaba Toth
相关产品推荐
相关产品推荐

