""" 测试大模型API连接(华为大模型默认,硅基流动备用) """ import os from dotenv import load_dotenv import requests # 加载环境变量 load_dotenv() def test_huawei_api(): """测试华为大模型API连接""" print("="*80) print("测试华为大模型API连接") print("="*80) print() # 读取配置(华为大模型) api_key = os.getenv('HUAWEI_API_KEY', 'sk-PoeiV3qwyTIRqcVc84E8E24cD2904872859a87922e0d9186') model = os.getenv('HUAWEI_MODEL', 'DeepSeek-R1-Distill-Llama-70B') api_url = os.getenv('HUAWEI_API_ENDPOINT', 'http://10.100.31.26:3001/v1/chat/completions') # 检查配置 print("1. 检查配置...") if not api_key: print(" ✗ 错误: 未找到 HUAWEI_API_KEY") print(" 请在 .env 文件中设置: HUAWEI_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": "请回复'测试成功'" } ], "stream": False, "presence_penalty": 1.03, "frequency_penalty": 1.0, "repetition_penalty": 1.0, "temperature": 0.5, "top_p": 0.95, "top_k": 1, "seed": 1, "max_tokens": 20, "n": 1 } 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_huawei_api() print() print("="*80) if success: print("✓ API测试通过,可以正常使用AI分析功能") else: print("✗ API测试失败,请检查配置后重试") print("="*80)