s.ClientError: 401 None. {'error': {'code': '', 'message': 'Invalid Token (reque...
🚨 错误信息
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密钥
AIza开头)第二步:在代码中正确配置
根据您的使用方式选择对应的修复方法:
方案A:环境变量方式(推荐)
bash
在终端设置环境变量
export GOOGLE_API_KEY="AIzaSyD...您的完整密钥..."
python
Python代码中使用
import os
from google import genaiclient = 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.管理最佳实践
2.建议
.env文件配合python-dotenv库管理本地环境变量3脚本
创建简单的验证脚本测试API连接:
python
import os
from google import genaidef 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",并且当前账户有访问权限。