s.ClientError: 401 None. {'error': {'code': '', 'message': 'Invalid Token (reque...

2026年01月25日 10:52 状态: processing

🚨 错误信息

google.genai.errors.ClientError: 401 None. {'error': {'code': '', 'message': 'Invalid Token (request id: 20260125104701610704113B9jrVC7u)', 'type': 'rix_api_error'}}

🤖 AI解决方案

代码糕手 - 专业报错分析报告 错误翻译


plaintext
原文:Invalid Token (request id: 20260125104701610704113B9jrVC7u)
译文:令牌无效(请求ID: 20260125104701610704113B9jrVC7u)

##原因分析
这是一个Google Gemini API(GENAI)的认证错误,HTTP状态码为401(未授权)。错误明确表明您提供给Google AI API的访问令牌(API Key)无效或已失效。可能的原因包括:

  • API密钥不存在 – 提供的字符串不是有效的Google AI API密钥

  • API密钥已过期 – 密钥有效期已到

  • API密钥被禁用 – 在Google AI Studio中被手动禁用

  • 密钥格式错误 – 复制粘贴时包含了空格或特殊字符

  • 环境变量未正确设置 – 代码引用的环境变量值为空或错误
  • 解决方案

    第一步:获取新的API密钥


  • 访问 [Google AI Studio](https://makersuite.google.com/app/apikey)

  • 登录您的Google账户

  • 点击"Create API Key"生成新的密钥

  • 复制完整密钥(以AIza开头)
  • 第二步:在代码中正确配置


    根据您的使用方式选择对应的修复方法:

    方案A:环境变量方式(推荐)

    bash

    在终端设置环境变量


    export GOOGLE_API_KEY="AIzaSyD...您的完整密钥..."

    python

    Python代码中使用


    import os
    from google import genai

    client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))

    方案B:直接配置方式

    python
    from google import genai

    直接将有效密钥放入代码


    client = genai.Client(api_key="AIzaSyD...您的完整密钥...")

    或从配置文件读取


    import json
    with open('config.json', 'r') as f:
    config = json.load(f)
    client = genai.Client(api_key=config["google_api_key"])

    预防措施

    1.管理最佳实践


  • 使用环境变量:永远不要将API密钥硬编码在源代码中

  • 密钥轮换:定期更新API密钥,特别是在团队成员变动后

  • 权限最小化:仅为API密钥分配必要的权限
  • 2.建议


  • 使用.env文件配合python-dotenv库管理本地环境变量

  • 在代码中添加密钥验证逻辑,启动时检查API密钥有效性

  • 使用密钥管理服务(如AWS Secrets Manager、Google Secret Manager)生产环境
  • 3脚本


    创建简单的验证脚本测试API连接:
    python
    import os
    from google import genai

    def test_api_key(api_key):
    try:
    client = genai.Client(api_key=api_key)
    response = client.models.list()
    print("✅ API密钥有效,连接成功!")
    return True
    except Exception as e:
    print(f"❌ API密钥无效: {e}")
    return False

    测试


    if __name__ == "__main__":
    api_key = os.environ.get("GOOGLE_API_KEY")
    test_api_key(api_key)

    ---
    提示:确保您的Google Cloud项目中已启用"Generative Language API",并且当前账户有访问权限。