loader.py 2.7 KB
import json
import os
from pathlib import Path
from typing import Dict, Optional, Tuple
from pydantic import ValidationError
from app.config.settings import (
    ModelConfig, AgentConfig, Settings
)


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


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:
            raise ConfigLoadError(f"配置文件不存在: {filepath}")
        except json.JSONDecodeError as e:
            raise ConfigLoadError(f"配置文件JSON格式错误: {filepath} - {e}")

    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 e:
            raise ConfigLoadError(f"Agent配置验证失败: {e}")

    def load_skills_from_toolkit(self, toolkit) -> Dict[str, dict]:
        """Read registered skill metadata from AgentScope Toolkit (not from skills.json file)."""
        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 e:
            raise ConfigLoadError(f"模型配置验证失败: {e}")

    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 e:
            raise ConfigLoadError(f"运行时配置验证失败: {e}")