98 lines
2.8 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.

"""
测试硅基流动API连接
"""
import os
from dotenv import load_dotenv
import requests
# 加载环境变量
load_dotenv()
def test_siliconflow_api():
"""测试硅基流动API连接"""
print("="*80)
print("测试硅基流动API连接")
print("="*80)
print()
# 读取配置
api_key = os.getenv('SILICONFLOW_API_KEY')
model = os.getenv('SILICONFLOW_MODEL', 'deepseek-ai/DeepSeek-V3.2-Exp')
api_url = "https://api.siliconflow.cn/v1/chat/completions"
# 检查配置
print("1. 检查配置...")
if not api_key:
print(" ✗ 错误: 未找到 SILICONFLOW_API_KEY")
print(" 请在 .env 文件中设置: SILICONFLOW_API_KEY=你的API密钥")
return False
print(f" ✓ API密钥: {api_key[:10]}...{api_key[-5:]}")
print(f" ✓ 模型: {model}")
print(f" ✓ API地址: {api_url}")
print()
# 测试API调用
print("2. 测试API调用...")
try:
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": "请回复'测试成功'"
}
],
"max_tokens": 20
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
print(" 正在发送请求...")
response = requests.post(
api_url,
json=payload,
headers=headers,
timeout=30
)
print(f" 响应状态码: {response.status_code}")
if response.status_code == 200:
result = response.json()
if 'choices' in result and len(result['choices']) > 0:
content = result['choices'][0]['message']['content']
print(f" ✓ API调用成功")
print(f" 响应内容: {content}")
return True
else:
print(f" ✗ API响应格式异常: {result}")
return False
else:
print(f" ✗ API调用失败")
print(f" 状态码: {response.status_code}")
print(f" 错误信息: {response.text[:500]}")
return False
except requests.exceptions.Timeout:
print(f" ✗ 请求超时30秒")
return False
except Exception as e:
print(f" ✗ 请求失败: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == '__main__':
success = test_siliconflow_api()
print()
print("="*80)
if success:
print("✓ API测试通过可以正常使用AI分析功能")
else:
print("✗ API测试失败请检查配置后重试")
print("="*80)