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

from pydantic import ValidationError

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


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 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