config.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """配置管理模块"""
  2. import os
  3. from pathlib import Path
  4. from pydantic_settings import BaseSettings
  5. from dotenv import load_dotenv
  6. # 加载环境变量
  7. load_dotenv()
  8. class Settings(BaseSettings):
  9. """应用配置"""
  10. # LLM配置(支持多种命名方式)
  11. llm_api_key: str = ""
  12. llm_base_url: str = "https://api.openai.com/v1"
  13. llm_model_id: str = "gpt-4"
  14. llm_timeout: int = 180
  15. # 兼容旧字段名
  16. openai_api_key: str = "" # 兼容字段,会自动映射到 llm_api_key
  17. openai_base_url: str = "https://api.openai.com/v1"
  18. openai_model: str = "gpt-4"
  19. # 搜索 API 配置
  20. tavily_api_key: str = ""
  21. serpapi_api_key: str = ""
  22. # 系统配置
  23. max_depth: int = 3
  24. approval_threshold: int = 75
  25. revision_threshold: int = 60
  26. enable_parallel: bool = False
  27. enable_search: bool = True # 是否启用搜索功能
  28. # 服务器配置(可选,用于 API 服务)
  29. host: str = "0.0.0.0"
  30. port: int = 8000
  31. cors_origins: str = ""
  32. log_level: str = "INFO"
  33. # 其他服务配置(可选,忽略未使用的)
  34. unsplash_access_key: str = ""
  35. unsplash_secret_key: str = ""
  36. vite_api_base_url: str = ""
  37. amap_api_key: str = ""
  38. vite_amap_web_key: str = ""
  39. # 字数配置
  40. word_count_level_1: int = 600
  41. word_count_level_2: int = 400
  42. word_count_level_3: int = 200
  43. word_count_tolerance: float = 0.1
  44. class Config:
  45. env_file = ".env"
  46. case_sensitive = False
  47. extra = "ignore" # 忽略未定义的字段,避免验证错误
  48. # 全局配置实例
  49. _settings = None
  50. def get_settings() -> Settings:
  51. """获取配置实例(单例模式)"""
  52. global _settings
  53. if _settings is None:
  54. _settings = Settings()
  55. # 兼容处理:如果使用旧字段名,自动映射到新字段名
  56. if _settings.openai_api_key and not _settings.llm_api_key:
  57. _settings.llm_api_key = _settings.openai_api_key
  58. if _settings.openai_base_url and _settings.llm_base_url == "https://api.openai.com/v1":
  59. _settings.llm_base_url = _settings.openai_base_url
  60. if _settings.openai_model and _settings.llm_model_id == "gpt-4":
  61. _settings.llm_model_id = _settings.openai_model
  62. return _settings
  63. def get_word_count(level: int) -> int:
  64. """获取指定层级的目标字数"""
  65. settings = get_settings()
  66. word_counts = {
  67. 1: settings.word_count_level_1,
  68. 2: settings.word_count_level_2,
  69. 3: settings.word_count_level_3
  70. }
  71. return word_counts.get(level, 400)