Commit 019d952d by sunqi02 Committed by 胡悦

feat(message-gate): 分类失败问题修正

1 parent dff977c5
...@@ -88,8 +88,13 @@ async def chat( ...@@ -88,8 +88,13 @@ async def chat(
file_url = msg.msg_content # 取第一张图片 URL file_url = msg.msg_content # 取第一张图片 URL
query = "\n".join(text_parts) query = "\n".join(text_parts)
if not query: # 检查是否有任何有效消息(text/other/file/image 均可)
raise HTTPException(status_code=400, detail="messages 中没有文本消息") has_any_content = bool(query) or file_url or any(
m.msg_type in ("file", "image", "other") and m.msg_content
for m in request.messages
)
if not has_any_content:
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
......
...@@ -60,6 +60,7 @@ class MessageGate: ...@@ -60,6 +60,7 @@ class MessageGate:
self.model = OpenAIChatModel( self.model = OpenAIChatModel(
model_name=gate_cfg.model_name, model_name=gate_cfg.model_name,
api_key=os.path.expandvars(gate_cfg.api_key), api_key=os.path.expandvars(gate_cfg.api_key),
stream=False,
client_kwargs={"base_url": gate_cfg.api_base}, client_kwargs={"base_url": gate_cfg.api_base},
) )
...@@ -144,7 +145,19 @@ class MessageGate: ...@@ -144,7 +145,19 @@ class MessageGate:
buffer.clear_pending() buffer.clear_pending()
return return
# actionable 或 incomplete(Phase 1 临时走 actionable 路径) if decision.intent == "incomplete":
await self._handle_incomplete(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
# 不清空 buffer:用户后续补充的消息需要合并
return
# actionable
await self._handle_actionable( await self._handle_actionable(
session_id=session_id, session_id=session_id,
room_id=room_id, room_id=room_id,
...@@ -162,12 +175,19 @@ class MessageGate: ...@@ -162,12 +175,19 @@ class MessageGate:
agent_codes: Optional[List[str]] = None, agent_codes: Optional[List[str]] = None,
) -> "GateDecision": ) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。""" """调 LLM 进行意图分类 + query 重写。"""
# 合并文本 # 合并文本,带类型标注让 LLM 更好理解
merged_text = "\n".join( parts = []
m.get("msg_content", "") for m in pending:
for m in pending mt = m.get("msg_type", "")
if m.get("msg_type") in ("text", "other", "file") mc = m.get("msg_content", "")
) if mt in ("text", "other", "file") and mc:
if mt == "file":
parts.append(f"[文件: {mc}]")
elif mt == "other":
parts.append(f"[其他: {mc}]")
else:
parts.append(mc)
merged_text = "\n".join(parts) if parts else "(空消息)"
# 加载最近 5 轮历史 # 加载最近 5 轮历史
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
...@@ -192,6 +212,7 @@ class MessageGate: ...@@ -192,6 +212,7 @@ class MessageGate:
# 解析 JSON # 解析 JSON
text = self._extract_text(response) text = self._extract_text(response)
logger.debug("[MessageGate] LLM raw response type=%s, extracted text=%s", type(response).__name__, text[:300])
return self._parse_decision_json(text) return self._parse_decision_json(text)
def _build_classify_prompt( def _build_classify_prompt(
...@@ -302,6 +323,36 @@ class MessageGate: ...@@ -302,6 +323,36 @@ class MessageGate:
"bot_id_mapping": bot_id_mapping, "bot_id_mapping": bot_id_mapping,
}) })
async def _handle_incomplete(
self,
session_id: str,
room_id: str,
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str],
) -> None:
"""incomplete 分支:追问用户意图,保留 pending_messages 等待补充。"""
if not decision.reply:
return
from app.service.memory import SessionMemory
from app.infrastructure.session_store import SessionStore
store = SessionStore()
merged_text = "\n".join(
m.get("msg_content", "") for m in pending
if m.get("msg_type") in ("text", "other", "file")
)
mem = SessionMemory(session_id, store)
mem.add("user", merged_text)
mem.add("assistant", decision.reply, agent_code=self.main_agent_key)
await self.post_reply_hook.execute({
"agent_name": self.main_agent_key,
"response_content": decision.reply,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping,
})
async def _handle_actionable( async def _handle_actionable(
self, self,
session_id: str, session_id: str,
......
...@@ -61,8 +61,8 @@ class SessionBuffer: ...@@ -61,8 +61,8 @@ class SessionBuffer:
self.store.set(self.session_id, data) self.store.set(self.session_id, data)
def has_text_message(self) -> bool: def has_text_message(self) -> bool:
"""检查 pending_messages 中是否有 text 类型消息。""" """检查 pending_messages 中是否有 text 或 other 类型消息。"""
for m in self.get_pending(): for m in self.get_pending():
if m.get("msg_type") == "text": if m.get("msg_type") in ("text", "other"):
return True return True
return False return False
\ No newline at end of file \ No newline at end of file
...@@ -4,19 +4,19 @@ ...@@ -4,19 +4,19 @@
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus", "model_name": "qwen3.6-plus",
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
}, },
"summary": { "summary": {
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus", "model_name": "qwen3.6-plus",
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
}, },
"message_gate": { "message_gate": {
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://api.deepseek.com/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "deepseek-v4-flash", "model_name": "deepseek-v4-flash",
"api_key": "${DEEPSEEK_API_KEY}" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
} }
}, },
"meeting_minutes": { "meeting_minutes": {
...@@ -24,13 +24,13 @@ ...@@ -24,13 +24,13 @@
"type": "dashscope_asr", "type": "dashscope_asr",
"api_base": "https://dashscope.aliyuncs.com/api/v1", "api_base": "https://dashscope.aliyuncs.com/api/v1",
"model_name": "fun-asr", "model_name": "fun-asr",
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
}, },
"qwen3.6-plus": { "qwen3.6-plus": {
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus", "model_name": "qwen3.6-plus",
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
}, },
"oss": { "oss": {
"access_key_id": "LTAI5tB2Q3EJFmaosMYN3uPc", "access_key_id": "LTAI5tB2Q3EJFmaosMYN3uPc",
......
...@@ -301,8 +301,8 @@ class TestChatCompletionsAPI: ...@@ -301,8 +301,8 @@ class TestChatCompletionsAPI:
) )
assert resp.status_code == 400 assert resp.status_code == 400
def test_text_only_messages_returns_400(self): def test_image_only_messages_returns_200(self):
"""只有 image 消息没有 text → 400""" """只有 image 消息没有 text → 200(MessageGate 会等待文本或追问)"""
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
...@@ -319,7 +319,7 @@ class TestChatCompletionsAPI: ...@@ -319,7 +319,7 @@ class TestChatCompletionsAPI:
], ],
}, },
) )
assert resp.status_code == 400 assert resp.status_code == 200
def test_missing_group_contact_id_returns_400(self): def test_missing_group_contact_id_returns_400(self):
"""不传 group.group_contact_id → 400""" """不传 group.group_contact_id → 400"""
......
...@@ -179,4 +179,66 @@ async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps): ...@@ -179,4 +179,66 @@ async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
# 等 task 完成 # 等 task 完成
task = gate._running_tasks["sess_001"] task = gate._running_tasks["sess_001"]
await task await task
gate.agent_hub.process_message.assert_awaited_once()
\ No newline at end of file \ No newline at end of file
gate.agent_hub.process_message.assert_awaited_once()
@pytest.mark.asyncio
async def test_incomplete_sends_reply_and_preserves_buffer(message_gate_with_deps):
"""incomplete 分支应发 IM 追问,且不清空 buffer。"""
gate = message_gate_with_deps
from app.infrastructure.session_store import SessionStore
from app.infrastructure.session_store import clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
buffer = SessionBuffer(store, "sess_inc")
buffer.append({
"msg_id": "m1", "msg_type": "file",
"msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t",
})
await gate._handle_incomplete(
session_id="sess_inc",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="incomplete", reply="这文件是用来做什么的?"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
# IM 追问被发送
gate.post_reply_hook.execute.assert_awaited_once()
call_args = gate.post_reply_hook.execute.call_args[0][0]
assert call_args["response_content"] == "这文件是用来做什么的?"
# buffer 未被清空(evaluate 里 incomplete 分支不清空)
remaining = buffer.get_pending()
assert len(remaining) == 1
@pytest.mark.asyncio
async def test_classify_file_only_as_incomplete(message_gate_with_deps):
"""file-only 消息应被 LLM 分类为 incomplete。"""
gate = message_gate_with_deps
fake_response_text = '{"intent": "incomplete", "reply": "这段录音需要转文字,还是做摘要?"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_file_only",
pending=pending,
agent_codes=["main"],
)
assert decision.intent == "incomplete"
assert decision.reply == "这段录音需要转文字,还是做摘要?"
# 验证发给 LLM 的 merged_text 带了类型标注
call_args = gate.model.call_args
messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
user_content = messages[1]["content"]
assert "[文件:" in user_content
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!