|
"""
|
|
Deepseek API相关功能模块 - 提供Deepseek API的调用和验证功能
|
|
"""
|
|
import requests
|
|
|
|
def validate_api_key(api_key):
|
|
"""
|
|
验证Deepseek API密钥是否有效并获取账户余额
|
|
|
|
Args:
|
|
api_key (str): 需要验证的Deepseek API密钥
|
|
|
|
Returns:
|
|
dict: 包含验证结果的字典,包括:
|
|
- success (bool): API密钥验证成功为True,失败为False
|
|
- return_message (str): 验证响应的具体消息,成功时为"200: Success!",失败时为错误详情
|
|
- balance (float): 账户余额,成功时为账户总余额,失败时为0
|
|
- states (str): 账户状态
|
|
"""
|
|
url = "https://api.deepseek.com/v1/user/balance"
|
|
|
|
headers = {
|
|
"Authorization": f"Bearer {api_key}"
|
|
}
|
|
|
|
try:
|
|
response = requests.get(url, headers=headers)
|
|
|
|
if response.status_code == 200:
|
|
response_data = response.json()
|
|
is_available = response_data.get("is_available", False)
|
|
|
|
if not is_available:
|
|
return {
|
|
"success": False,
|
|
"return_message": "429: Insufficient balance",
|
|
"balance": 0,
|
|
"states": ""
|
|
}
|
|
|
|
balance_infos = response_data.get("balance_infos", [])
|
|
|
|
balance = 0.0
|
|
|
|
try:
|
|
exchange_rate_response = requests.get("https://api.exchangerate-api.com/v4/latest/USD")
|
|
exchange_rate_response.raise_for_status()
|
|
exchange_rate_data = exchange_rate_response.json()
|
|
exchange_rate = exchange_rate_data.get("rates", {}).get("CNY")
|
|
|
|
if exchange_rate is None:
|
|
exchange_rate = 7.2
|
|
except Exception as e:
|
|
exchange_rate = 7.2
|
|
|
|
has_cny = False
|
|
has_usd = False
|
|
|
|
for balance_info in balance_infos:
|
|
currency = balance_info.get("currency")
|
|
total_balance = float(balance_info.get("total_balance", 0))
|
|
|
|
if currency == "CNY":
|
|
balance += total_balance
|
|
if total_balance > 0:
|
|
has_cny = True
|
|
elif currency == "USD":
|
|
balance += total_balance * exchange_rate
|
|
if total_balance > 0:
|
|
has_usd = True
|
|
|
|
states = ""
|
|
if has_cny and has_usd:
|
|
states = "CNY/USD"
|
|
elif has_cny:
|
|
states = "CNY"
|
|
elif has_usd:
|
|
states = "USD"
|
|
|
|
return {
|
|
"success": True,
|
|
"return_message": "200: Success!",
|
|
"balance": balance,
|
|
"states": states
|
|
}
|
|
else:
|
|
return_message = ""
|
|
try:
|
|
error_data = response.json()
|
|
if "error" in error_data:
|
|
return_message = error_data["error"].get("message", "")
|
|
return_message = f"{response.status_code}: {return_message}"
|
|
except:
|
|
return_message = f"{response.status_code}: {response.text or f'HTTP错误'}"
|
|
|
|
return {
|
|
"success": False,
|
|
"return_message": return_message,
|
|
"balance": 0,
|
|
"states": ""
|
|
}
|
|
except Exception as e:
|
|
error_str = str(e)
|
|
print(f"验证API密钥时出错: {error_str}")
|
|
return {
|
|
"success": False,
|
|
"return_message": f"500: 请求异常: {error_str}",
|
|
"balance": 0,
|
|
"states": ""
|
|
} |