Spaces:
Sleeping
Sleeping
File size: 3,201 Bytes
1a06196 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
"""
配置管理模块
统一管理所有环境变量和配置项
"""
import os
import logging
from typing import List
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
class Config:
"""应用配置类"""
# API认证配置
VALID_API_KEY: str = os.getenv("VALID_API_KEY", "")
K2THINK_TOKEN: str = os.getenv("K2THINK_TOKEN", "")
K2THINK_API_URL: str = os.getenv("K2THINK_API_URL", "https://www.k2think.ai/api/chat/completions")
# 服务器配置
HOST: str = os.getenv("HOST", "0.0.0.0")
PORT: int = int(os.getenv("PORT", "8001"))
# 功能开关
TOOL_SUPPORT: bool = os.getenv("TOOL_SUPPORT", "true").lower() == "true"
DEBUG_LOGGING: bool = os.getenv("DEBUG_LOGGING", "false").lower() == "true"
ENABLE_ACCESS_LOG: bool = os.getenv("ENABLE_ACCESS_LOG", "true").lower() == "true"
# 性能配置
SCAN_LIMIT: int = int(os.getenv("SCAN_LIMIT", "200000"))
SYSTEM_MESSAGE_LENGTH: int = int(os.getenv("SYSTEM_MESSAGE_LENTH", "200000"))
REQUEST_TIMEOUT: float = float(os.getenv("REQUEST_TIMEOUT", "60"))
MAX_KEEPALIVE_CONNECTIONS: int = int(os.getenv("MAX_KEEPALIVE_CONNECTIONS", "20"))
MAX_CONNECTIONS: int = int(os.getenv("MAX_CONNECTIONS", "100"))
STREAM_DELAY: float = float(os.getenv("STREAM_DELAY", "0.05"))
STREAM_CHUNK_SIZE: int = int(os.getenv("STREAM_CHUNK_SIZE", "50"))
MAX_STREAM_TIME: float = float(os.getenv("MAX_STREAM_TIME", "10.0"))
# 日志配置
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO").upper()
# CORS配置
CORS_ORIGINS: List[str] = (
os.getenv("CORS_ORIGINS", "*").split(",")
if os.getenv("CORS_ORIGINS", "*") != "*"
else ["*"]
)
@classmethod
def validate(cls) -> None:
"""验证必需的配置项"""
if not cls.VALID_API_KEY:
raise ValueError("错误:VALID_API_KEY 环境变量未设置。请在 .env 文件中提供一个安全的API密钥。")
if not cls.K2THINK_TOKEN:
raise ValueError("错误:K2THINK_TOKEN 环境变量未设置。请在 .env 文件中提供有效的K2Think JWT Token。")
# 验证数值范围
if cls.PORT < 1 or cls.PORT > 65535:
raise ValueError(f"错误:PORT 值 {cls.PORT} 不在有效范围内 (1-65535)")
if cls.REQUEST_TIMEOUT <= 0:
raise ValueError(f"错误:REQUEST_TIMEOUT 必须大于0,当前值: {cls.REQUEST_TIMEOUT}")
if cls.STREAM_DELAY < 0:
raise ValueError(f"错误:STREAM_DELAY 不能为负数,当前值: {cls.STREAM_DELAY}")
@classmethod
def setup_logging(cls) -> None:
"""设置日志配置"""
level_map = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR
}
log_level = level_map.get(cls.LOG_LEVEL, logging.INFO)
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
) |