llm_account_helper.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. import sys
  3. import random
  4. import logging
  5. current_dir = os.path.dirname(os.path.abspath(__file__))
  6. root_dir = os.path.dirname(current_dir)
  7. sys.path.insert(0, root_dir)
  8. from utils.mysql import mysql_db
  9. logging.basicConfig(
  10. level=logging.INFO,
  11. format='%(asctime)s - %(levelname)s - %(message)s'
  12. )
  13. def get_api_key(llm_type: str) -> str:
  14. """
  15. 获取指定类型的LLM API密钥。
  16. 从数据库中随机选择一个状态为正常的API密钥。
  17. Args:
  18. llm_type (str): LLM类型,例如"openai"、"openrouter"等
  19. Returns:
  20. str: 有效的API密钥
  21. """
  22. try:
  23. # 查询所有状态为正常(status=1)的API密钥
  24. api_keys = mysql_db.select(
  25. table='llm_account',
  26. columns='api_key',
  27. where='status = %s and type = %s',
  28. where_params=(1, llm_type)
  29. )
  30. if not api_keys:
  31. raise ValueError(f"数据库中没有找到有效的{llm_type} API密钥")
  32. # 随机选择一个API密钥
  33. selected_key = random.choice(api_keys)['api_key']
  34. return selected_key
  35. except Exception as e:
  36. logging.error(f"获取{llm_type} API密钥失败: {e}")
  37. # 如果数据库查询失败,抛出异常
  38. raise