如何用内联凭证(而非文件)通过Python SDK认证Google Gemini Pro Vision AI
解决方案:直接使用内存中的凭证字典创建GCP服务账号凭证
你不需要依赖文件路径来创建GCP服务账号凭证,google.oauth2.service_account.Credentials提供了from_service_account_info()方法,专门用于接收内存中的字典格式凭证信息,完美适配你从Azure Key Vault加载敏感字段后构造的字典。
核心修改点
- 替换
from_service_account_file()为from_service_account_info(),直接传入你构造的gcp_credentials字典 - 确保
private_key字段格式正确(从Key Vault取出时可能丢失换行符,需还原)
修改后的完整代码
import io import json import logging from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient from google.auth.transport.requests import Request from google.oauth2.service_account import Credentials # ---------------------------------------------------------------- AZURE_KEYVAULT_URL = 'https://my-kv-name.vault.azure.net/' GCP_PROJECT_ID = 'my-proj' GCP_REGION = 'my-region' logging.basicConfig(level=logging.INFO) # ---------------------------------------------------------------- def get_secrets_from_key_vault(key_vault_url, secret_names): az_credential = DefaultAzureCredential() secret_client = SecretClient(vault_url=key_vault_url, credential=az_credential) secrets = {} for secret_name in secret_names: secret = secret_client.get_secret(secret_name) secrets[secret_name] = secret.value return secrets # ----------------------------------------------------------------- secret_names = [ 'secret1', 'secret2' ] secret_values = get_secrets_from_key_vault(AZURE_KEYVAULT_URL, secret_names) # 还原private_key的换行符(如果Key Vault存储时丢失的话) private_key = secret_values['secret2'].replace('\\n', '\n') gcp_credentials = { "type": "service_account", "project_id": "vertexai-poc-400414", "private_key_id": secret_values['secret1'], "private_key": private_key, "client_email": "me@cool.com", "client_id": "long-number-here", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/me@cool.com", "universe_domain": "googleapis.com" } # 使用from_service_account_info直接传入字典 gcp_credentials = Credentials.from_service_account_info( gcp_credentials, scopes=['https://www.googleapis.com/auth/cloud-platform'] ) # Handle auth refresh if gcp_credentials.expired: gcp_credentials.refresh(Request())
关键说明
from_service_account_info()的作用:这个方法是Google Auth库专门为内存中的凭证信息设计的,和from_service_account_file()功能完全一致,只是输入源从文件变成了字典。- private_key格式处理:Azure Key Vault存储多行字符串时,可能会将换行符转义为
\n(而非实际换行),所以需要用replace('\\n', '\n')还原成GCP要求的PEM格式,否则会触发认证失败。
内容的提问来源于stack exchange,提问作者ericOnline
相关产品推荐
相关产品推荐

