Commit 3de190ae by sunqi02

数据流中将bot_code改为bot_id

1 parent bee95282
...@@ -14,7 +14,6 @@ router = APIRouter() ...@@ -14,7 +14,6 @@ router = APIRouter()
class GroupInfo(BaseModel): class GroupInfo(BaseModel):
group_contact_id: Optional[str] = Field(None, description="群联系人ID") group_contact_id: Optional[str] = Field(None, description="群联系人ID")
group_name: Optional[str] = Field(None, description="群名称") group_name: Optional[str] = Field(None, description="群名称")
bot_code: Optional[str] = Field(None, description="机器人编码")
class PositionInfo(BaseModel): class PositionInfo(BaseModel):
...@@ -25,7 +24,7 @@ class PositionInfo(BaseModel): ...@@ -25,7 +24,7 @@ class PositionInfo(BaseModel):
class AgentInfo(BaseModel): class AgentInfo(BaseModel):
agent_id: int = Field(..., description="Agent ID,对应 agent.code") agent_id: int = Field(..., description="Agent ID,对应 agent.code")
bot_code: str = Field(..., description="机器人账号,格式 channel:bot_id,用于发送消息") bot_id: str = Field(..., description="机器人账号,用于发送消息")
class MessageInfo(BaseModel): class MessageInfo(BaseModel):
...@@ -84,27 +83,27 @@ async def chat( ...@@ -84,27 +83,27 @@ async def chat(
if request.group and request.group.group_contact_id: if request.group and request.group.group_contact_id:
room_id = request.group.group_contact_id room_id = request.group.group_contact_id
# 4. 提取 allowed_agent_codes 和 bot_code_mapping:agent_id → 内部 agent code 映射 # 4. 提取 allowed_agent_codes 和 bot_id_mapping:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None allowed_agent_codes: Optional[list] = None
bot_code_mapping: Optional[Dict[str, str]] = None bot_id_mapping: Optional[Dict[str, str]] = None
if request.agents: if request.agents:
# 构建 agent.code → 内部名称(dict key)映射 # 构建 agent.code → 内部名称(dict key)映射
code_to_name = { code_to_name = {
cfg.code: name for name, cfg in agent_hub.agents.items() cfg.code: name for name, cfg in agent_hub.agents.items()
} }
allowed_agent_codes = [] allowed_agent_codes = []
bot_code_mapping = {} bot_id_mapping = {}
for agent_info in request.agents: for agent_info in request.agents:
agent_code_str = str(agent_info.agent_id) agent_code_str = str(agent_info.agent_id)
internal_name = code_to_name.get(agent_code_str) internal_name = code_to_name.get(agent_code_str)
if internal_name: if internal_name:
if internal_name != "main": if internal_name != "main":
allowed_agent_codes.append(internal_name) allowed_agent_codes.append(internal_name)
bot_code_mapping[internal_name] = agent_info.bot_code bot_id_mapping[internal_name] = agent_info.bot_id
if not allowed_agent_codes: if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由 allowed_agent_codes = None # 无有效子 agent,走默认路由
if not bot_code_mapping: if not bot_id_mapping:
bot_code_mapping = None bot_id_mapping = None
# 5. 后台异步处理 # 5. 后台异步处理
background_tasks.add_task( background_tasks.add_task(
...@@ -116,7 +115,7 @@ async def chat( ...@@ -116,7 +115,7 @@ async def chat(
user_query=query, user_query=query,
file_url=file_url, file_url=file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping, bot_id_mapping=bot_id_mapping,
) )
return {"status": "ok", "session_id": request.session_id} return {"status": "ok", "session_id": request.session_id}
...@@ -130,7 +129,7 @@ async def _process_message_async( ...@@ -130,7 +129,7 @@ async def _process_message_async(
user_query: str, user_query: str,
file_url: Optional[str], file_url: Optional[str],
allowed_agent_codes: Optional[list], allowed_agent_codes: Optional[list],
bot_code_mapping: Optional[Dict[str, str]] = None, bot_id_mapping: Optional[Dict[str, str]] = None,
): ):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。""" """后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try: try:
...@@ -141,7 +140,7 @@ async def _process_message_async( ...@@ -141,7 +140,7 @@ async def _process_message_async(
user_query=user_query, user_query=user_query,
file_url=file_url, file_url=file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping, bot_id_mapping=bot_id_mapping,
) )
except Exception: except Exception:
logger.exception( logger.exception(
......
...@@ -7,7 +7,7 @@ from app.hooks.base import Hook ...@@ -7,7 +7,7 @@ from app.hooks.base import Hook
class IMSender(Protocol): class IMSender(Protocol):
"""Protocol for IM service — matches 机器人对接说明 API""" """Protocol for IM service — matches 机器人对接说明 API"""
async def send_message( async def send_message(
self, bot_code: str, content: str, contact_id: str, at_list: str = "" self, bot_id: str, content: str, contact_id: str, at_list: str = ""
) -> Dict[str, Any]: ) -> Dict[str, Any]:
... ...
...@@ -33,14 +33,14 @@ class PostReplyHook(Hook): ...@@ -33,14 +33,14 @@ class PostReplyHook(Hook):
response_content = context.get("response_content") response_content = context.get("response_content")
room_id = context.get("room_id") room_id = context.get("room_id")
mentioned_list = context.get("mentioned_list", []) mentioned_list = context.get("mentioned_list", [])
bot_code_mapping = context.get("bot_code_mapping", {}) bot_id_mapping = context.get("bot_id_mapping", {})
if not agent_name or not response_content: if not agent_name or not response_content:
return None return None
# bot_code 优先从请求映射中取,兜底用静态配置 # bot_id 优先从请求映射中取,兜底用静态配置
bot_code = bot_code_mapping.get(agent_name) or self.account_mapping.get(agent_name) bot_id = bot_id_mapping.get(agent_name) or self.account_mapping.get(agent_name)
if not bot_code: if not bot_id:
return None return None
clean_content = self._strip_thinking_blocks(response_content) clean_content = self._strip_thinking_blocks(response_content)
...@@ -50,7 +50,7 @@ class PostReplyHook(Hook): ...@@ -50,7 +50,7 @@ class PostReplyHook(Hook):
at_list = ",".join(mentioned_list) if mentioned_list else "" at_list = ",".join(mentioned_list) if mentioned_list else ""
result = await self.im_service.send_message( result = await self.im_service.send_message(
bot_code=bot_code, bot_id=bot_id,
content=clean_content, content=clean_content,
contact_id=room_id, contact_id=room_id,
at_list=at_list, at_list=at_list,
......
...@@ -207,7 +207,7 @@ class AgentHub: ...@@ -207,7 +207,7 @@ class AgentHub:
channel: str = "wechat_group", channel: str = "wechat_group",
file_url: Optional[str] = None, file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None, allowed_agent_codes: Optional[list] = None,
bot_code_mapping: Optional[Dict[str, str]] = None, bot_id_mapping: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
Process a user message end-to-end. Process a user message end-to-end.
...@@ -318,7 +318,7 @@ class AgentHub: ...@@ -318,7 +318,7 @@ class AgentHub:
"response_content": response_content, "response_content": response_content,
"room_id": room_id, "room_id": room_id,
"mentioned_list": [user_id], "mentioned_list": [user_id],
"bot_code_mapping": bot_code_mapping or {}, "bot_id_mapping": bot_id_mapping or {},
}) })
processing_time_ms = (time.time() - start_time) * 1000 processing_time_ms = (time.time() - start_time) * 1000
......
...@@ -11,13 +11,13 @@ class ConsoleIMService: ...@@ -11,13 +11,13 @@ class ConsoleIMService:
async def send_message( async def send_message(
self, self,
bot_code: str, bot_id: str,
content: str, content: str,
contact_id: str, contact_id: str,
at_list: str = "", at_list: str = "",
) -> Dict[str, Any]: ) -> Dict[str, Any]:
payload = { payload = {
"bot_code": bot_code, "bot_id": bot_id,
"content": content, "content": content,
"contact_id": contact_id, "contact_id": contact_id,
"msg_type": "text", "msg_type": "text",
...@@ -31,7 +31,7 @@ class ConsoleIMService: ...@@ -31,7 +31,7 @@ class ConsoleIMService:
print(json.dumps(payload, ensure_ascii=False, indent=2)) print(json.dumps(payload, ensure_ascii=False, indent=2))
print("=" * 50 + "\n") print("=" * 50 + "\n")
return {"status": "printed", "bot_code": bot_code} return {"status": "printed", "bot_id": bot_id}
async def close(self): async def close(self):
pass pass
...@@ -27,7 +27,7 @@ class IMService: ...@@ -27,7 +27,7 @@ class IMService:
async def send_message( async def send_message(
self, self,
bot_code: str, bot_id: str,
content: str, content: str,
contact_id: str, contact_id: str,
at_list: str = "", at_list: str = "",
...@@ -35,7 +35,7 @@ class IMService: ...@@ -35,7 +35,7 @@ class IMService:
"""Send a text message via IM business API. """Send a text message via IM business API.
Args: Args:
bot_code: 机器人账号,格式 channel:bot_id (e.g. wt_ww:RBT001) bot_id: 机器人账号 (e.g. wt_ww:RBT001)
content: 消息正文 content: 消息正文
contact_id: 目标群/联系人 ID (c_contacts.contact_id) contact_id: 目标群/联系人 ID (c_contacts.contact_id)
at_list: @列表,逗号分隔成员昵称 (群聊有效) at_list: @列表,逗号分隔成员昵称 (群聊有效)
...@@ -43,7 +43,7 @@ class IMService: ...@@ -43,7 +43,7 @@ class IMService:
payload = { payload = {
"contact_id": contact_id, "contact_id": contact_id,
"content": content, "content": content,
"bot_code": bot_code, "bot_id": bot_id,
"msg_type": "text", "msg_type": "text",
} }
if at_list: if at_list:
......
{ {
"session_id": "test_sess_001", "session_id": "test_sess_001",
"group": { "group": {
"group_contact_id": "test_room_001", "group_contact_id": "4BD6DE10053F765A7F161DF36A6E0031901A2DDBF0758730A19ADA8F0B6DD9F8",
"group_name": "测试群", "group_name": "测试群"
"bot_code": "test_bot"
}, },
"position": { "position": {
"position_id": 1, "position_id": 1,
...@@ -11,7 +10,7 @@ ...@@ -11,7 +10,7 @@
"position_name": "驻店销售岗" "position_name": "驻店销售岗"
}, },
"agents": [ "agents": [
{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"} {"agent_id": 101, "bot_id": "ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82"}
], ],
"messages": [ "messages": [
{ {
......
...@@ -104,14 +104,13 @@ def _make_request( ...@@ -104,14 +104,13 @@ def _make_request(
"group": { "group": {
"group_contact_id": group_contact_id, "group_contact_id": group_contact_id,
"group_name": "测试群", "group_name": "测试群",
"bot_code": "test_bot",
}, },
"position": { "position": {
"position_id": 1, "position_id": 1,
"position_code": "store_sales", "position_code": "store_sales",
"position_name": "驻店销售岗", "position_name": "驻店销售岗",
}, },
"agents": agents or [{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}], "agents": agents or [{"agent_id": 101, "bot_id": "wt_ww:bot_meeting_001"}],
"messages": [ "messages": [
{ {
"msg_id": "m1", "msg_id": "m1",
...@@ -249,7 +248,7 @@ class TestChatCompletionsAPI: ...@@ -249,7 +248,7 @@ class TestChatCompletionsAPI:
json=_make_request( json=_make_request(
session_id="sess_agent_filter", session_id="sess_agent_filter",
query="你好", query="你好",
agents=[{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}], agents=[{"agent_id": 101, "bot_id": "wt_ww:bot_meeting_001"}],
), ),
) )
...@@ -401,8 +400,8 @@ class TestPostReplyHook: ...@@ -401,8 +400,8 @@ class TestPostReplyHook:
mock_im.send_message.assert_not_called() mock_im.send_message.assert_not_called()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_uses_bot_code_from_request_mapping(self): async def test_uses_bot_id_from_request_mapping(self):
"""bot_code_mapping 优先于 account_mapping""" """bot_id_mapping 优先于 account_mapping"""
from app.hooks.post_reply import PostReplyHook from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock() mock_im = AsyncMock()
...@@ -417,16 +416,16 @@ class TestPostReplyHook: ...@@ -417,16 +416,16 @@ class TestPostReplyHook:
"response_content": "回复", "response_content": "回复",
"room_id": "room_001", "room_id": "room_001",
"mentioned_list": [], "mentioned_list": [],
"bot_code_mapping": {"main": "wt_ww:request_bot"}, "bot_id_mapping": {"main": "wt_ww:request_bot"},
}) })
mock_im.send_message.assert_called_once() mock_im.send_message.assert_called_once()
kwargs = mock_im.send_message.call_args[1] kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:request_bot" assert kwargs["bot_id"] == "wt_ww:request_bot"
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_falls_back_to_account_mapping(self): async def test_falls_back_to_account_mapping(self):
"""bot_code_mapping 为空时,回退到 account_mapping""" """bot_id_mapping 为空时,回退到 account_mapping"""
from app.hooks.post_reply import PostReplyHook from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock() mock_im = AsyncMock()
...@@ -443,11 +442,11 @@ class TestPostReplyHook: ...@@ -443,11 +442,11 @@ class TestPostReplyHook:
}) })
kwargs = mock_im.send_message.call_args[1] kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "static_bot" assert kwargs["bot_id"] == "static_bot"
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_sends_with_new_param_names(self): async def test_sends_with_new_param_names(self):
"""验证 IM 调用使用 bot_code / contact_id / at_list 参数""" """验证 IM 调用使用 bot_id / contact_id / at_list 参数"""
from app.hooks.post_reply import PostReplyHook from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock() mock_im = AsyncMock()
...@@ -465,7 +464,7 @@ class TestPostReplyHook: ...@@ -465,7 +464,7 @@ class TestPostReplyHook:
}) })
kwargs = mock_im.send_message.call_args[1] kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:bot_001" assert kwargs["bot_id"] == "wt_ww:bot_001"
assert kwargs["contact_id"] == "wr_xxxxx" assert kwargs["contact_id"] == "wr_xxxxx"
assert kwargs["content"] == "会议纪要已整理" assert kwargs["content"] == "会议纪要已整理"
assert kwargs["at_list"] == "张三,李四" assert kwargs["at_list"] == "张三,李四"
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!