You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain教程使用Gemini-1.5-Flash时遭遇GoogleAuthError求助

解决方案:ChatVertexAI 认证错误 DefaultCredentialsError

问题根源

你混淆了两种Gemini模型的调用逻辑:

  • ChatVertexAI 用于调用Google Cloud Vertex AI平台托管的Gemini模型,依赖Google Cloud的应用默认凭据(ADC)完成认证,不支持直接用GOOGLE_API_KEY;
  • 直接使用GOOGLE_API_KEY的场景,对应调用Gemini公开REST API,LangChain中需用ChatGoogleGenerativeAI类。

具体解决方法

方法1:切换适配API KEY的模型类(最快实现)

如果不想配置Google Cloud凭据,直接用已有的GOOGLE_API_KEY,替换代码中的模型初始化逻辑:

from langchain_google_genai import ChatGoogleGenerativeAI
import os
from dotenv import load_dotenv

load_dotenv()
llm = ChatGoogleGenerativeAI(
    model="gemini-1.5-flash",
    google_api_key=os.getenv("GOOGLE_API_KEY")
)

方法2:配置Google Cloud应用默认凭据(适配ChatVertexAI)

若坚持使用ChatVertexAI,需完成本地凭据配置:

  • 安装Google Cloud CLI(gcloud)工具;
  • 在终端执行命令:
    gcloud auth application-default login
    
  • 按照浏览器引导登录你的Google Cloud账户,完成后Jupyter会自动读取生成的本地凭据文件;
  • 确保你的Google Cloud项目已启用Vertex AI API,且登录账户拥有Vertex AI User(roles/aiplatform.user)权限。

方法3:使用服务账号密钥文件(适合无交互/生产场景)

  • 在Google Cloud控制台创建服务账号,分配Vertex AI User权限,下载JSON格式的密钥文件;
  • 在Jupyter中设置环境变量指向密钥文件:
    import os
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/绝对路径/到/你的服务账号密钥.json"
    
  • 重新初始化ChatVertexAI即可正常运行。

内容的提问来源于stack exchange,提问作者punsoca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:42:04