Commit c82b3fed by sunqi02

refactor(agent_hub): eliminate hardcoded 'main', DB-driven config

- Add _find_steward_agent()/_find_steward_key() for dynamic steward lookup
- Replace all hardcoded 'main' with is_steward-based checks
- Simplify prompt building (no more .format() placeholder substitution)
- Remove account_mapping from hooks, bot_id from request only
- Delete self.agent_to_account / self.account_to_agent
- Add REVIEW_GUIDE module constant
- API endpoint uses is_steward instead of 'main' check

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 1a9d946a
......@@ -91,19 +91,19 @@ async def chat(
allowed_agent_codes: Optional[list] = None
bot_id_mapping: dict = {}
if request.agents:
# 构建 agent.code → 内部名称(dict key)映射
code_to_name = {
cfg.code: name for name, cfg in agent_hub.agents.items()
# 构建 AgentConfig.code → dict key 映射
code_to_key = {
cfg.code: key for key, cfg in agent_hub.agents.items()
}
allowed_agent_codes = []
for agent_info in request.agents:
agent_code_str = str(agent_info.agent_id)
internal_name = code_to_name.get(agent_code_str)
if internal_name and internal_name != "main":
allowed_agent_codes.append(internal_name)
# 提取 bot_id 映射:{internal_agent_name: bot_id}
if internal_name and agent_info.bot_id:
bot_id_mapping[internal_name] = agent_info.bot_id
agent_id_str = str(agent_info.agent_id)
agent_key = code_to_key.get(agent_id_str)
if agent_key and not agent_hub.agents[agent_key].is_steward:
allowed_agent_codes.append(agent_key)
# 提取 bot_id 映射:{dict_key: bot_id}
if agent_key and agent_info.bot_id:
bot_id_mapping[agent_key] = agent_info.bot_id
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
......
......@@ -20,14 +20,22 @@ from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__)
REVIEW_GUIDE = """
## 收到子Agent返回后
1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
"""
async def _im_post_reasoning_hook(
self, kwargs, output,
*, im_service, account_mapping, room_id, user_id, bot_id_mapping,
*, im_service, 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))
bot_id = bot_id_mapping.get(self.name)
if not bot_id:
return None
# 只提取 ThinkingBlock,跳过 tool_use 等其他 block
......@@ -59,11 +67,11 @@ async def _im_post_reasoning_hook(
async def _im_pre_acting_hook(
self, kwargs,
*, im_service, account_mapping, room_id, user_id, bot_id_mapping,
*, im_service, 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))
bot_id = bot_id_mapping.get(self.name)
if not bot_id:
return None
tool_call = kwargs.get("tool_call")
......@@ -110,16 +118,13 @@ class AgentHub:
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()
if preloaded_agents is None:
raise AgentHubError("preloaded_agents is required — load from DB via ConfigLoader.load_agents_from_db()")
self.agents: Dict[str, Any] = preloaded_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.post_reply_hook = PostReplyHook(im_service=im_service)
self.toolkit = Toolkit()
self.model = OpenAIChatModel(
......@@ -159,6 +164,10 @@ class AgentHub:
# Register call_sub_agent as a tool for serial chain collaboration
call_sub = self._make_call_sub_agent_tool()
# 动态获取一个非 steward 的 agent key 作为示例
sub_example = next(
(k for k, a in self.agents.items() if not a.is_steward), "sub_agent"
)
self.toolkit.register_tool_function(
call_sub,
func_name="call_sub_agent",
......@@ -173,7 +182,7 @@ class AgentHub:
"properties": {
"agent_code": {
"type": "string",
"description": "子Agent调用码,必须从可用子Agent列表中选择,如 \"meeting\"",
"description": f"子Agent调用码,必须从可用子Agent列表中选择,如 \"{sub_example}\"",
},
"instruction": {
"type": "string",
......@@ -229,7 +238,6 @@ class AgentHub:
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 {},
......@@ -238,11 +246,20 @@ class AgentHub:
"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 _find_steward_agent(self) -> Any:
"""查找主 Agent(is_steward=True)。"""
for agent in self.agents.values():
if agent.is_steward:
return agent
raise AgentHubError("未找到主 Agent(is_steward=True)")
def _find_steward_key(self) -> str:
"""查找主 Agent 的 dict key。"""
for key, agent in self.agents.items():
if agent.is_steward:
return key
raise AgentHubError("未找到主 Agent(is_steward=True)")
def _build_main_prompt(
self,
......@@ -253,39 +270,22 @@ class AgentHub:
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 配置未找到")
steward = self._find_steward_agent()
prompt = steward.prompt # 完整文本,直接使用
# Collect duties from sub-agents, filtered by position if applicable
duty_lines = []
sub_lines = []
for code, agent in self.agents.items():
if code == "main":
if agent.is_steward:
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}"
)
sub_lines.append(f"- {agent.name}(调用码: {code}): {agent.name}相关任务")
duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent"
if sub_lines:
prompt += "\n\n## 可调用的子Agent\n" + "\n".join(sub_lines)
prompt = main_agent.prompt_template.format(
company="公司",
duties=duties_text,
)
review_guide = """
## 收到子Agent返回后
1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
"""
return prompt + review_guide
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."""
......@@ -293,17 +293,7 @@ class AgentHub:
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
return agent.prompt # 直接使用,无需拼接
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
......@@ -357,8 +347,8 @@ class AgentHub:
messages = memory.get_messages(max_rounds=10)
# 始终路由到 main agent
target_agent = "main"
# 始终路由到 steward agent
target_agent = self._find_steward_key()
routing_reason = "default"
context = {
......@@ -375,7 +365,7 @@ class AgentHub:
)
# Build prompt based on target agent
if target_agent == "main":
if self.agents[target_agent].is_steward:
system_prompt = self._build_main_prompt(context, allowed_agent_codes=allowed_agent_codes)
else:
system_prompt = self._build_sub_agent_prompt(target_agent, context)
......@@ -410,7 +400,7 @@ class AgentHub:
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")
memory.add("user", user_query, agent_code=target_agent)
try:
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content() or ""
......@@ -447,7 +437,7 @@ class AgentHub:
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"]
valid = [c for c, a in self.agents.items() if not a.is_steward]
return (
f"错误:子 Agent '{agent_code}' 不存在。"
f"可用调用码: {valid}"
......@@ -561,10 +551,14 @@ class AgentHub:
子Agent的处理结果
"""
if not agent_code or not instruction:
# 动态获取一个非 steward 的 agent key 作为示例
sub_example = next(
(k for k, a in self.agents.items() if not a.is_steward), "sub_agent"
)
return ToolResponse(
content=[TextBlock(type="text", text=(
"错误:agent_code 和 instruction 都是必填参数。\n"
"正确示例:call_sub_agent(agent_code=\"meeting\", instruction=\"请帮我整理会议纪要\")"
f"正确示例:call_sub_agent(agent_code=\"{sub_example}\", instruction=\"请帮我处理任务\")"
))]
)
result = await self._call_sub_agent(agent_code, instruction)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!