stock-ai-agent/diagnose_api_key.py
2026-02-03 10:27:04 +08:00

83 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
诊断脚本检查智谱AI API Key配置
"""
import os
import sys
from pathlib import Path
# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent / 'backend'))
from app.config import get_settings
def main():
print("=" * 60)
print("智谱AI API Key 诊断")
print("=" * 60)
# 检查当前工作目录
print(f"\n当前工作目录: {Path.cwd()}")
# 检查.env文件
env_files = [
Path.cwd() / ".env",
Path.cwd().parent / ".env",
Path(__file__).parent / ".env"
]
print("\n检查.env文件:")
for env_file in env_files:
if env_file.exists():
print(f" ✓ 找到: {env_file}")
else:
print(f" ✗ 不存在: {env_file}")
# 加载配置
print("\n加载配置...")
try:
settings = get_settings()
print(" ✓ 配置加载成功")
except Exception as e:
print(f" ✗ 配置加载失败: {e}")
return
# 检查API Key
print("\nAPI Key 检查:")
api_key = settings.zhipuai_api_key
if not api_key:
print(" ✗ API Key 为空")
return
print(f" ✓ API Key 已设置")
print(f" - 长度: {len(api_key)}")
print(f" - 前10位: {api_key[:10]}...")
print(f" - 后10位: ...{api_key[-10:]}")
# 检查格式
if '.' in api_key:
parts = api_key.split('.')
print(f" ✓ 包含'.'分隔符,分为{len(parts)}部分")
for i, part in enumerate(parts):
print(f" 部分{i+1}: {len(part)}字符")
else:
print(" ✗ 缺少'.'分隔符智谱AI Key应该包含'.'")
# 尝试初始化客户端
print("\n尝试初始化智谱AI客户端...")
try:
from zhipuai import ZhipuAI
client = ZhipuAI(api_key=api_key)
print(" ✓ 客户端初始化成功")
except Exception as e:
print(f" ✗ 客户端初始化失败: {type(e).__name__}: {e}")
import traceback
print("\n详细错误:")
print(traceback.format_exc())
print("\n" + "=" * 60)
if __name__ == "__main__":
main()