Commit ad0b8f26 by sunqi02 Committed by 胡悦

fix(agent_hub): 更新消息处理逻辑以支持多种消息类型的内容拼接

1 parent 1c4887a3
...@@ -2,8 +2,7 @@ import logging ...@@ -2,8 +2,7 @@ import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, List from typing import Optional, List
from app.agent_core.agent_hub import AgentHub from app.service.agent_hub import AgentHub
from app.agent_core.message_gate import MessageGate
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -29,8 +28,6 @@ class AgentInfo(BaseModel): ...@@ -29,8 +28,6 @@ class AgentInfo(BaseModel):
agent_name: Optional[str] = Field(None, description="Agent 名称") agent_name: Optional[str] = Field(None, description="Agent 名称")
bot_id: Optional[str] = Field(None, description="机器人编码") bot_id: Optional[str] = Field(None, description="机器人编码")
is_steward: Optional[bool] = Field(False, description="是否为管家 Agent") is_steward: Optional[bool] = Field(False, description="是否为管家 Agent")
status: Optional[str] = Field("enable", description="状态: enable/disable")
is_deleted: Optional[bool] = Field(False, description="是否已删除")
class MessageInfo(BaseModel): class MessageInfo(BaseModel):
...@@ -38,8 +35,8 @@ class MessageInfo(BaseModel): ...@@ -38,8 +35,8 @@ class MessageInfo(BaseModel):
msg_time: str = Field(..., description="消息时间") msg_time: str = Field(..., description="消息时间")
sender_id: str = Field(..., description="发送者ID") sender_id: str = Field(..., description="发送者ID")
sender_name: Optional[str] = Field(None, description="发送者名称") sender_name: Optional[str] = Field(None, description="发送者名称")
msg_type: str = Field(..., description="消息类型: text(文本)/ 其余全部视为文件") msg_type: str = Field(..., description="消息类型: text / image")
msg_content: str = Field(default="", description="消息内容(text 为文本,其余类型为文件/图片 URL)") msg_content: str = Field(default="", description="消息内容(text 为文本,image 为图片 URL)")
payload: Optional[dict] = Field(default_factory=dict, description="扩展字段") payload: Optional[dict] = Field(default_factory=dict, description="扩展字段")
...@@ -55,17 +52,11 @@ def get_agent_hub(): ...@@ -55,17 +52,11 @@ def get_agent_hub():
return agent_hub_instance return agent_hub_instance
def get_message_gate():
from app.main import message_gate_instance
return message_gate_instance
@router.post("/completions") @router.post("/completions")
async def chat( async def chat(
request: ChatRequest, request: ChatRequest,
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
agent_hub: AgentHub = Depends(get_agent_hub), agent_hub: AgentHub = Depends(get_agent_hub),
message_gate: MessageGate = Depends(get_message_gate),
): ):
""" """
接收消息后立即返回 200,Agent 在后台异步处理。 接收消息后立即返回 200,Agent 在后台异步处理。
...@@ -78,150 +69,83 @@ async def chat( ...@@ -78,150 +69,83 @@ async def chat(
if not session_id: if not session_id:
raise HTTPException(status_code=400, detail="group.group_contact_id 不能为空") raise HTTPException(status_code=400, detail="group.group_contact_id 不能为空")
# 1. 提取 query:只有 text 类型为文本,其余全部当文件处理 # 1. 提取 query:text/other/file 消息的 msg_content 用 \n 拼接
text_parts = [] text_parts = []
file_url: Optional[str] = None file_url: Optional[str] = None
for msg in request.messages: for msg in request.messages:
if msg.msg_type == "text": if msg.msg_type in ("text", "other", "file"):
if msg.msg_content: if msg.msg_content:
text_parts.append(msg.msg_content) text_parts.append(msg.msg_content)
else: elif msg.msg_type == "image":
if msg.msg_content and file_url is None: if msg.msg_content and file_url is None:
file_url = msg.msg_content # 取第一个非 text 消息的 URL file_url = msg.msg_content # 取第一张图片 URL
query = "\n".join(text_parts) query = "\n".join(text_parts)
has_any_content = bool(query) or bool(file_url) if not query:
if not has_any_content: raise HTTPException(status_code=400, detail="messages 中没有文本消息")
raise HTTPException(status_code=400, detail="messages 中没有有效消息")
# 2. 提取 user_id:取最后一条消息的 sender_id # 2. 提取 user_id:取最后一条消息的 sender_id
user_id = request.messages[-1].sender_id user_id = request.messages[-1].sender_id
# 3. 提取 allowed_agent_codes / offline_agents_info / bot_id_mapping # 3. 提取 allowed_agent_codes 和 bot_id_mapping
allowed_agent_codes: Optional[list] = None allowed_agent_codes: Optional[list] = None
offline_agents_info: Optional[list] = None
bot_id_mapping: dict = {} bot_id_mapping: dict = {}
if request.agents: if request.agents:
# 构建 AgentConfig.code → dict key 映射 # 构建 agent.code → 内部名称(dict key)映射
code_to_key = { code_to_name = {
cfg.code: key for key, cfg in agent_hub.agents.items() cfg.code: name for name, cfg in agent_hub.agents.items()
} }
allowed_agent_codes = [] allowed_agent_codes = []
offline_agents_info = []
for agent_info in request.agents: for agent_info in request.agents:
agent_id_str = str(agent_info.agent_id) agent_code_str = str(agent_info.agent_id)
agent_key = code_to_key.get(agent_id_str) internal_name = code_to_name.get(agent_code_str)
if not agent_key: if internal_name and internal_name != "main":
continue allowed_agent_codes.append(internal_name)
# 提取 bot_id 映射:{internal_agent_name: bot_id}
# 过滤已下线/已删除的 agent,构建下线信息供主 Agent 知晓 if internal_name and agent_info.bot_id:
is_offline = agent_info.status != "enable" or agent_info.is_deleted bot_id_mapping[internal_name] = agent_info.bot_id
if is_offline and not agent_hub.agents[agent_key].is_steward:
agent_cfg = agent_hub.agents[agent_key]
offline_agents_info.append({
"name": agent_cfg.name,
"code": agent_key,
"description": agent_cfg.description or f"{agent_cfg.name}相关任务",
})
if agent_info.bot_id:
bot_id_mapping[agent_key] = agent_info.bot_id
continue
if 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: if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由 allowed_agent_codes = None # 无有效子 agent,走默认路由
if not offline_agents_info:
offline_agents_info = None
# 后端自动补全发言人口 agent code,确保主Agent 始终可调用发言人
MOUTH_AGENT_CODE = "-1"
if allowed_agent_codes is not None and MOUTH_AGENT_CODE not in allowed_agent_codes:
if MOUTH_AGENT_CODE in agent_hub.agents:
allowed_agent_codes.append(MOUTH_AGENT_CODE)
# 发言人使用主Agent的bot_id发送消息
if MOUTH_AGENT_CODE not in bot_id_mapping:
steward_key = agent_hub._find_steward_key()
steward_bot_id = bot_id_mapping.get(steward_key)
if steward_bot_id:
bot_id_mapping[MOUTH_AGENT_CODE] = steward_bot_id
# 4. 追加消息到 buffer(在 MessageGate per-session 锁内,确保并发安全)
await message_gate.append_messages(
session_id, [m.model_dump() for m in request.messages]
)
# 4.5 入口日志:记录本次请求的概要(不打印完整 payload,避免敏感信息泄露) # 4. 后台异步处理
text_preview = (query[:80] + "…") if len(query) > 80 else query
msg_types = [m.msg_type for m in request.messages]
logger.info(
"[ChatEndpoint] session=%s user=%s 收到消息,msg_count=%d types=%s,文本预览=%r,file_url=%s,agents=%d",
session_id, user_id, len(request.messages), msg_types, text_preview,
file_url or "无", len(request.agents),
)
# 5. 后台异步处理 via MessageGate
background_tasks.add_task( background_tasks.add_task(
_process_message_async_via_gate, _process_message_async,
agent_hub=agent_hub, agent_hub=agent_hub,
message_gate=message_gate,
session_id=session_id, session_id=session_id,
room_id=session_id, room_id=session_id,
user_id=user_id, user_id=user_id,
messages=request.messages, user_query=query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_id_mapping=bot_id_mapping, bot_id_mapping=bot_id_mapping,
offline_agents_info=offline_agents_info,
) )
return {"status": "ok", "session_id": session_id} return {"status": "ok", "session_id": session_id}
async def _process_message_async_via_gate( async def _process_message_async(
agent_hub: AgentHub, agent_hub: AgentHub,
message_gate: MessageGate,
session_id: str, session_id: str,
room_id: str, room_id: str,
user_id: str, user_id: str,
messages: list, user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
bot_id_mapping: Optional[dict] = None, bot_id_mapping: Optional[dict] = None,
offline_agents_info: Optional[list] = None,
): ):
"""通过 MessageGate 评估后再决定是否走 AgentHub。""" """后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try: try:
await message_gate.evaluate(
session_id=session_id,
room_id=room_id,
user_id=user_id,
bot_id_mapping=bot_id_mapping or {},
offline_agents_info=offline_agents_info,
)
except Exception:
logger.exception("MessageGate 评估失败,尝试兜底")
try:
# 兜底:走原有 AgentHub 流程
text_parts = []
file_url: Optional[str] = None
for msg in messages:
if msg.msg_type == "text":
if msg.msg_content:
text_parts.append(msg.msg_content)
else:
if msg.msg_content and file_url is None:
file_url = msg.msg_content
query = "\n".join(text_parts)
allowed_agent_codes = None # 兜底场景省略精细路由
await agent_hub.process_message( await agent_hub.process_message(
session_id=session_id, session_id=session_id,
room_id=room_id, room_id=room_id,
user_id=user_id, user_id=user_id,
user_query=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,
offline_agents_info=offline_agents_info, bot_id_mapping=bot_id_mapping,
bot_id_mapping=bot_id_mapping or {},
) )
except Exception: except Exception:
logger.exception("兜底逻辑也失败了: session=%s", session_id) logger.exception(
"Agent 后台处理失败: session=%s user=%s query=%s",
session_id, user_id, user_query[:50],
)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!