100 lines
3.0 KiB
Python
100 lines
3.0 KiB
Python
"""
|
||
前端配置管理模块
|
||
集中管理所有配置项,支持环境变量覆盖
|
||
需要类型转换的配置在此处理
|
||
"""
|
||
|
||
import os
|
||
from dataclasses import dataclass
|
||
from typing import Optional
|
||
from dotenv import load_dotenv
|
||
|
||
# 加载 .env 文件
|
||
load_dotenv()
|
||
|
||
|
||
# ========== 辅助函数:类型转换 ==========
|
||
def _get_str(key: str) -> str | None:
|
||
"""获取字符串配置"""
|
||
return os.getenv(key)
|
||
|
||
|
||
def _get_int(key: str, default: int = 0) -> int:
|
||
"""获取整数配置,自动转换"""
|
||
value = os.getenv(key)
|
||
if value is not None:
|
||
try:
|
||
return int(value)
|
||
except (ValueError, TypeError):
|
||
pass
|
||
return default
|
||
|
||
|
||
def _get_bool(key: str, default: bool = False) -> bool:
|
||
"""获取布尔配置,自动转换"""
|
||
value = os.getenv(key)
|
||
if value is not None:
|
||
return value.lower() in ("true", "1", "yes", "on")
|
||
return default
|
||
|
||
|
||
@dataclass
|
||
class FrontendConfig:
|
||
"""前端配置类 - 统一管理所有配置项"""
|
||
|
||
# ==================== API 配置 ====================
|
||
api_base: str = ""
|
||
|
||
# ==================== 页面配置(固定值,无需环境变量) ====================
|
||
page_title: str = "AI 个人助手"
|
||
page_icon: str = "🤖"
|
||
layout: str = "wide"
|
||
|
||
# ==================== 模型配置(固定值,无需环境变量) ====================
|
||
default_model: str = "zhipu"
|
||
model_options: Optional[dict] = None
|
||
|
||
# ==================== 用户配置(固定值,无需环境变量) ====================
|
||
default_user_id: str = "default_user"
|
||
|
||
# ==================== 历史记录配置(固定值,无需环境变量) ====================
|
||
history_limit: int = 50
|
||
summary_max_length: int = 30
|
||
|
||
# ==================== 流式响应配置(固定值,无需环境变量) ====================
|
||
stream_timeout: int = 120
|
||
|
||
# ==================== 日志配置 ====================
|
||
log_level: str = ""
|
||
debug: bool = False
|
||
|
||
def __post_init__(self):
|
||
"""初始化后处理 - 设置默认值和加载环境变量"""
|
||
if self.model_options is None:
|
||
self.model_options = {
|
||
"zhipu": "智谱 GLM-5.1(在线)",
|
||
"local": "本地 llama.cpp(Gemma-4)",
|
||
"deepseek": "DeepSeek V4-Pro(在线)"
|
||
}
|
||
|
||
# 从环境变量加载配置(优先级最高)
|
||
self._load_from_env()
|
||
|
||
def _load_from_env(self):
|
||
"""从环境变量加载配置(仅加载必要的配置项)"""
|
||
# API 地址(移除 /chat 后缀)
|
||
api_url = _get_str("API_URL")
|
||
if api_url:
|
||
self.api_base = api_url.replace("/chat", "").rstrip("/")
|
||
|
||
# 日志配置
|
||
log_level = _get_str("LOG_LEVEL")
|
||
if log_level:
|
||
self.log_level = log_level.upper()
|
||
|
||
self.debug = _get_bool("DEBUG", False)
|
||
|
||
|
||
# 全局配置实例(单例模式)
|
||
config = FrontendConfig()
|