loader.py
4.31 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import json
import logging
import os
from pathlib import Path
from typing import Dict, Optional
from pydantic import ValidationError
from app.config.settings import 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_from_db(self, db_session) -> Dict[str, AgentConfig]:
"""从 ai_agents + ai_agent_skills 表加载所有活跃 agent。"""
from app.model.agent import Agent, AgentSkill
agents_rows = (
db_session.query(Agent)
.filter(Agent.is_deleted == False)
.all()
)
result: Dict[str, AgentConfig] = {}
for row in agents_rows:
skill_rows = (
db_session.query(AgentSkill)
.filter(AgentSkill.agent_id == row.id)
.all()
)
skills = [s.skill_code for s in skill_rows]
key = row.code
result[key] = AgentConfig(
name=row.name,
code=str(row.id),
prompt=row.prompt or row.description or "",
description=row.description or "",
skills=skills,
is_steward=row.is_steward,
)
stewards = [k for k, v in result.items() if v.is_steward]
if len(stewards) > 1:
for k in stewards[1:]:
result[k] = result[k].model_copy(update={"is_steward": False})
return result
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_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