loader.py
2.7 KB
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
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}")