Commit 9c4e1f28 by sunqi02

更新接口流程

https://github.com/mattpocock/skills
接口的内容和请求流程
1 parent 846ee6ff
from fastapi import APIRouter, Depends, HTTPException import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional from typing import Optional, List
from sqlalchemy.orm import Session from app.service.agent_hub import AgentHub
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse logger = logging.getLogger(__name__)
from app.service.agent_hub import AgentHub, AgentHubError
router = APIRouter() router = APIRouter()
class ChatRequest(BaseModel): # ── 新请求 Schema ──
session_id: str = Field(..., description="会话ID")
user_id: str = Field(..., description="用户ID") class GroupInfo(BaseModel):
room_id: str = Field(default="", description="群ID") group_contact_id: Optional[str] = Field(None, description="群联系人ID")
channel: str = Field(default="wechat_group", description="消息渠道") group_name: Optional[str] = Field(None, description="群名称")
query: str = Field(..., description="用户问题") bot_code: Optional[str] = Field(None, description="机器人编码")
mentioned_agent_code: Optional[str] = Field(None, description="@提及的Agent编码")
file_url: Optional[str] = Field(None, description="文件URL")
class PositionInfo(BaseModel):
position_id: Optional[int] = Field(None, description="岗位ID")
position_code: Optional[str] = Field(None, description="岗位编码") position_code: Optional[str] = Field(None, description="岗位编码")
position_name: Optional[str] = Field(None, description="岗位名称")
class ChatResponse(BaseModel): class AgentInfo(BaseModel):
session_id: str agent_id: int = Field(..., description="Agent ID,对应 agent.code")
response_agent_code: str agent_name: str = Field(..., description="Agent 名称")
response_content: str
routing_reason: str
processing_time_ms: float class MessageInfo(BaseModel):
msg_id: str = Field(..., description="消息ID")
msg_time: str = Field(..., description="消息时间")
sender_id: str = Field(..., description="发送者ID")
sender_name: Optional[str] = Field(None, description="发送者名称")
msg_type: str = Field(..., description="消息类型: text / image")
msg_content: str = Field(default="", description="消息内容(text 为文本,image 为图片 URL)")
payload: Optional[dict] = Field(default_factory=dict, description="扩展字段")
class ChatRequest(BaseModel):
session_id: str = Field(..., description="会话ID")
group: Optional[GroupInfo] = Field(default=None, description="群信息")
position: Optional[PositionInfo] = Field(default=None, description="岗位信息")
agents: List[AgentInfo] = Field(default_factory=list, description="可用 Agent 列表")
messages: List[MessageInfo] = Field(..., min_length=1, description="消息列表")
def get_agent_hub(db: Session = Depends(get_db)): def get_agent_hub():
from app.main import agent_hub_instance from app.main import agent_hub_instance
return agent_hub_instance return agent_hub_instance
@router.post("/completions", response_model=ChatResponse) @router.post("/completions")
async def chat( async def chat(
request: ChatRequest, request: ChatRequest,
background_tasks: BackgroundTasks,
agent_hub: AgentHub = Depends(get_agent_hub), agent_hub: AgentHub = Depends(get_agent_hub),
db: Session = Depends(get_db),
): ):
"""
接收消息后立即返回 200,Agent 在后台异步处理。
处理结果通过 PostReplyHook 发送到 IM。
"""
# 1. 提取 query:text 消息的 msg_content 用 \n 拼接
text_parts = []
file_url: Optional[str] = None
for msg in request.messages:
if msg.msg_type == "text":
if msg.msg_content:
text_parts.append(msg.msg_content)
elif msg.msg_type == "image":
if msg.msg_content and file_url is None:
file_url = msg.msg_content # 取第一张图片 URL
query = "\n".join(text_parts)
if not query:
raise HTTPException(status_code=400, detail="messages 中没有文本消息")
# 2. 提取 user_id:取最后一条消息的 sender_id
user_id = request.messages[-1].sender_id
# 3. 提取 room_id
room_id = ""
if request.group and request.group.group_contact_id:
room_id = request.group.group_contact_id
# 4. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None
if request.agents:
# 构建 agent.code → 内部名称(dict key)映射
code_to_name = {
cfg.code: name for name, 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)
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
# 5. 后台异步处理
background_tasks.add_task(
_process_message_async,
agent_hub=agent_hub,
session_id=request.session_id,
room_id=room_id,
user_id=user_id,
user_query=query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
)
return {"status": "ok", "session_id": request.session_id}
async def _process_message_async(
agent_hub: AgentHub,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try: try:
# Resolve position_code -> allowed agent codes await agent_hub.process_message(
allowed_agent_codes: Optional[list] = None session_id=session_id,
if request.position_code: room_id=room_id,
from app.model.position_tag import PositionTag user_id=user_id,
from app.model.agent import Agent, AgentPosition user_query=user_query,
file_url=file_url,
pos_tag = db.query(PositionTag).filter(
PositionTag.code == request.position_code
).first()
if pos_tag:
agent_ids = [
row.agent_id
for row in db.query(AgentPosition.agent_id).filter(
AgentPosition.position_id == pos_tag.id
).all()
]
if agent_ids:
agents = db.query(Agent.code).filter(
Agent.id.in_(agent_ids),
Agent.is_deleted == False,
).all()
allowed_agent_codes = [a.code for a in agents]
result = await agent_hub.process_message(
session_id=request.session_id,
room_id=request.room_id,
user_id=request.user_id,
user_query=request.query,
mentioned_agent_code=request.mentioned_agent_code,
channel=request.channel,
file_url=request.file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
) )
return ChatResponse(**result) except Exception:
except AgentHubError as e: logger.exception(
raise HTTPException(status_code=502, detail=str(e)) "Agent 后台处理失败: session=%s user=%s query=%s",
except ValueError as e: session_id, user_id, user_query[:50],
raise HTTPException(status_code=400, detail=str(e)) )
...@@ -287,7 +287,12 @@ class AgentHub: ...@@ -287,7 +287,12 @@ class AgentHub:
) )
# Run ReAct loop via framework # Run ReAct loop via framework
user_msg = Msg("user", user_query, "user") # 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")
response_msg = await agent.reply(user_msg) response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content() response_content = response_msg.get_text_content()
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
"agents": { "agents": {
"main": { "main": {
"name": "主 Agent", "name": "主 Agent",
"code": "main", "code": "100",
"role": "coordinator", "role": "coordinator",
"prompt_template": "你是{company}的智能助手,负责协调各个岗位Agent协作回答用户问题。\n\n## 核心规则(必须遵守)\n\n1. 当用户问题属于某个子Agent的职责范围时,你**必须调用 call_sub_agent 工具**来委托处理,**严禁**自己编造处理结果或口头描述\"正在处理\"。\n2. 收到子Agent返回结果后,直接整合回复用户,不要再次调用同一个子Agent。\n3. 只有当问题明确不属于任何子Agent职责时,才可以直接回答。\n\n## 可用子Agent(通过 call_sub_agent 调用)\n\n{duties}\n\n## 工具使用提醒\n\n你有一个 call_sub_agent(agent_code, instruction) 工具。用户不会看到你的内部思考过程,请直接用行动代替描述。", "prompt_template": "你是{company}的智能助手,负责协调各个岗位Agent协作回答用户问题。\n\n## 核心规则(必须遵守)\n\n1. 当用户问题属于某个子Agent的职责范围时,你**必须调用 call_sub_agent 工具**来委托处理,**严禁**自己编造处理结果或口头描述\"正在处理\"。\n2. 收到子Agent返回结果后,直接整合回复用户,不要再次调用同一个子Agent。\n3. 只有当问题明确不属于任何子Agent职责时,才可以直接回答。\n\n## 可用子Agent(通过 call_sub_agent 调用)\n\n{duties}\n\n## 工具使用提醒\n\n你有一个 call_sub_agent(agent_code, instruction) 工具。用户不会看到你的内部思考过程,请直接用行动代替描述。",
"skills": [] "skills": []
}, },
"meeting": { "meeting": {
"name": "会议纪要 Agent", "name": "会议纪要 Agent",
"code": "meeting", "code": "101",
"role": "会议纪要助手", "role": "会议纪要助手",
"prompt_template": "你是{company}的会议纪要助手,职责包括:{duties}。请根据用户的需求,帮助处理会议纪要相关的任务。", "prompt_template": "你是{company}的会议纪要助手,职责包括:{duties}。请根据用户的需求,帮助处理会议纪要相关的任务。",
"skills": ["meeting_minutes"] "skills": ["meeting_minutes"]
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
# 模拟用户消息发送到 Agent 服务 # 模拟用户消息发送到 Agent 服务
# 用法: ./send_test.sh "你的问题" # 用法: ./send_test.sh "你的问题"
# 例如: ./send_test.sh "帮我整理上周的会议纪要" # 例如: ./send_test.sh "帮我整理上周的会议纪要"
# ./send_test.sh "@meeting 帮我整理会议纪要"
QUERY="${1:-你好,请问你能帮我什么?}" QUERY="${1:-你好,请问你能帮我什么?}"
API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}" API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}"
...@@ -14,9 +13,9 @@ echo "" ...@@ -14,9 +13,9 @@ echo ""
echo "提问: ${QUERY}" echo "提问: ${QUERY}"
echo "" echo ""
# 用 jq 替换 query 字段(如果安装了 jq),否则用 sed # 用 jq 替换 messages[0].msg_content 字段
if command -v jq &> /dev/null; then if command -v jq &> /dev/null; then
PAYLOAD=$(jq --arg q "${QUERY}" '.query = $q' test_request.json) PAYLOAD=$(jq --arg q "${QUERY}" '.messages[0].msg_content = $q' test_request.json)
else else
PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json) PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json)
fi fi
......
{ {
"session_id": "test_sess_001", "session_id": "test_sess_001",
"user_id": "test_user_001", "group": {
"room_id": "test_room_001", "group_contact_id": "test_room_001",
"channel": "wechat_group", "group_name": "测试群",
"query": "{{QUERY}}", "bot_code": "test_bot"
"mentioned_agent_code": null, },
"file_url": null, "position": {
"position_code": "conference_assistant" "position_id": 1,
"position_code": "store_sales",
"position_name": "驻店销售岗"
},
"agents": [
{"agent_id": 101, "agent_name": "会议纪要 Agent"}
],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "test_user_001",
"sender_name": "测试用户",
"msg_type": "text",
"msg_content": "{{QUERY}}",
"payload": {}
}
]
} }
...@@ -88,6 +88,47 @@ fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub ...@@ -88,6 +88,47 @@ fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub
client = TestClient(fastapi_app) client = TestClient(fastapi_app)
# ── Helper: 构造新格式请求体 ──
def _make_request(
session_id: str = "sess_test",
query: str = "你好",
agents: list = None,
group_contact_id: str = "room_001",
sender_id: str = "user_001",
extra_messages: list = None,
) -> dict:
"""构造符合新 API 格式的请求体。"""
body = {
"session_id": session_id,
"group": {
"group_contact_id": group_contact_id,
"group_name": "测试群",
"bot_code": "test_bot",
},
"position": {
"position_id": 1,
"position_code": "store_sales",
"position_name": "驻店销售岗",
},
"agents": agents or [{"agent_id": 101, "agent_name": "会议纪要 Agent"}],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": sender_id,
"sender_name": "测试用户",
"msg_type": "text",
"msg_content": query,
"payload": {},
}
],
}
if extra_messages:
body["messages"].extend(extra_messages)
return body
# ── Fixtures ────────────────────────────────────────────────────── # ── Fixtures ──────────────────────────────────────────────────────
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def clean_session_tables(): def clean_session_tables():
...@@ -101,150 +142,157 @@ def clean_session_tables(): ...@@ -101,150 +142,157 @@ def clean_session_tables():
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
# API 层集成测试 — POST /api/v1/chat/completions # API 层集成测试 — POST /api/v1/chat/completions (新异步格式)
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
class TestChatCompletionsAPI: class TestChatCompletionsAPI:
def test_default_routing_to_main(self): def test_returns_200_with_new_format(self):
"""未 @提及 且 session 无继承 → 路由到 main""" """新格式请求 → 立即返回 200 + session_id"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好,我是智能助手,有什么可以帮助你的?")): with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)): with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json=_make_request(session_id="sess_api_001", query="你好"),
"session_id": "sess_api_001",
"user_id": "user_001",
"room_id": "room_001",
"query": "你好",
},
) )
assert resp.status_code == 200 assert resp.status_code == 200
data = resp.json()["data"] data = resp.json()["data"]
assert data["response_agent_code"] == "main" assert data["status"] == "ok"
assert data["routing_reason"] == "default" assert data["session_id"] == "sess_api_001"
assert len(data["response_content"]) > 0
assert data["processing_time_ms"] > 0 def test_session_created_from_group_contact_id(self):
"""group_contact_id → room_id, 会话被创建"""
def test_mention_routing_to_sub_agent(self): with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
"""@提及 meeting → 直接路由到 meeting"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理上次会议纪要如下:1. 项目进度讨论...")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)): with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json=_make_request(
"session_id": "sess_api_002", session_id="sess_api_002",
"user_id": "user_001", query="测试",
"room_id": "room_001", group_contact_id="grp_room_99",
"query": "整理会议纪要", ),
"mentioned_agent_code": "meeting",
},
) )
assert resp.status_code == 200 assert resp.status_code == 200
data = resp.json()["data"] session = test_hub.session_service.get_session("sess_api_002")
assert data["response_agent_code"] == "meeting" assert session is not None
assert data["routing_reason"] == "mention" assert session.room_id == "grp_room_99"
def test_inheritance_routing(self): def test_user_id_from_last_message_sender(self):
"""首次 @meeting,第二次不 @mention → 继承 meeting""" """user_id 从 messages 最后一条消息的 sender_id 推导"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容...")): with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)): with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# 请求 1:@mention resp = client.post(
r1 = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json=_make_request(
"session_id": "sess_api_003", session_id="sess_api_003",
"user_id": "user_001", query="你好",
"room_id": "room_001", extra_messages=[
"query": "查会议纪要", {
"mentioned_agent_code": "meeting", "msg_id": "m2",
}, "msg_time": "2026-05-23T10:01:00Z",
"sender_id": "user_last",
"sender_name": "最后发言者",
"msg_type": "text",
"msg_content": "第二条消息",
"payload": {},
}
],
),
) )
assert r1.status_code == 200
assert r1.json()["data"]["response_agent_code"] == "meeting"
# 请求 2:无 mention,应继承 meeting assert resp.status_code == 200
r2 = client.post( # 验证后台处理时 user_id 使用了最后一条 sender
messages = test_hub.session_service.get_session_messages("sess_api_003")
# 至少有 user 消息被存储
assert len(messages) >= 1
def test_image_message_extracts_file_url(self):
"""image 类型消息的 msg_content 作为图片 URL 传给 Agent"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("我看到了一张图片")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
"session_id": "sess_api_003", "session_id": "sess_img_001",
"user_id": "user_001", "messages": [
"room_id": "room_001", {
"query": "再查一个", "msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "user_001",
"msg_type": "text",
"msg_content": "这张图片是什么",
"payload": {},
},
{
"msg_id": "m2",
"msg_time": "2026-05-23T10:00:01Z",
"sender_id": "user_001",
"msg_type": "image",
"msg_content": "https://oss.example.com/img/photo.jpg",
"payload": {},
},
],
}, },
) )
assert r2.status_code == 200
assert r2.json()["data"]["response_agent_code"] == "meeting"
assert r2.json()["data"]["routing_reason"] == "inheritance"
def test_messages_accumulate_in_session(self): assert resp.status_code == 200
"""同一 session 多次请求,消息累积"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
for i in range(3):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_004",
"user_id": "user_001",
"room_id": "room_001",
"query": f"问题{i + 1}",
},
)
assert resp.status_code == 200
# Task 0: messages are in KV store, verify via SessionService
messages = test_hub.session_service.get_session_messages("sess_api_004")
assert len(messages) == 6 # 3 user + 3 assistant
def test_model_error_returns_502(self):
"""模型调用失败 → 502 Bad Gateway"""
mock_model = AsyncMock(side_effect=AgentHubError("模型API返回错误: 500"))
mock_model.stream = False
with patch.object(test_hub, 'model', new=mock_model): def test_agents_filter_allowed_codes(self):
"""agents 数组中的 agent_id 映射为 allowed_agent_codes"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)): with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# agents 中包含 agent_id=101(meeting agent)
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json=_make_request(
"session_id": "sess_err_001", session_id="sess_agent_filter",
"user_id": "user_001", query="你好",
"room_id": "room_001", agents=[{"agent_id": 101, "agent_name": "会议纪要 Agent"}],
"query": "触发错误", ),
},
) )
assert resp.status_code == 502 assert resp.status_code == 200
def test_missing_required_fields(self): def test_missing_messages_returns_400(self):
"""缺少必填字段 → 400(自定义异常处理器将 422 转为 400)""" """缺少 messages 字段 → 400"""
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={"session_id": "sess_incomplete"}, json={"session_id": "sess_no_msg"},
) )
assert resp.status_code == 400 assert resp.status_code == 400
def test_channel_default_value(self): def test_empty_messages_returns_400(self):
"""channel 字段默认为 wechat_group""" """空 messages 数组 → 400"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")): resp = client.post(
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)): "/api/v1/chat/completions",
resp = client.post( json={
"/api/v1/chat/completions", "session_id": "sess_empty_msg",
json={ "messages": [],
"session_id": "sess_api_005", },
"user_id": "user_001", )
"room_id": "room_001", assert resp.status_code == 400
"query": "测试",
},
)
assert resp.status_code == 200 def test_text_only_messages_returns_400(self):
# Task 0: verify channel from KV store, not DB """只有 image 消息没有 text → 400"""
session = test_hub.session_service.get_session("sess_api_005") resp = client.post(
assert session is not None "/api/v1/chat/completions",
assert session.channel == "wechat_group" json={
"session_id": "sess_img_only",
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "user_001",
"msg_type": "image",
"msg_content": "https://example.com/img.jpg",
"payload": {},
},
],
},
)
assert resp.status_code == 400
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
...@@ -354,7 +402,7 @@ class TestPostReplyHook: ...@@ -354,7 +402,7 @@ class TestPostReplyHook:
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试 # AgentHub 路由逻辑测试(直接调用 process_message)
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
...@@ -391,10 +439,131 @@ class TestAgentHubRouting: ...@@ -391,10 +439,131 @@ class TestAgentHubRouting:
session_id=sid, room_id="r1", user_id="u1", user_query="Q2" session_id=sid, room_id="r1", user_id="u1", user_query="Q2"
) )
# 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
@pytest.mark.asyncio
async def test_default_routing_to_main(self):
"""未指定 agent → 路由到 main"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好,我是智能助手")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_route_001",
room_id="room_001",
user_id="user_001",
user_query="你好",
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
assert len(result["response_content"]) > 0
@pytest.mark.asyncio
async def test_mention_routing_to_sub_agent(self):
"""mentioned_agent_code='meeting' → 直接路由到 meeting"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理会议纪要")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_route_002",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
)
assert result["response_agent_code"] == "meeting"
assert result["routing_reason"] == "mention"
@pytest.mark.asyncio
async def test_inheritance_routing(self):
"""首次 meeting,第二次不 mention → 继承 meeting"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
sid = "sess_route_003"
r1 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="查会议纪要",
mentioned_agent_code="meeting",
)
assert r1["response_agent_code"] == "meeting"
r2 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="再查一个",
)
assert r2["response_agent_code"] == "meeting"
assert r2["routing_reason"] == "inheritance"
@pytest.mark.asyncio
async def test_messages_accumulate(self):
"""同一 session 多次请求,消息累积"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
sid = "sess_accumulate"
for i in range(3):
await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query=f"问题{i + 1}",
)
messages = test_hub.session_service.get_session_messages(sid)
assert len(messages) == 6 # 3 user + 3 assistant
@pytest.mark.asyncio
async def test_channel_default_value(self):
"""channel 字段默认为 wechat_group"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
await test_hub.process_message(
session_id="sess_channel",
room_id="room_001",
user_id="user_001",
user_query="测试",
)
session = test_hub.session_service.get_session("sess_channel")
assert session is not None
assert session.channel == "wechat_group"
@pytest.mark.asyncio
async def test_image_url_appended_to_query(self):
"""file_url 不为空时,图片 URL 追加到 query 中"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("我看到图片了")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_img",
room_id="room_001",
user_id="user_001",
user_query="这张图片是什么",
file_url="https://oss.example.com/img/photo.jpg",
)
assert result["response_content"] is not None
@pytest.mark.asyncio
async def test_allowed_agent_codes_restricts_routing(self):
"""allowed_agent_codes 限制路由范围"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# allowed 中不包含 meeting,mention meeting 应回退到 main
result = await test_hub.process_message(
session_id="sess_restricted",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
allowed_agent_codes=[], # 空列表,不允许任何子 agent
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "position_restricted"
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
# 协作层集成测试 — call_sub_agent 串行链 # 协作层集成测试 — call_sub_agent 串行链
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!