Commit c05826bd by 孙奇

feat(agent_hub): 从数据库同步 agent.code 值并优化配置加载逻辑

1 parent 4b35a230
import json
import logging
import os
from pathlib import Path
from typing import Dict, Optional, Tuple
from pydantic import ValidationError
from app.config.settings import AgentConfig, ModelConfig, Settings
from app.config.settings import AGENT_CODE_SYNC_MAP, AgentConfig, ModelConfig, Settings
logger = logging.getLogger(__name__)
class ConfigLoadError(Exception):
......@@ -35,6 +38,52 @@ class ConfigLoader:
except ValidationError as exc:
raise ConfigLoadError(f"Agent 配置校验失败: {exc}") from exc
def sync_agent_codes_from_db(
self, agents: Dict[str, AgentConfig], db_session
) -> None:
"""从 official_site_agent_display 表同步 agent.code,失败时保留 JSON 默认值。
根据 AGENT_CODE_SYNC_MAP 中的映射,查询 DB 中 agent_name 对应的 agent_id,
然后更新 AgentConfig.code = str(agent_id)。
"""
try:
from app.model.official_site_agent_display import OfficialSiteAgentDisplay
target_names = list(AGENT_CODE_SYNC_MAP.keys())
rows = (
db_session.query(
OfficialSiteAgentDisplay.agent_name,
OfficialSiteAgentDisplay.agent_id,
)
.filter(OfficialSiteAgentDisplay.agent_name.in_(target_names))
.all()
)
name_to_id = {row.agent_name: row.agent_id for row in rows}
for db_name, internal_key in AGENT_CODE_SYNC_MAP.items():
if internal_key not in agents:
continue
agent_id = name_to_id.get(db_name)
if agent_id is not None:
old_code = agents[internal_key].code
agents[internal_key].code = str(agent_id)
logger.info(
"Agent code 已从 DB 同步: %s.code %s → %s",
internal_key, old_code, agent_id,
)
else:
logger.warning(
"DB 中未找到 agent_name='%s',保留 JSON 默认值 code='%s'",
db_name, agents[internal_key].code,
)
except Exception:
logger.warning(
"从 DB 同步 agent code 失败,使用 JSON 默认值",
exc_info=True,
)
def load_skills_from_toolkit(self, toolkit) -> Dict[str, dict]:
skills = {}
for name, skill in toolkit.skills.items():
......
from pydantic import BaseModel
from typing import List
from typing import Dict, List
# official_site_agent_display.agent_name → 内部 agent dict key
# 用于从 DB 同步 agent.code 值
AGENT_CODE_SYNC_MAP: Dict[str, str] = {
"管家 Agent": "main",
"会议Agent": "meeting",
}
class ModelConfig(BaseModel):
......
......@@ -63,6 +63,11 @@ async def lifespan(app: FastAPI):
config_loader = ConfigLoader()
settings = config_loader.load_settings()
db = SessionLocal()
# 加载 Agent 配置并从 DB 同步 code 值
agents = config_loader.load_agents()
config_loader.sync_agent_codes_from_db(agents, db)
session_service = ActiveSessionService(db=db)
use_console_im = os.getenv("USE_CONSOLE_IM")
......@@ -83,6 +88,7 @@ async def lifespan(app: FastAPI):
config_loader=config_loader,
session_service=session_service,
im_service=im_service,
preloaded_agents=agents,
)
yield
......
......@@ -104,12 +104,13 @@ class AgentHub:
config_loader: ConfigLoader,
session_service: ActiveSessionService,
im_service,
preloaded_agents: Optional[Dict[str, Any]] = None,
):
self.config_loader = config_loader
self.session_service = session_service
self.im_service = im_service
self.agents = config_loader.load_agents()
self.agents = preloaded_agents if preloaded_agents is not None else config_loader.load_agents()
self.main_model_config = config_loader.load_models()["main"]
agent_to_account, account_to_agent = config_loader.load_account_mappings()
self.agent_to_account = agent_to_account
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!