Files
吉鑫升 f1d58983c2 feat: 智能体精选排序与新对话智能体选择器
- 后端新增 featured_order 字段及精选排序 API(/agents/selector、/agents/{id}/featured、/agents/featured/order),移除 user_agent_pin 表
- 前端新对话页 (ChatPage) 与输入框 (InputBox) 接入 agent-selector,选中后跳转 AgentChatPage 并通过 sessionStorage 透传首条消息
- 新增管理员智能体管理弹窗 (agent-manage-dialog) 支持精选添加/移除/上下移动
2026-05-21 14:39:12 +08:00

168 lines
5.6 KiB
Python

"""Configuration and loaders for custom agents."""
import logging
import re
from typing import Any
import yaml
from pydantic import BaseModel
from deerflow.config.paths import get_paths
logger = logging.getLogger(__name__)
SOUL_FILENAME = "SOUL.md"
AGENT_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
# Backward-compatible alias. Historically this validated the display name;
# after the DB-backed agent table, display names can be Chinese and duplicated.
# The pattern now applies only to storage/runtime ids.
AGENT_NAME_PATTERN = AGENT_ID_PATTERN
def validate_agent_id(agent_id: str | None) -> str | None:
"""Validate a custom agent id before using it in filesystem paths."""
if agent_id is None:
return None
if not isinstance(agent_id, str):
raise ValueError("Invalid agent id. Expected a string or None.")
if not AGENT_ID_PATTERN.fullmatch(agent_id):
raise ValueError(f"Invalid agent id '{agent_id}'. Must match pattern: {AGENT_ID_PATTERN.pattern}")
return agent_id
def validate_agent_name(name: str | None) -> str | None:
"""Backward-compatible alias for validating a storage/runtime agent id."""
return validate_agent_id(name)
class AgentConfig(BaseModel):
"""Configuration for a custom agent."""
id: str | None = None
name: str
description: str = ""
model: str | None = None
tool_groups: list[str] | None = None
# skills controls which skills are loaded into a custom agent's prompt:
# - None (or omitted): no skills (custom agents require explicit selection)
# - [] (explicit empty list): no skills
# - ["skill1", "skill2"]: load only the specified skills
skills: list[str] | None = None
def load_agent_config(agent_id: str | None) -> AgentConfig | None:
"""Load the custom or default agent's config from its directory.
Args:
agent_id: The agent storage/runtime id.
Returns:
AgentConfig instance, or ``None`` when the on-disk artifacts are missing.
Raises:
ValueError: If config.yaml exists but cannot be parsed.
Tolerance:
A missing agent directory or missing config.yaml is **not** an error —
the runtime simply falls back to default Lead Agent behavior for that
id. This keeps the chat session usable when the DB still has an agent
row but its files have been deleted (e.g. data dir moved between
machines, or filesystem wiped). The router layer is expected to
lazily restore the directory next time the agent is fetched via API.
"""
if agent_id is None:
return None
agent_id = validate_agent_id(agent_id)
agent_dir = get_paths().agent_dir(agent_id)
config_file = agent_dir / "config.yaml"
if not agent_dir.exists():
logger.warning(
"Agent directory missing for id '%s' (%s); falling back to default config",
agent_id,
agent_dir,
)
return None
if not config_file.exists() and not (agent_dir / SOUL_FILENAME).exists():
logger.warning(
"Agent has no config.yaml or %s at %s; falling back to default config",
SOUL_FILENAME,
agent_dir,
)
return None
data: dict[str, Any] = {}
if config_file.exists():
try:
with open(config_file, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
except yaml.YAMLError as e:
raise ValueError(f"Failed to parse agent config {config_file}: {e}") from e
# Ensure id/name are set from directory id if not in file.
if "id" not in data:
data["id"] = agent_id
if "name" not in data:
data["name"] = agent_id
# Strip unknown fields before passing to Pydantic (e.g. legacy prompt_file)
known_fields = set(AgentConfig.model_fields.keys())
data = {k: v for k, v in data.items() if k in known_fields}
return AgentConfig(**data)
def load_agent_soul(agent_id: str | None) -> str | None:
"""Read the SOUL.md file for a custom agent, if it exists.
SOUL.md defines the agent's personality, values, and behavioral guardrails.
It is injected into the lead agent's system prompt as additional context.
Args:
agent_id: The storage/runtime id of the agent or None for the default agent.
Returns:
The SOUL.md content as a string, or None if the file does not exist.
"""
agent_dir = get_paths().agent_dir(validate_agent_id(agent_id)) if agent_id else get_paths().base_dir
soul_path = agent_dir / SOUL_FILENAME
if not soul_path.exists():
return None
content = soul_path.read_text(encoding="utf-8").strip()
return content or None
def list_custom_agents() -> list[AgentConfig]:
"""Scan the agents directory and return all valid custom agents.
Returns:
List of AgentConfig for each valid agent directory found.
"""
agents_dir = get_paths().agents_dir
if not agents_dir.exists():
return []
agents: list[AgentConfig] = []
for entry in sorted(agents_dir.iterdir()):
if not entry.is_dir():
continue
config_file = entry / "config.yaml"
soul_file = entry / SOUL_FILENAME
if not config_file.exists() and not soul_file.exists():
logger.debug(f"Skipping {entry.name}: no config.yaml or SOUL.md")
continue
try:
agent_cfg = load_agent_config(entry.name)
agents.append(agent_cfg)
except Exception as e:
logger.warning(f"Skipping agent '{entry.name}': {e}")
return agents