Commit 0858f030 by sunqi02

feat(message-gate): implement evaluate() main flow and wire into endpoint

1 parent 876b710f
...@@ -3,6 +3,7 @@ from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException ...@@ -3,6 +3,7 @@ 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.service.agent_hub import AgentHub from app.service.agent_hub import AgentHub
from app.service.message_gate import MessageGate
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -52,11 +53,17 @@ def get_agent_hub(): ...@@ -52,11 +53,17 @@ 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 在后台异步处理。
...@@ -107,16 +114,23 @@ async def chat( ...@@ -107,16 +114,23 @@ async def chat(
if not allowed_agent_codes: if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由 allowed_agent_codes = None # 无有效子 agent,走默认路由
# 4. 后台异步处理 # 4. 追加消息到 buffer(在 BackgroundTask 之外,确保锁外追加)
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
store = SessionStore()
buffer = SessionBuffer(store, session_id)
for msg in request.messages:
buffer.append(msg.model_dump())
# 5. 后台异步处理 via MessageGate
background_tasks.add_task( background_tasks.add_task(
_process_message_async, _process_message_async_via_gate,
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,
user_query=query, messages=request.messages,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_id_mapping=bot_id_mapping, bot_id_mapping=bot_id_mapping,
) )
...@@ -149,3 +163,49 @@ async def _process_message_async( ...@@ -149,3 +163,49 @@ async def _process_message_async(
"Agent 后台处理失败: session=%s user=%s query=%s", "Agent 后台处理失败: session=%s user=%s query=%s",
session_id, user_id, user_query[:50], session_id, user_id, user_query[:50],
) )
async def _process_message_async_via_gate(
agent_hub: AgentHub,
message_gate: MessageGate,
session_id: str,
room_id: str,
user_id: str,
messages: list,
bot_id_mapping: Optional[dict] = None,
):
"""通过 MessageGate 评估后再决定是否走 AgentHub。"""
try:
await message_gate.evaluate(
session_id=session_id,
room_id=room_id,
user_id=user_id,
bot_id_mapping=bot_id_mapping or {},
messages=messages,
)
except Exception:
logger.exception("MessageGate 评估失败,尝试兜底")
try:
# 兜底:走原有 AgentHub 流程
text_parts = []
file_url: Optional[str] = None
for msg in messages:
if msg.msg_type in ("text", "other", "file"):
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
query = "\n".join(text_parts)
allowed_agent_codes = None # 兜底场景省略精细路由
await agent_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
bot_id_mapping=bot_id_mapping or {},
)
except Exception:
logger.exception("兜底逻辑也失败了: session=%s", session_id)
...@@ -46,6 +46,7 @@ from app.service.console_im_service import ConsoleIMService ...@@ -46,6 +46,7 @@ from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService from app.service.im_service import IMService
agent_hub_instance = None agent_hub_instance = None
message_gate_instance = None
configure_logging("backend", logging.INFO) configure_logging("backend", logging.INFO)
runtime_settings = ConfigLoader().load_settings() runtime_settings = ConfigLoader().load_settings()
base_path = (runtime_settings.server.base_path or "").rstrip("/") base_path = (runtime_settings.server.base_path or "").rstrip("/")
...@@ -57,7 +58,7 @@ oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/do ...@@ -57,7 +58,7 @@ oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/do
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
global agent_hub_instance global agent_hub_instance, message_gate_instance
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine) ensure_runtime_schema(engine)
...@@ -97,10 +98,26 @@ async def lifespan(app: FastAPI): ...@@ -97,10 +98,26 @@ async def lifespan(app: FastAPI):
preloaded_agents=agents, preloaded_agents=agents,
) )
# ── MessageGate 实例化 ──
from app.service.message_gate import MessageGate
from app.hooks.post_reply import PostReplyHook
main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main")
post_reply_hook = PostReplyHook(im_service=im_service)
message_gate_instance = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub_instance,
main_agent_key=main_agent_key,
)
yield yield
if agent_hub_instance: if agent_hub_instance:
await agent_hub_instance.close() await agent_hub_instance.close()
if message_gate_instance:
await message_gate_instance.close()
db.close() db.close()
......
...@@ -62,5 +62,144 @@ class MessageGate: ...@@ -62,5 +62,144 @@ class MessageGate:
messages: List[Dict[str, Any]] = None, messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0, wait_seconds: float = 6.0,
) -> None: ) -> None:
"""评估入口:等待、分类、重写、分发。"""
raise NotImplementedError
\ No newline at end of file \ No newline at end of file
"""评估入口:等待、分类、重写、分发。
Args:
session_id: 会话 ID
room_id: 房间 ID
user_id: 用户 ID
bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射
messages: 原始消息列表(已由 endpoint 追加到 buffer,留空)
wait_seconds: 等待窗口(默认 6 秒,测试时可缩短)
"""
# 注入当前调用上下文
self._current_bot_id_mapping = bot_id_mapping
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore
store = SessionStore()
buffer = SessionBuffer(store, session_id)
lock = self._get_lock(session_id)
async with lock:
# 步骤 4:检查 buffer 是否全是 file/image/other 无 text
if not buffer.has_text_message() and buffer.get_pending():
logger.info(
"[MessageGate] session=%s 无 text 消息,等待 %.1fs",
session_id, wait_seconds,
)
await asyncio.sleep(wait_seconds)
# 等待后重新读取 buffer
buffer = SessionBuffer(store, session_id)
# 步骤 6:检查 running task(Phase 1 简化版:发现 running 直接跳过)
running_task = self._running_tasks.get(session_id)
if running_task and not running_task.done():
logger.info(
"[MessageGate] session=%s 已有 running task,跳过",
session_id,
)
buffer.clear_pending()
return
# 步骤 7:调 LLM 分类 + 重写
pending = buffer.get_pending()
if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return
decision = await self._classify_and_rewrite(
session_id=session_id,
pending=pending,
agent_codes=list(self._current_bot_id_mapping.keys()),
)
# 步骤 8:根据 intent 分支
if decision.intent == "ignore":
# 按 msg_id 移除本批次
ids = [m["msg_id"] for m in pending if "msg_id" in m]
buffer.remove_by_msg_ids(ids)
return
if decision.intent == "casual":
await self._handle_casual(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
)
buffer.clear_pending()
return
# actionable 或 incomplete(Phase 1 临时走 actionable 路径)
await self._handle_actionable(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=self._current_bot_id_mapping,
)
buffer.clear_pending()
async def _classify_and_rewrite(
self,
session_id: str,
pending: List[Dict[str, Any]],
agent_codes: Optional[List[str]] = None,
) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。Phase 1 临时返回 actionable。"""
merged_text = "\n".join(
m.get("msg_content", "")
for m in pending
if m.get("msg_type") in ("text", "other", "file")
)
return GateDecision(intent="actionable", rewritten_query=merged_text)
async def _handle_casual(
self,
session_id: str,
room_id: str,
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
) -> None:
"""casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。"""
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": self._current_bot_id_mapping,
})
async def _handle_actionable(
self,
session_id: str,
room_id: str,
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str],
) -> None:
"""actionable 分支:分发到 AgentHub。"""
pass
async def close(self) -> None:
"""清理资源(Phase 1 简化版)。"""
self._running_tasks.clear()
self._session_locks.clear()
\ No newline at end of file \ No newline at end of file
...@@ -85,9 +85,40 @@ def _override_get_agent_hub(): ...@@ -85,9 +85,40 @@ def _override_get_agent_hub():
return test_hub return test_hub
from app.api.v1.endpoints.agent_hub import get_agent_hub def _override_get_message_gate():
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision
mock_gate = MagicMock(spec=MessageGate)
mock_gate.evaluate = AsyncMock(return_value=None)
# 让 evaluate 同步调用 agent_hub.process_message(模拟 actionable 分支)
async def fake_evaluate(session_id, room_id, user_id, bot_id_mapping, messages=None, wait_seconds=6.0, **kwargs):
text_parts = []
file_url = None
for msg in (messages or []):
if msg.msg_type in ("text", "other", "file"):
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
query = "\n".join(text_parts)
await test_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=query,
file_url=file_url,
allowed_agent_codes=None,
bot_id_mapping=bot_id_mapping,
)
mock_gate.evaluate = AsyncMock(side_effect=fake_evaluate)
return mock_gate
from app.api.v1.endpoints.agent_hub import get_agent_hub, get_message_gate
fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub
fastapi_app.dependency_overrides[get_message_gate] = _override_get_message_gate
client = TestClient(fastapi_app) client = TestClient(fastapi_app)
......
...@@ -31,4 +31,74 @@ def test_gate_decision_dataclass_defaults(): ...@@ -31,4 +31,74 @@ def test_gate_decision_dataclass_defaults():
d = GateDecision(intent="ignore") d = GateDecision(intent="ignore")
assert d.intent == "ignore" assert d.intent == "ignore"
assert d.rewritten_query is None assert d.rewritten_query is None
assert d.reply is None
\ No newline at end of file \ No newline at end of file
assert d.reply is None
import asyncio
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import clear_default_store_for_tests
@pytest.fixture
def message_gate_with_deps():
"""构造一个带假依赖的 MessageGate。"""
config_loader = MagicMock()
session_service = MagicMock()
post_reply_hook = MagicMock()
post_reply_hook.execute = AsyncMock()
agent_hub = MagicMock()
agent_hub.process_message = AsyncMock()
gate = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub,
main_agent_key="main",
)
gate._current_bot_id_mapping = {"main": "bot-001"}
return gate
@pytest.mark.asyncio
async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
"""纯 file 消息应等待(用 monkey-patched 短等待避免测试慢)。"""
gate = message_gate_with_deps
# 用 0.1 秒等待代替 6 秒
from app.service import message_gate as mg_module
original_sleep = mg_module.asyncio.sleep
async def fast_sleep(_):
await original_sleep(0.01)
mg_module.asyncio.sleep = fast_sleep
try:
# 模拟 LLM 返回 actionable(patch 内部方法)
gate._classify_and_rewrite = AsyncMock(return_value=GateDecision(
intent="actionable",
rewritten_query="请分析文件 [url]",
))
gate._dispatch_to_agent_hub = AsyncMock()
# 追加 file 消息到 buffer
from app.infrastructure.session_store import SessionStore
clear_default_store_for_tests()
store = SessionStore()
buffer = SessionBuffer(store, "sess_001")
buffer.append({
"msg_id": "m1", "msg_type": "file",
"msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t",
})
await gate.evaluate(
session_id="sess_001",
room_id="r1",
user_id="u1",
bot_id_mapping={"main": "bot-001"},
messages=[],
)
# 等待 0.01s 后分类被调用
assert gate._classify_and_rewrite.await_count == 1
finally:
mg_module.asyncio.sleep = original_sleep
\ 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!