Commit 44496ef2 by 孙奇 Committed by 胡悦

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

1 parent 84f4a7ed
......@@ -6,7 +6,9 @@ from typing import Dict, Optional
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__)
logger = logging.getLogger(__name__)
......@@ -67,6 +69,52 @@ class ConfigLoader:
return result
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):
......
......@@ -6,8 +6,6 @@ from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
logger = logging.getLogger(__name__)
from app.api.v1.router import api_router
from app.config.loader import ConfigLoader
from app.infrastructure.database import engine, SessionLocal
......@@ -40,13 +38,12 @@ from app.model.wecom_sync import ( # noqa: F401
WeComSyncCheckpoint,
)
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.agent_core.agent_hub import AgentHub
from app.agent_core.active_session_service import ActiveSessionService
from app.agent_core.console_im_service import ConsoleIMService
from app.agent_core.im_service import IMService
from app.service.agent_hub import AgentHub
from app.service.active_session_service import ActiveSessionService
from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService
agent_hub_instance = None
message_gate_instance = None
configure_logging("backend", logging.INFO)
runtime_settings = ConfigLoader().load_settings()
base_path = (runtime_settings.server.base_path or "").rstrip("/")
......@@ -58,25 +55,20 @@ oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/do
@asynccontextmanager
async def lifespan(app: FastAPI):
global agent_hub_instance, message_gate_instance
global agent_hub_instance
Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine)
config_loader = ConfigLoader()
settings = config_loader.load_settings()
db_factory = SessionLocal
# 从数据库加载 Agent 配置
with db_factory() as db:
agents = config_loader.load_agents_from_db(db)
logger.info(
"Agent 配置已从 DB 加载: %d 个, steward=%s",
len(agents),
next((k for k, v in agents.items() if v.is_steward), None),
)
db = SessionLocal()
session_service = ActiveSessionService(db_factory=db_factory)
# 加载 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")
if use_console_im is None:
......@@ -97,30 +89,13 @@ async def lifespan(app: FastAPI):
session_service=session_service,
im_service=im_service,
preloaded_agents=agents,
db_factory=db_factory,
)
# ── MessageGate 实例化 ──
from app.agent_core.message_gate import MessageGate
from app.hooks.post_reply import PostReplyHook
main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main")
post_reply_hook = PostReplyHook(im_service=im_service)
message_gate_instance = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub_instance,
main_agent_key=main_agent_key,
)
yield
if agent_hub_instance:
await agent_hub_instance.close()
if message_gate_instance:
await message_gate_instance.close()
# db_factory 是 class,不需要 close;短 session 由 with 自动管理
db.close()
app = FastAPI(
......
import logging
import time
from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
from app.service.active_session_service import ActiveSessionService
from agentscope.tool import Toolkit
from app.hooks.post_reply import PostReplyHook
from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.message._message_block import TextBlock
from agentscope.tool._response import ToolResponse
from agentscope.tool import execute_python_code, execute_shell_command
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__)
async def _im_post_reasoning_hook(
self, kwargs, output,
*, im_service, account_mapping, room_id, user_id, bot_id_mapping,
):
"""AgentScope native hook: 推理完成后通过 IM 发送 thinking 文本。"""
logger.info(f"[Hook 触发] agent={self.name} 时机=post_reasoning")
bot_id = (bot_id_mapping.get(self.name) or account_mapping.get(self.name))
if not bot_id:
return None
# 只提取 ThinkingBlock,跳过 tool_use 等其他 block
content_parts = []
if output and hasattr(output, "content"):
blocks = output.content if isinstance(output.content, list) else []
for block in blocks:
if isinstance(block, dict) and block.get("type") == "thinking":
content_parts.append(block.get("thinking", ""))
content = "\n".join(content_parts) if content_parts else None
if not content:
return None
# 中间过程只发前10个字符 + 省略号
content = content[:25] + "..." if len(content) > 10 else content
# 删除"下载"这个词
content = content.replace("下载", "点击")
logger.info(f"[Hook 发送 IM] agent={self.name} bot_id={bot_id} content={content[:50]}...")
try:
await im_service.send_message(
bot_id=bot_id, content=content,
contact_id=room_id, at_list="",
)
except Exception:
logger.warning(
"[Hook IM 发送失败] agent=%s room=%s(不影响推理流程)",
self.name, room_id, exc_info=True,
)
async def _im_pre_acting_hook(
self, kwargs,
*, im_service, account_mapping, room_id, user_id, bot_id_mapping,
):
"""AgentScope native hook: 工具调用前通过 IM 发送即将执行的工具信息。"""
logger.info(f"[Hook 触发] agent={self.name} 时机=pre_acting")
bot_id = (bot_id_mapping.get(self.name) or account_mapping.get(self.name))
if not bot_id:
return None
tool_call = kwargs.get("tool_call")
if not tool_call:
return None
content = str(tool_call)
logger.info(f"[Hook 发送 IM] agent={self.name} bot_id={bot_id} tool_call={tool_call}")
try:
await im_service.send_message(
bot_id=bot_id, content=content,
contact_id=room_id, at_list="",
)
except Exception:
logger.warning(
"[Hook IM 发送失败] agent=%s room=%s(不影响推理流程)",
self.name, room_id, exc_info=True,
)
class AgentHubError(Exception):
"""Raised when AgentHub processing fails."""
pass
class AgentHub:
"""
中央调度器 - 唯一运行的 Agent 运行时
持有所有 Agent 的配置,负责:
1. 提示词组装
2. 模型调用
3. 消息路由和分发
4. 通过 Hook 发送消息
"""
def __init__(
self,
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 = 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
self.account_to_agent = account_to_agent
self.post_reply_hook = PostReplyHook(
im_service=im_service,
account_mapping=agent_to_account
)
self.toolkit = Toolkit()
self.model = OpenAIChatModel(
model_name=self.main_model_config.model_name,
api_key=self.main_model_config.api_key,
stream=False,
client_kwargs={"base_url": self.main_model_config.api_base}
)
self.formatter = OpenAIChatFormatter()
# Register all skills from skills/ directory to Toolkit
skills_dir = Path(__file__).parent.parent.parent / "skills"
logger.info(f"扫描 skills 目录并注册到全局 Toolkit: {skills_dir}")
for skill_entry in sorted(skills_dir.iterdir()):
if skill_entry.is_dir() and not skill_entry.name.startswith('.'):
skill_md = skill_entry / "SKILL.md"
if skill_md.exists():
try:
self.toolkit.register_agent_skill(str(skill_entry))
except Exception as e:
logger.warning(
f"跳过 skill {skill_entry.name}: {e}"
)
# Load skills metadata from Toolkit
self.skills = config_loader.load_skills_from_toolkit(self.toolkit)
# Register built-in coding tools (shared by all agents)
self.toolkit.register_tool_function(
execute_python_code,
group_name="basic",
)
self.toolkit.register_tool_function(
execute_shell_command,
group_name="basic",
)
# Register call_sub_agent as a tool for serial chain collaboration
call_sub = self._make_call_sub_agent_tool()
self.toolkit.register_tool_function(
call_sub,
func_name="call_sub_agent",
group_name="basic",
json_schema={
"type": "function",
"function": {
"name": "call_sub_agent",
"description": "调用子Agent处理特定任务。当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。",
"parameters": {
"type": "object",
"properties": {
"agent_code": {
"type": "string",
"description": "子Agent调用码,必须从可用子Agent列表中选择,如 \"meeting\"",
},
"instruction": {
"type": "string",
"description": "给子Agent的具体指令,必须包含用户需求的完整描述",
},
},
"required": ["agent_code", "instruction"],
},
},
},
)
# Register sandboxed read_file tool for reading project files
read_file = self._make_read_file_tool()
self.toolkit.register_tool_function(
read_file,
func_name="read_file",
group_name="basic",
)
# 构建每个 agent 的专属 toolkit(按 skills 字段过滤)
self.agent_toolkits: Dict[str, Toolkit] = {}
for agent_code, agent_config in self.agents.items():
logger.info(f"构建 agent '{agent_code}' 的专属 Toolkit (skills: {agent_config.skills})")
agent_tk = Toolkit()
# 复制 basic 组工具(所有 agent 共用)
for name, tool in self.toolkit.tools.items():
if tool.group == "basic":
agent_tk.register_tool_function(
tool.original_func,
group_name=tool.group,
func_name=tool.name,
preset_kwargs=tool.preset_kwargs,
json_schema=tool.json_schema,
)
# 只复制该 agent 配置的 skills
for skill_name in agent_config.skills:
if skill_name in self.toolkit.skills:
skill_info = self.toolkit.skills[skill_name]
skill_dir = skill_info.get("dir", "")
if skill_dir:
agent_tk.register_agent_skill(skill_dir)
self.agent_toolkits[agent_code] = agent_tk
def _register_im_hooks(
self,
agent,
room_id: str,
user_id: str,
bot_id_mapping: Optional[Dict[str, str]],
):
"""为 Agent 实例注册 IM 发送 hook。"""
logger.info(f"[Hook 注册] agent={agent.name} 时机=post_reasoning")
route_ctx = dict(
im_service=self.im_service,
account_mapping=self.agent_to_account,
room_id=room_id,
user_id=user_id,
bot_id_mapping=bot_id_mapping or {},
)
agent.register_instance_hook(
"post_reasoning", "im_post_reasoning",
partial(_im_post_reasoning_hook, **route_ctx),
)
# pre_acting hook 保留未启用,需要时取消注释
# agent.register_instance_hook(
# "pre_acting", "im_pre_acting",
# partial(_im_pre_acting_hook, **route_ctx),
# )
def _build_main_prompt(
self,
context: Dict[str, Any],
allowed_agent_codes: Optional[list] = None,
) -> str:
"""
Build the main agent's prompt including sub-agent duty descriptions.
When allowed_agent_codes is set, only agents in that list are advertised.
"""
main_agent = self.agents.get("main")
if not main_agent:
raise AgentHubError("主 Agent 配置未找到")
# Collect duties from sub-agents, filtered by position if applicable
duty_lines = []
for code, agent in self.agents.items():
if code == "main":
continue
if allowed_agent_codes is not None and code not in allowed_agent_codes:
continue
# 使用简洁职责描述,避免原样拼入 prompt_template 中的 {company}/{duties} 占位符
sub_desc = f"负责{agent.role}相关任务"
duty_lines.append(
f"- {agent.name}(调用码: {code}): {sub_desc}"
)
duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent"
prompt = main_agent.prompt_template.format(
company="公司",
duties=duties_text,
)
review_guide = """
## 收到子Agent返回后
1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
"""
return prompt + review_guide
def _build_sub_agent_prompt(self, agent_code: str, context: Dict[str, Any]) -> str:
"""Build prompt for a sub-agent when handling a routed query."""
agent = self.agents.get(agent_code)
if not agent:
raise AgentHubError(f"Agent {agent_code} 配置未找到")
# Build duties from ALL agents (for context)
duty_lines = []
for code, a in self.agents.items():
duty_lines.append(f"- {a.name}({a.role})")
prompt = agent.prompt_template.format(
company="公司",
duties="\n".join(duty_lines),
)
return prompt
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
role = m.get("role", "user")
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content") or ""
return Msg(name=role, role=role, content=content)
async def process_message(
self,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
mentioned_agent_code: Optional[str] = None,
channel: str = "wechat_group",
file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None,
bot_id_mapping: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""
Process a user message end-to-end.
Flow:
1. Get or create session
2. Load conversation history
3. If @mentioned a specific agent → route directly
4. Otherwise → main agent judges intent
5. If intent is "route" → sub-agent handles
6. Send reply via post_reply hook
"""
start_time = time.time()
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
self._current_route_ctx = dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
)
session = self.session_service.get_or_create_session(
session_id=session_id,
room_id=room_id,
channel=channel
)
memory = SessionMemory(
session_id=session_id,
store=self.session_service.store,
max_rounds=20,
)
messages = memory.get_messages(max_rounds=10)
# 始终路由到 main agent
target_agent = "main"
routing_reason = "default"
context = {
"user_query": user_query,
"messages": messages,
"room_id": room_id,
"user_id": user_id
}
logger.debug(
"路由决策: target=%s reason=%s position_restricted=%s allowed=%s",
target_agent, routing_reason,
allowed_agent_codes is not None, allowed_agent_codes,
)
# Build prompt based on target agent
if target_agent == "main":
system_prompt = self._build_main_prompt(context, allowed_agent_codes=allowed_agent_codes)
else:
system_prompt = self._build_sub_agent_prompt(target_agent, context)
# Bridge: convert SessionStore dict history → AgentScope Msg[]
agent_memory = InMemoryMemory()
recent = messages[-10:]
history_msgs = [self._dict_to_msg(m) for m in recent]
if history_msgs:
await agent_memory.add(history_msgs)
# Create per-request ReActAgent with per-agent toolkit
agent = ReActAgent(
name=target_agent,
sys_prompt=system_prompt,
model=self.model,
formatter=self.formatter,
toolkit=self.agent_toolkits.get(target_agent, self.toolkit),
memory=agent_memory,
max_iters=10,
)
# Register IM hooks for this agent instance
self._register_im_hooks(agent, room_id, user_id, bot_id_mapping)
# Run ReAct loop via framework
# If there's an image URL, append it to the query so the agent can see it
effective_query = user_query
if file_url:
effective_query = f"{user_query}\n\n[用户发送了一张图片: {file_url}]"
user_msg = Msg("user", effective_query, "user")
# Store user message BEFORE agent call so it persists even on error
memory.add("user", user_query, agent_code="main")
try:
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content() or ""
memory.add("assistant", response_content, agent_code=target_agent)
finally:
# 持久化到 DB — always save what we have
self.session_service.save_to_db(session_id)
# Send via hook
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
"response_content": response_content,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {},
})
except Exception:
logger.warning(
"[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent, session_id, room_id, exc_info=True,
)
processing_time_ms = (time.time() - start_time) * 1000
return {
"session_id": session.session_id,
"response_agent_code": target_agent,
"response_content": response_content,
"routing_reason": routing_reason,
"processing_time_ms": round(processing_time_ms, 2)
}
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。"""
if agent_code not in self.agents:
valid = [c for c in self.agents if c != "main"]
return (
f"错误:子 Agent '{agent_code}' 不存在。"
f"可用调用码: {valid}"
)
sub_prompt = self._build_sub_agent_prompt(agent_code, {})
sub_memory = InMemoryMemory()
# All agents use the shared toolkit
sub_toolkit = self.toolkit
sub_agent = ReActAgent(
name=agent_code,
sys_prompt=sub_prompt,
model=self.model,
formatter=self.formatter,
toolkit=self.agent_toolkits.get(agent_code, self.toolkit),
memory=sub_memory,
max_iters=10,
)
# 为子 Agent 注册 IM hook
ctx = self._current_route_ctx
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
response = await sub_agent.reply(Msg("user", instruction, "user"))
return response.get_text_content()
def _make_read_file_tool(self):
"""Create a sandboxed read_file tool function.
The sandbox root is the backend project directory (parent of app/).
"""
root_dir = Path(__file__).parent.parent.parent.resolve()
async def read_file(file_path: str) -> ToolResponse:
"""Read the content of a local file. Path is relative to the project root.
Use this to read SKILL.md files, MEMORY.md, configuration files, etc.
Example: read_file('skills/get_weather/SKILL.md')
Args:
file_path: File path relative to the project root,
e.g. 'skills/meeting_minutes/SKILL.md' or 'config/agents.json'
Returns:
File content as text, truncated to 10000 characters if too large.
"""
try:
# Normalize: convert backslashes, strip single leading ./
normalized = file_path.replace("\\", "/")
if normalized.startswith("./"):
normalized = normalized[2:]
full_path = (root_dir / normalized).resolve()
# Sandbox check: prevent path traversal (must be BEFORE exists check)
if not str(full_path).startswith(str(root_dir)):
return ToolResponse(
content=[TextBlock(
type="text",
text="❌ Access denied: path escapes project root"
)]
)
if not full_path.exists():
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ File not found: {file_path}"
)]
)
if not full_path.is_file():
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ Not a file: {file_path}"
)]
)
content = full_path.read_text(encoding="utf-8")
if len(content) > 10000:
content = content[:10000] + "\n...[truncated]"
return ToolResponse(
content=[TextBlock(type="text", text=content)]
)
except Exception as e:
return ToolResponse(
content=[TextBlock(
type="text",
text=f"❌ Error reading file: {str(e)}"
)]
)
return read_file
def _make_call_sub_agent_tool(self):
"""Create closure tool function for registration to Toolkit."""
async def call_sub_agent(agent_code: str = "", instruction: str = "") -> ToolResponse:
"""调用子Agent处理特定任务。
当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。
Args:
agent_code: 子Agent调用码,必须从可用子Agent列表中选择,如 "meeting"
instruction: 给子Agent的具体指令,必须包含用户需求的完整描述
Returns:
子Agent的处理结果
"""
if not agent_code or not instruction:
return ToolResponse(
content=[TextBlock(type="text", text=(
"错误:agent_code 和 instruction 都是必填参数。\n"
"正确示例:call_sub_agent(agent_code=\"meeting\", instruction=\"请帮我整理会议纪要\")"
))]
)
result = await self._call_sub_agent(agent_code, instruction)
return ToolResponse(
content=[TextBlock(type="text", text=result)]
)
return call_sub_agent
def register_skill_tool(self, skill_name: str, tool_func, func_name: str):
"""将工具注册到所有拥有该 skill 的 agent toolkit"""
for agent_code, agent_config in self.agents.items():
if skill_name in agent_config.skills:
self.agent_toolkits[agent_code].register_tool_function(
tool_func,
func_name=func_name,
group_name="basic",
)
async def close(self):
"""Clean up resources (no-op with AgentScope)."""
pass
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!