Commit bee95282 by sunqi02

消息发送接入机器人服务

1 parent 6d7282f9
import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field
from typing import Optional, List
from typing import Dict, Optional, List
from app.service.agent_hub import AgentHub
logger = logging.getLogger(__name__)
......@@ -25,7 +25,7 @@ class PositionInfo(BaseModel):
class AgentInfo(BaseModel):
agent_id: int = Field(..., description="Agent ID,对应 agent.code")
agent_name: str = Field(..., description="Agent 名称")
bot_code: str = Field(..., description="机器人账号,格式 channel:bot_id,用于发送消息")
class MessageInfo(BaseModel):
......@@ -84,21 +84,27 @@ async def chat(
if request.group and request.group.group_contact_id:
room_id = request.group.group_contact_id
# 4. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射
# 4. 提取 allowed_agent_codes 和 bot_code_mapping:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None
bot_code_mapping: Optional[Dict[str, str]] = 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 = []
bot_code_mapping = {}
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 internal_name:
if internal_name != "main":
allowed_agent_codes.append(internal_name)
bot_code_mapping[internal_name] = agent_info.bot_code
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
if not bot_code_mapping:
bot_code_mapping = None
# 5. 后台异步处理
background_tasks.add_task(
......@@ -110,6 +116,7 @@ async def chat(
user_query=query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping,
)
return {"status": "ok", "session_id": request.session_id}
......@@ -123,6 +130,7 @@ async def _process_message_async(
user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
bot_code_mapping: Optional[Dict[str, str]] = None,
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try:
......@@ -133,6 +141,7 @@ async def _process_message_async(
user_query=user_query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping,
)
except Exception:
logger.exception(
......
......@@ -5,9 +5,9 @@ from app.hooks.base import Hook
class IMSender(Protocol):
"""Protocol for IM service — implementation in Task 5"""
"""Protocol for IM service — matches 机器人对接说明 API"""
async def send_message(
self, account: str, content: str, room_id: str, mentioned_list: list[str]
self, bot_code: str, content: str, contact_id: str, at_list: str = ""
) -> Dict[str, Any]:
...
......@@ -33,23 +33,27 @@ class PostReplyHook(Hook):
response_content = context.get("response_content")
room_id = context.get("room_id")
mentioned_list = context.get("mentioned_list", [])
bot_code_mapping = context.get("bot_code_mapping", {})
if not agent_name or not response_content:
return None
bot_account = self.account_mapping.get(agent_name)
if not bot_account:
# bot_code 优先从请求映射中取,兜底用静态配置
bot_code = bot_code_mapping.get(agent_name) or self.account_mapping.get(agent_name)
if not bot_code:
return None
clean_content = self._strip_thinking_blocks(response_content)
if not clean_content:
return None
at_list = ",".join(mentioned_list) if mentioned_list else ""
result = await self.im_service.send_message(
account=bot_account,
bot_code=bot_code,
content=clean_content,
room_id=room_id,
mentioned_list=mentioned_list
contact_id=room_id,
at_list=at_list,
)
return result
......
......@@ -207,6 +207,7 @@ class AgentHub:
channel: str = "wechat_group",
file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None,
bot_code_mapping: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""
Process a user message end-to-end.
......@@ -316,7 +317,8 @@ class AgentHub:
"agent_name": target_agent,
"response_content": response_content,
"room_id": room_id,
"mentioned_list": [user_id]
"mentioned_list": [user_id],
"bot_code_mapping": bot_code_mapping or {},
})
processing_time_ms = (time.time() - start_time) * 1000
......
"""Console IM service — prints hook output instead of sending to real IM."""
import json
from typing import Dict, List, Any, Optional
from typing import Dict, Any, Optional
class ConsoleIMService:
......@@ -11,17 +11,19 @@ class ConsoleIMService:
async def send_message(
self,
account: str,
bot_code: str,
content: str,
room_id: str,
mentioned_list: Optional[List[str]] = None,
contact_id: str,
at_list: str = "",
) -> Dict[str, Any]:
payload = {
"account": account,
"bot_code": bot_code,
"content": content,
"room_id": room_id,
"mentioned_list": mentioned_list or [],
"contact_id": contact_id,
"msg_type": "text",
}
if at_list:
payload["at_list"] = at_list
print("\n" + "=" * 50)
print(" [Hook: post_reply] → 计划发送到 IM")
......@@ -29,7 +31,7 @@ class ConsoleIMService:
print(json.dumps(payload, ensure_ascii=False, indent=2))
print("=" * 50 + "\n")
return {"status": "printed", "account": account}
return {"status": "printed", "bot_code": bot_code}
async def close(self):
pass
from typing import Dict, List, Any, Optional
from typing import Dict, Any, Optional
import httpx
......@@ -8,7 +8,11 @@ class IMServiceError(Exception):
class IMService:
"""Service for sending messages via IM (自建服务)"""
"""Service for sending messages via IM business API (机器人对接说明)
Calls: POST {base_url}/api/v1/business/messages/send
Auth: X-Api-Key header
"""
def __init__(self, base_url: str, api_key: Optional[str] = None):
self.base_url = base_url.rstrip("/")
......@@ -23,25 +27,35 @@ class IMService:
async def send_message(
self,
account: str,
bot_code: str,
content: str,
room_id: str,
mentioned_list: List[str] = None
contact_id: str,
at_list: str = "",
) -> Dict[str, Any]:
"""Send a text message via IM business API.
Args:
bot_code: 机器人账号,格式 channel:bot_id (e.g. wt_ww:RBT001)
content: 消息正文
contact_id: 目标群/联系人 ID (c_contacts.contact_id)
at_list: @列表,逗号分隔成员昵称 (群聊有效)
"""
payload = {
"account": account,
"contact_id": contact_id,
"content": content,
"room_id": room_id,
"mentioned_list": mentioned_list or []
"bot_code": bot_code,
"msg_type": "text",
}
if at_list:
payload["at_list"] = at_list
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
headers["X-Api-Key"] = self.api_key
try:
response = await self.client.post(
f"{self.base_url}/api/send_message",
f"{self.base_url}/api/v1/business/messages/send",
json=payload,
headers=headers
)
......
......@@ -11,7 +11,7 @@
"position_name": "驻店销售岗"
},
"agents": [
{"agent_id": 101, "agent_name": "会议纪要 Agent"}
{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}
],
"messages": [
{
......
......@@ -111,7 +111,7 @@ def _make_request(
"position_code": "store_sales",
"position_name": "驻店销售岗",
},
"agents": agents or [{"agent_id": 101, "agent_name": "会议纪要 Agent"}],
"agents": agents or [{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}],
"messages": [
{
"msg_id": "m1",
......@@ -249,7 +249,7 @@ class TestChatCompletionsAPI:
json=_make_request(
session_id="sess_agent_filter",
query="你好",
agents=[{"agent_id": 101, "agent_name": "会议纪要 Agent"}],
agents=[{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}],
),
)
......@@ -400,6 +400,76 @@ class TestPostReplyHook:
assert result is None
mock_im.send_message.assert_not_called()
@pytest.mark.asyncio
async def test_uses_bot_code_from_request_mapping(self):
"""bot_code_mapping 优先于 account_mapping"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "static_bot"}
)
await hook.execute({
"agent_name": "main",
"response_content": "回复",
"room_id": "room_001",
"mentioned_list": [],
"bot_code_mapping": {"main": "wt_ww:request_bot"},
})
mock_im.send_message.assert_called_once()
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:request_bot"
@pytest.mark.asyncio
async def test_falls_back_to_account_mapping(self):
"""bot_code_mapping 为空时,回退到 account_mapping"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "static_bot"}
)
await hook.execute({
"agent_name": "main",
"response_content": "回复",
"room_id": "room_001",
})
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "static_bot"
@pytest.mark.asyncio
async def test_sends_with_new_param_names(self):
"""验证 IM 调用使用 bot_code / contact_id / at_list 参数"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"meeting": "wt_ww:bot_001"}
)
await hook.execute({
"agent_name": "meeting",
"response_content": "会议纪要已整理",
"room_id": "wr_xxxxx",
"mentioned_list": ["张三", "李四"],
})
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:bot_001"
assert kwargs["contact_id"] == "wr_xxxxx"
assert kwargs["content"] == "会议纪要已整理"
assert kwargs["at_list"] == "张三,李四"
# ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试(直接调用 process_message)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!