Commit 0744dd31 by sunqi02

feat(layer5): add call_sub_agent tool + result review for serial chain collaboration

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 1cf6119c
...@@ -12,6 +12,7 @@ from agentscope.model import OpenAIChatModel ...@@ -12,6 +12,7 @@ from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.message._message_block import TextBlock, ToolUseBlock, ToolResultBlock from agentscope.message._message_block import TextBlock, ToolUseBlock, ToolResultBlock
from agentscope.tool._response import ToolResponse
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -78,6 +79,14 @@ class AgentHub: ...@@ -78,6 +79,14 @@ class AgentHub:
# Load skills metadata from Toolkit # Load skills metadata from Toolkit
self.skills = config_loader.load_skills_from_toolkit(self.toolkit) self.skills = config_loader.load_skills_from_toolkit(self.toolkit)
# 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",
)
def _build_main_prompt(self, context: Dict[str, Any]) -> str: def _build_main_prompt(self, context: Dict[str, Any]) -> str:
""" """
Build the main agent's prompt including ALL sub-agent duty descriptions. Build the main agent's prompt including ALL sub-agent duty descriptions.
...@@ -107,7 +116,18 @@ class AgentHub: ...@@ -107,7 +116,18 @@ class AgentHub:
skills=skills_text skills=skills_text
) )
return prompt review_guide = """
## 工作规则
收到子Agent的返回后,你需要判断:
1. 子Agent的结果是否完整、可用?
2. 是否还需要其他子Agent协作?(如:纪要整理后需要提取待办)
3. 是否可以直接整合结果回复用户?
如果还需要继续处理,调用相应的子Agent(call_sub_agent)或工具。
如果已经可以回复,请整合所有结果,用自然语言回复用户。
"""
return prompt + review_guide
def _build_sub_agent_prompt(self, agent_code: str, context: Dict[str, Any]) -> str: 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.""" """Build prompt for a sub-agent when handling a routed query."""
...@@ -362,7 +382,7 @@ class AgentHub: ...@@ -362,7 +382,7 @@ class AgentHub:
input=tool_input, input=tool_input,
) )
tool_response_content = "" tool_response_content = ""
async for resp in self.toolkit.call_tool_function(tool_use_block): resp = await self.toolkit.call_tool_function(tool_use_block)
tool_response_content = resp.content if hasattr(resp, 'content') else str(resp) tool_response_content = resp.content if hasattr(resp, 'content') else str(resp)
current_messages.append({ current_messages.append({
...@@ -373,6 +393,40 @@ class AgentHub: ...@@ -373,6 +393,40 @@ class AgentHub:
raise AgentHubError("ReAct循环超过最大次数(10)") raise AgentHubError("ReAct循环超过最大次数(10)")
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""Call a sub-agent to handle a task, return its reasoning result."""
if agent_code not in self.agents:
return f"错误:子 Agent '{agent_code}' 不存在"
sub_prompt = self._build_sub_agent_prompt(agent_code, {})
sub_messages: list[dict] = [{"role": "system", "content": sub_prompt}]
sub_messages.append({"role": "user", "content": instruction})
# Sub-agent uses pure text reasoning (no tools), single iteration
response = await self._call_model(sub_messages, tools=None, max_iterations=1)
return response
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:
"""Call a sub-agent to handle a specific task.
Args:
agent_code: Sub-agent code, e.g. meeting / support
instruction: Specific instructions for the sub-agent
Returns:
Sub-agent's processing result
"""
result = await self._call_sub_agent(agent_code, instruction)
return ToolResponse(
content=[TextBlock(type="text", text=result)]
)
return call_sub_agent
async def close(self): async def close(self):
"""Clean up resources (no-op with AgentScope).""" """Clean up resources (no-op with AgentScope)."""
pass pass
...@@ -38,7 +38,7 @@ fastapi_app.dependency_overrides[get_db] = override_get_db ...@@ -38,7 +38,7 @@ fastapi_app.dependency_overrides[get_db] = override_get_db
# ── 创建测试 AgentHub(共享同一个测试 DB)───────────────────────── # ── 创建测试 AgentHub(共享同一个测试 DB)─────────────────────────
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.service.session_service import SessionService from app.service.session_service import SessionService
from app.service.agent_hub import AgentHub from app.service.agent_hub import AgentHub, AgentHubError
def _make_test_hub(): def _make_test_hub():
...@@ -380,3 +380,88 @@ class TestAgentHubRouting: ...@@ -380,3 +380,88 @@ class TestAgentHubRouting:
# Task 0: messages are in KV store # Task 0: messages are in KV store
messages = test_hub.session_service.get_session_messages(sid) messages = test_hub.session_service.get_session_messages(sid)
assert len(messages) == 4 # 2 user + 2 assistant assert len(messages) == 4 # 2 user + 2 assistant
# ═══════════════════════════════════════════════════════════════════
# 协作层集成测试 — call_sub_agent 串行链
# ═══════════════════════════════════════════════════════════════════
class TestCollaboration:
"""Serial chain collaboration integration tests — simulate multi-call ReAct with call_sub_agent."""
@pytest.mark.asyncio
async def test_serial_chain_two_sub_agents(self):
"""Simulate: model calls meeting → then task → then returns integrated result."""
# Three model calls: tool_call(meeting) → tool_call(task) → text reply
responses = [
[{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
"input": {"agent_code": "meeting", "instruction": "整理纪要"}}],
[{"type": "tool_use", "id": "call_2", "name": "call_sub_agent",
"input": {"agent_code": "task", "instruction": "提取待办"}}],
[{"type": "text", "text": "已整理纪要并提取待办:1.提交方案 2.确认预算"}],
]
call_count = [0]
def _make_resp(blocks):
r = MagicMock()
r.content = blocks
return r
async def model_side_effect(*args, **kwargs):
idx = min(call_count[0], len(responses) - 1)
result = _make_resp(responses[idx])
call_count[0] += 1
return result
async def mock_sub_call(agent_code, instruction):
if agent_code == "meeting":
return "纪要: 讨论了Q2预算和团队调整"
elif agent_code == "task":
return "待办: 1.提交Q2预算 2.人员调整方案"
return ""
async def noop_format(msgs):
return msgs
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
result = await test_hub.process_message(
session_id="sess_collab_001",
room_id="room_001",
user_id="u1",
user_query="整理纪要并提取待办",
)
assert "已整理" in result["response_content"]
@pytest.mark.asyncio
async def test_max_iterations_limit(self):
"""Loop exceeding 10 iterations should raise AgentHubError."""
tool_call_blocks = [
{"type": "tool_use", "id": "call_x", "name": "call_sub_agent",
"input": {"agent_code": "meeting", "instruction": "x"}}
]
async def model_side_effect(*args, **kwargs):
r = MagicMock()
r.content = tool_call_blocks
return r
async def mock_sub_call(*args, **kwargs):
return "result"
async def noop_format(msgs):
return msgs
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
with pytest.raises(AgentHubError, match="最大次数"):
await test_hub.process_message(
session_id="sess_limit_001",
room_id="room_001",
user_id="u1",
user_query="test",
)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!