loader.py 5.48 KB
import json
import logging
import os
from pathlib import Path
from typing import Dict, Optional, Tuple

from pydantic import ValidationError

from app.config.settings import AGENT_CODE_SYNC_MAP, AgentConfig, ModelConfig, Settings

logger = logging.getLogger(__name__)


class ConfigLoadError(Exception):
    """Raised when config loading or validation fails."""


class ConfigLoader:
    def __init__(self, config_dir: Optional[str] = None):
        if config_dir is None:
            config_dir = os.getenv("APP_CONFIG_DIR") or (Path(__file__).parent.parent.parent / "config")
        self.config_dir = Path(config_dir)

    def _load_json(self, filename: str) -> dict:
        filepath = self.config_dir / filename
        try:
            with open(filepath, "r", encoding="utf-8") as f:
                return json.load(f)
        except FileNotFoundError as exc:
            raise ConfigLoadError(f"配置文件不存在: {filepath}") from exc
        except json.JSONDecodeError as exc:
            raise ConfigLoadError(f"配置文件 JSON 格式错误: {filepath} - {exc}") from exc

    def load_agents(self) -> Dict[str, AgentConfig]:
        data = self._load_json("agents.json")
        try:
            return {code: AgentConfig(**config) for code, config in data["agents"].items()}
        except ValidationError as exc:
            raise ConfigLoadError(f"Agent 配置校验失败: {exc}") from exc

    def sync_agent_codes_from_db(
        self, agents: Dict[str, AgentConfig], db_session
    ) -> None:
        """从 official_site_agent_display 表同步 agent.code,失败时保留 JSON 默认值。

        根据 AGENT_CODE_SYNC_MAP 中的映射,查询 DB 中 agent_name 对应的 agent_id,
        然后更新 AgentConfig.code = str(agent_id)。
        """
        try:
            from app.model.official_site_agent_display import OfficialSiteAgentDisplay

            target_names = list(AGENT_CODE_SYNC_MAP.keys())
            rows = (
                db_session.query(
                    OfficialSiteAgentDisplay.agent_name,
                    OfficialSiteAgentDisplay.agent_id,
                )
                .filter(OfficialSiteAgentDisplay.agent_name.in_(target_names))
                .all()
            )

            name_to_id = {row.agent_name: row.agent_id for row in rows}

            for db_name, internal_key in AGENT_CODE_SYNC_MAP.items():
                if internal_key not in agents:
                    continue
                agent_id = name_to_id.get(db_name)
                if agent_id is not None:
                    old_code = agents[internal_key].code
                    agents[internal_key].code = str(agent_id)
                    logger.info(
                        "Agent code 已从 DB 同步: %s.code %s → %s",
                        internal_key, old_code, agent_id,
                    )
                else:
                    logger.warning(
                        "DB 中未找到 agent_name='%s',保留 JSON 默认值 code='%s'",
                        db_name, agents[internal_key].code,
                    )

        except Exception:
            logger.warning(
                "从 DB 同步 agent code 失败,使用 JSON 默认值",
                exc_info=True,
            )

    def load_skills_from_toolkit(self, toolkit) -> Dict[str, dict]:
        skills = {}
        for name, skill in toolkit.skills.items():
            skills[name] = {
                "code": name,
                "name": skill.get("name", name),
                "description": skill.get("description", ""),
                "instruction": skill.get("description", ""),
                "location": skill.get("dir", ""),
            }
        return skills

    def load_models(self) -> Dict[str, ModelConfig]:
        data = self._load_json("models.json")
        try:
            return {name: ModelConfig(**config) for name, config in data["models"].items()}
        except ValidationError as exc:
            raise ConfigLoadError(f"模型配置校验失败: {exc}") from exc

    def load_account_mappings(self) -> Tuple[Dict[str, str], Dict[str, str]]:
        data = self._load_json("mappings.json")
        return data["agent_accounts"], data["account_agents"]

    def load_settings(self) -> Settings:
        filepath = self.config_dir / "settings.json"
        if not filepath.exists():
            return Settings()
        data = self._load_json("settings.json")
        try:
            return Settings(**data)
        except ValidationError as exc:
            raise ConfigLoadError(f"运行时配置校验失败: {exc}") from exc

    def load_database_url(self) -> str:
        database_url = os.getenv("DATABASE_URL", "").strip()
        if not database_url:
            env_file = self.config_dir.parent / ".env"
            if env_file.exists():
                for line in env_file.read_text(encoding="utf-8").splitlines():
                    stripped = line.strip()
                    if not stripped or stripped.startswith("#") or "=" not in stripped:
                        continue
                    key, value = stripped.split("=", 1)
                    if key.strip() == "DATABASE_URL":
                        database_url = value.strip().strip("'\"")
                        break
        if not database_url:
            raise ConfigLoadError("DATABASE_URL 未配置,backend 仅支持显式 MySQL 连接")
        if not database_url.startswith("mysql+pymysql://"):
            raise ConfigLoadError("DATABASE_URL 必须使用 mysql+pymysql://,不再支持 SQLite 兜底")
        return database_url