| """ | |
| Anthropic API相关功能模块 - 提供Anthropic Claude API的调用和验证功能 | |
| """ | |
| import requests | |
| def validate_api_key(api_key): | |
| """ | |
| 验证Anthropic API密钥是否有效 | |
| Args: | |
| api_key (str): 需要验证的Anthropic API密钥 | |
| Returns: | |
| dict: 包含验证结果的字典,包括: | |
| - success (bool): API密钥验证成功为True,失败为False | |
| - return_message (str): 验证响应的具体消息,成功时为"200: Success!",失败时为错误详情 | |
| - balance (float): 账户余额,固定为0 | |
| - states (str): 账户状态,付费版或免费版 | |
| """ | |
| url = "https://api.anthropic.com/v1/messages" | |
| headers = { | |
| "x-api-key": api_key, | |
| "content-type": "application/json", | |
| "anthropic-version": "2023-06-01" | |
| } | |
| payload = { | |
| "model": "claude-3-5-sonnet-20241022", | |
| "max_tokens": 1, | |
| "messages": [ | |
| {"role": "user", "content": "Hello"} | |
| ] | |
| } | |
| try: | |
| response = requests.post(url, headers=headers, json=payload) | |
| if response.status_code == 200: | |
| states = "" | |
| rateLimit = response.headers.get("anthropic-ratelimit-input-tokens-limit") | |
| if rateLimit: | |
| tokens = int(rateLimit) | |
| if tokens == 40000: | |
| states = "Tier1" | |
| elif tokens == 80000: | |
| states = "Tier2" | |
| elif tokens == 160000: | |
| states = "Tier3" | |
| elif tokens == 400000: | |
| states = "Tier4" | |
| else: | |
| states = "Unknown" | |
| return { | |
| "success": True, | |
| "return_message": "200: Success!", | |
| "balance": 0, | |
| "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": "" | |
| } | |