Files
eryao/backend/src/v1/agent/system_agents_config.py
T

100 lines
2.8 KiB
Python
Raw Normal View History

2026-04-03 16:56:47 +08:00
"""
System agents 配置加载工具
从 system_agents.yaml 加载配置并构建 RuntimeConfig
"""
from pathlib import Path
import yaml
from pydantic import ValidationError
from schemas.agent.system_agent import SystemAgentLLMConfig
from schemas.agent.runtime_config import (
ContextSource,
ContextWindowMode,
MessageContextConfig,
RuntimeConfig,
)
def _default_system_agents_path() -> Path:
return (
Path(__file__).resolve().parents[2]
/ "core"
/ "config"
/ "static"
/ "database"
/ "system_agents.yaml"
)
def _load_system_agents_yaml(path: Path | None = None) -> dict[str, object]:
target_path = path or _default_system_agents_path()
with target_path.open("r", encoding="utf-8") as f:
loaded = yaml.safe_load(f) or {}
if not isinstance(loaded, dict):
raise ValueError(f"Invalid system agents format: {target_path}")
return loaded
def _parse_context_messages_config(
yaml_config: dict[str, object] | None,
) -> MessageContextConfig:
if not yaml_config:
return MessageContextConfig()
raw_mode = yaml_config.get("mode", "day")
mode_str = raw_mode if isinstance(raw_mode, str) else "day"
raw_count = yaml_config.get("count", 2)
count = raw_count if isinstance(raw_count, int) else 2
try:
source = ContextSource.LATEST_CHAT
except ValueError:
source = ContextSource.LATEST_CHAT
try:
window_mode = ContextWindowMode(mode_str)
except ValueError:
window_mode = ContextWindowMode.DAY
return MessageContextConfig(
source=source,
window_mode=window_mode,
window_count=count,
)
def build_runtime_config_from_system_agents(
yaml_path: Path | None = None,
) -> RuntimeConfig:
"""
从 system_agents.yaml 构建 RuntimeConfig
仅使用 worker 配置:
- worker.context_messages 配置上下文窗口
- enabled_tools 固定为空(eryao 不启用自定义工具)
"""
raw = _load_system_agents_yaml(yaml_path)
raw_agents = raw.get("agents", [])
agents_list = raw_agents if isinstance(raw_agents, list) else []
worker_config: SystemAgentLLMConfig | None = None
for agent in agents_list:
if not isinstance(agent, dict):
continue
agent_type = str(agent.get("agent_type", "")).strip().lower()
if agent_type == "worker":
config_dict = agent.get("config") or {}
try:
worker_config = SystemAgentLLMConfig.model_validate(config_dict)
except ValidationError:
worker_config = SystemAgentLLMConfig()
context_cfg = _parse_context_messages_config(
worker_config.context_messages.model_dump() if worker_config else None
)
return RuntimeConfig(
enabled_tools=[],
context=context_cfg,
)