"""测试DeepSeek API配置"""
import os
from dotenv import load_dotenv
from openai import OpenAI

# 加载环境变量
load_dotenv()

def test_deepseek_api():
    """测试DeepSeek API连接"""
    api_key = os.getenv('DEEPSEEK_API_KEY')
    base_url = os.getenv('DEEPSEEK_BASE_URL', 'https://api.deepseek.com')

    print(f"API Key: {api_key[:20]}..." if api_key else "未找到API Key")
    print(f"Base URL: {base_url}")

    if not api_key:
        print("[ERROR] DEEPSEEK_API_KEY not configured")
        return False

    try:
        # 创建客户端
        client = OpenAI(
            api_key=api_key,
            base_url=base_url
        )

        # 发送测试请求
        print("\nTesting API connection...")
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "你是一个AI助手"},
                {"role": "user", "content": "你好，请用一句话介绍你自己"}
            ],
            max_tokens=100
        )

        result = response.choices[0].message.content
        # 移除emoji和特殊字符
        result_clean = result.encode('ascii', 'ignore').decode('ascii')
        print(f"\n[SUCCESS] API connection successful!")
        print(f"Response: {result_clean if result_clean else result[:50]}")
        print(f"Usage: {response.usage}")
        return True

    except Exception as e:
        print(f"\n[ERROR] API connection failed: {str(e)}")
        return False

if __name__ == '__main__':
    test_deepseek_api()
