Commit 7ac6702a by sunqi02 Committed by 胡悦

feat(agent_hub): 更新 SessionBuffer 和 ActiveSessionService,增强会话管理和日志记录功能

1 parent cccc6382
...@@ -123,7 +123,7 @@ async def chat( ...@@ -123,7 +123,7 @@ async def chat(
from app.service.session_buffer import SessionBuffer from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
store = SessionStore() store = SessionStore()
buffer = SessionBuffer(store, session_id) buffer = SessionBuffer(store, session_id, session_service=agent_hub.session_service)
for msg in request.messages: for msg in request.messages:
buffer.append(msg.model_dump()) buffer.append(msg.model_dump())
......
...@@ -100,12 +100,20 @@ class ActiveSessionService: ...@@ -100,12 +100,20 @@ class ActiveSessionService:
def save_to_db(self, session_id: str) -> None: def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。""" """将内存中的 session 持久化到 DB。"""
if not self._db: if not self._db:
logger.warning("[save_to_db] session=%s _db 为 None,跳过持久化", session_id)
return return
data = self.store.get(session_id) data = self.store.get(session_id)
if not data: if not data:
logger.warning("[save_to_db] session=%s KV 中无数据,跳过持久化", session_id)
return return
history = data.get("conversation_history") or []
logger.info(
"[save_to_db] session=%s 即将写入 DB,conversation_history 长度=%d",
session_id, len(history),
)
try: try:
existing = self._db.query(Session).filter( existing = self._db.query(Session).filter(
Session.session_id == session_id Session.session_id == session_id
......
...@@ -45,6 +45,27 @@ async def _im_post_reasoning_hook( ...@@ -45,6 +45,27 @@ async def _im_post_reasoning_hook(
): ):
"""AgentScope native hook: 推理完成后摘要化 thinking 并通过 IM 发送。""" """AgentScope native hook: 推理完成后摘要化 thinking 并通过 IM 发送。"""
logger.info(f"[Hook 触发] agent={self.name} 时机=post_reasoning") logger.info(f"[Hook 触发] agent={self.name} 时机=post_reasoning")
# 若刚收到 call_sub_agent 结果,跳过 thinking 摘要
# 下一轮就是最终回复,由 PostReplyHook 发出,避免重复消息
memory_msgs = await self.memory.get_memory()
# 检查倒数第2条:post_reasoning 触发时 memory[-1] 已是本轮 reasoning 输出,
# call_sub_agent 的 tool_result 在上轮 _acting() 写入,位于 memory[-2]
if len(memory_msgs) >= 2:
prev = memory_msgs[-2]
if hasattr(prev, "content"):
for block in prev.content or []:
if (
isinstance(block, dict)
and block.get("type") == "tool_result"
and block.get("name") == "call_sub_agent"
):
logger.info(
"[Hook 跳过] agent=%s call_sub_agent 获得sub Agent结果,跳过本次 thinking 摘要和 IM 发送",
self.name,
)
return None
bot_id = bot_id_mapping.get(self.name) bot_id = bot_id_mapping.get(self.name)
if not bot_id: if not bot_id:
return None return None
......
"""Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。""" """Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。"""
from __future__ import annotations from __future__ import annotations
import logging
from typing import Any, List, Optional from typing import Any, List, Optional
logger = logging.getLogger(__name__)
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
...@@ -41,6 +44,10 @@ class SessionMemory: ...@@ -41,6 +44,10 @@ class SessionMemory:
}) })
existing["conversation_history"] = history existing["conversation_history"] = history
self._store.set(self.session_id, existing) self._store.set(self.session_id, existing)
logger.info(
"[SessionMemory] session=%s add role=%s → conversation_history 长度=%d",
self.session_id, role, len(history),
)
def get_messages( def get_messages(
self, self,
......
...@@ -90,10 +90,19 @@ class MessageGate: ...@@ -90,10 +90,19 @@ class MessageGate:
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
store = SessionStore() store = SessionStore()
buffer = SessionBuffer(store, session_id) buffer = SessionBuffer(store, session_id, session_service=self.session_service)
lock = self._get_lock(session_id) lock = self._get_lock(session_id)
async with lock: async with lock:
# 调试:记录锁获取时的 KV 状态
_kv_data = store.get(session_id) or {}
_kv_history = _kv_data.get("conversation_history") or []
_kv_pending = _kv_data.get("pending_messages") or []
logger.info(
"[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
session_id, len(_kv_history), len(_kv_pending),
)
# 步骤 4:检查 buffer 是否全是 file/image/other 无 text # 步骤 4:检查 buffer 是否全是 file/image/other 无 text
if not buffer.has_text_message() and buffer.get_pending(): if not buffer.has_text_message() and buffer.get_pending():
logger.info( logger.info(
...@@ -102,7 +111,7 @@ class MessageGate: ...@@ -102,7 +111,7 @@ class MessageGate:
) )
await asyncio.sleep(wait_seconds) await asyncio.sleep(wait_seconds)
# 等待后重新读取 buffer # 等待后重新读取 buffer
buffer = SessionBuffer(store, session_id) buffer = SessionBuffer(store, session_id, session_service=self.session_service)
# 步骤 6:检查 running task(Phase 1 简化版:发现 running 直接跳过) # 步骤 6:检查 running task(Phase 1 简化版:发现 running 直接跳过)
running_task = self._running_tasks.get(session_id) running_task = self._running_tasks.get(session_id)
...@@ -315,6 +324,7 @@ class MessageGate: ...@@ -315,6 +324,7 @@ class MessageGate:
mem = SessionMemory(session_id, store) mem = SessionMemory(session_id, store)
mem.add("user", merged_text) mem.add("user", merged_text)
mem.add("assistant", decision.reply, agent_code=self.main_agent_key) mem.add("assistant", decision.reply, agent_code=self.main_agent_key)
self.session_service.save_to_db(session_id)
await self.post_reply_hook.execute({ await self.post_reply_hook.execute({
"agent_name": self.main_agent_key, "agent_name": self.main_agent_key,
"response_content": decision.reply, "response_content": decision.reply,
...@@ -345,6 +355,7 @@ class MessageGate: ...@@ -345,6 +355,7 @@ class MessageGate:
mem = SessionMemory(session_id, store) mem = SessionMemory(session_id, store)
mem.add("user", merged_text) mem.add("user", merged_text)
mem.add("assistant", decision.reply, agent_code=self.main_agent_key) mem.add("assistant", decision.reply, agent_code=self.main_agent_key)
self.session_service.save_to_db(session_id)
await self.post_reply_hook.execute({ await self.post_reply_hook.execute({
"agent_name": self.main_agent_key, "agent_name": self.main_agent_key,
"response_content": decision.reply, "response_content": decision.reply,
...@@ -375,32 +386,27 @@ class MessageGate: ...@@ -375,32 +386,27 @@ class MessageGate:
file_url = m["msg_content"] file_url = m["msg_content"]
break break
async def _run(): try:
try: await self.agent_hub.process_message(
await self.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=query, file_url=file_url,
file_url=file_url, allowed_agent_codes=None, # Phase 1 简化:不传
allowed_agent_codes=None, # Phase 1 简化:不传 bot_id_mapping=bot_id_mapping,
bot_id_mapping=bot_id_mapping, )
) except asyncio.CancelledError:
except asyncio.CancelledError: logger.info(
logger.info( "[MessageGate] session=%s 任务被取消",
"[MessageGate] session=%s 任务被取消", session_id,
session_id, )
) raise
raise except Exception:
except Exception: logger.exception(
logger.exception( "[MessageGate] session=%s AgentHub.process_message 失败",
"[MessageGate] session=%s AgentHub.process_message 失败", session_id,
session_id, )
)
task = asyncio.create_task(_run())
self._running_tasks[session_id] = task
task.add_done_callback(lambda t: self._running_tasks.pop(session_id, None))
async def close(self) -> None: async def close(self) -> None:
"""清理资源:取消运行中的任务并清空状态。""" """清理资源:取消运行中的任务并清空状态。"""
......
"""SessionBuffer - 封装 pending_messages 的存取操作。""" """SessionBuffer - 封装 pending_messages 的存取操作。"""
from __future__ import annotations from __future__ import annotations
from typing import Any, Dict, List, Optional import logging
from typing import Any, Dict, List, Optional, TYPE_CHECKING
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
if TYPE_CHECKING:
from app.service.active_session_service import ActiveSessionService
def _ensure_session_exists(store: SessionStore, session_id: str) -> Dict[str, Any]: logger = logging.getLogger(__name__)
"""确保 session payload 存在,否则创建空 payload。"""
def _ensure_session_exists(
store: SessionStore,
session_id: str,
session_service: Optional["ActiveSessionService"] = None,
) -> Dict[str, Any]:
"""确保 session payload 存在于 KV。KV miss 时先尝试 DB 冷恢复。"""
existing = store.get(session_id) existing = store.get(session_id)
if existing is None: if existing is None:
existing = { # KV miss → 尝试 DB 冷恢复
"session_id": session_id, if session_service is not None:
"conversation_history": [], session_service.get_or_create_session(session_id=session_id)
"pending_messages": [], existing = store.get(session_id)
} if existing is None:
store.set(session_id, existing) logger.warning(
return existing "[SessionBuffer] session=%s KV+DB 均不存在,新建 session",
session_id,
)
existing = {
"session_id": session_id,
"conversation_history": [],
"pending_messages": [],
}
store.set(session_id, existing)
return existing
else:
logger.info(
"[SessionBuffer] session=%s 从 DB 冷恢复成功",
session_id,
)
if "pending_messages" not in existing: if "pending_messages" not in existing:
existing["pending_messages"] = [] existing["pending_messages"] = []
store.set(session_id, existing) store.set(session_id, existing)
history_len = len(existing.get("conversation_history") or [])
logger.info(
"[SessionBuffer] session=%s 已存在,conversation_history 长度=%d",
session_id, history_len,
)
return existing return existing
class SessionBuffer: class SessionBuffer:
"""操作指定 session 的 pending_messages 缓冲区。""" """操作指定 session 的 pending_messages 缓冲区。"""
def __init__(self, store: SessionStore, session_id: str) -> None: def __init__(
self,
store: SessionStore,
session_id: str,
session_service: Optional["ActiveSessionService"] = None,
) -> None:
self.store = store self.store = store
self.session_id = session_id self.session_id = session_id
_ensure_session_exists(store, session_id) _ensure_session_exists(store, session_id, session_service=session_service)
def get_pending(self) -> List[Dict[str, Any]]: def get_pending(self) -> List[Dict[str, Any]]:
"""返回当前 pending_messages 列表的副本。""" """返回当前 pending_messages 列表的副本。"""
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
}, },
"agents": [ "agents": [
{"agent_id": 11, "bot_id": "ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82", "is_steward": true}, {"agent_id": 11, "bot_id": "ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82", "is_steward": true},
{"agent_id": 17, "bot_id": "d53d00b08f8b4e22844ecfd0bb12e343", "is_steward": false} {"agent_id": 17, "bot_id": "ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82", "is_steward": false}
], ],
"messages": [ "messages": [
{ {
......
...@@ -890,6 +890,8 @@ async def test_hook_summarizes_thinking_before_send(): ...@@ -890,6 +890,8 @@ async def test_hook_summarizes_thinking_before_send():
mock_agent = MagicMock() mock_agent = MagicMock()
mock_agent.name = MEETING_KEY mock_agent.name = MEETING_KEY
mock_agent.memory = MagicMock()
mock_agent.memory.get_memory = AsyncMock(return_value=[])
mock_output = MagicMock() mock_output = MagicMock()
mock_output.content = [{"type": "thinking", "thinking": "这条思考过程非常长," * 10}] mock_output.content = [{"type": "thinking", "thinking": "这条思考过程非常长," * 10}]
...@@ -919,6 +921,8 @@ async def test_hook_summarizes_even_short_thinking(): ...@@ -919,6 +921,8 @@ async def test_hook_summarizes_even_short_thinking():
mock_agent = MagicMock() mock_agent = MagicMock()
mock_agent.name = MEETING_KEY mock_agent.name = MEETING_KEY
mock_agent.memory = MagicMock()
mock_agent.memory.get_memory = AsyncMock(return_value=[])
mock_output = MagicMock() mock_output = MagicMock()
mock_output.content = [{"type": "thinking", "thinking": "正在处理"}] mock_output.content = [{"type": "thinking", "thinking": "正在处理"}]
...@@ -934,3 +938,44 @@ async def test_hook_summarizes_even_short_thinking(): ...@@ -934,3 +938,44 @@ async def test_hook_summarizes_even_short_thinking():
# 不论长短都应调用摘要化 # 不论长短都应调用摘要化
mock_summarize.assert_called_once() mock_summarize.assert_called_once()
@pytest.mark.asyncio
async def test_hook_skips_after_call_sub_agent_result():
"""call_sub_agent 工具结果后的 post_reasoning 应跳过 IM 发送。"""
from app.service.agent_hub import _im_post_reasoning_hook
mock_im = AsyncMock()
mock_summarize = AsyncMock()
mock_agent = MagicMock()
mock_agent.name = MEETING_KEY
# post_reasoning 触发时 memory[-1] 已是本轮 reasoning 输出,
# call_sub_agent 的 tool_result 在上轮 _acting() 写入,位于 memory[-2]
mock_tool_result = MagicMock()
mock_tool_result.content = [
{"type": "tool_result", "id": "call_123", "name": "call_sub_agent", "output": "会议纪要已生成"}
]
mock_current_reasoning = MagicMock()
mock_current_reasoning.content = []
mock_agent.memory = MagicMock()
mock_agent.memory.get_memory = AsyncMock(
return_value=[mock_tool_result, mock_current_reasoning]
)
mock_output = MagicMock()
mock_output.content = [{"type": "thinking", "thinking": "收到结果,整合回复用户"}]
result = await _im_post_reasoning_hook(
mock_agent, {}, mock_output,
im_service=mock_im,
room_id="room_001",
user_id="user_001",
bot_id_mapping={MEETING_KEY: "bot_001"},
summarize_thinking=mock_summarize,
)
# 应直接返回 None,不发送 IM
assert result is None
mock_im.send_message.assert_not_called()
mock_summarize.assert_not_called()
...@@ -149,18 +149,9 @@ async def test_classify_actionable_with_rewrite(message_gate_with_deps): ...@@ -149,18 +149,9 @@ async def test_classify_actionable_with_rewrite(message_gate_with_deps):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps): async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
"""actionable 分支应创建 asyncio.Task 调 AgentHub。""" """actionable 分支应直接 await AgentHub.process_message。"""
gate = message_gate_with_deps gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
# 让 process_message 慢一点,避免 task 在 sleep(0.1) 内完成被 done_callback 清理
async def _slow_process(*args, **kwargs):
await asyncio.sleep(0.5)
gate.agent_hub.process_message = AsyncMock(side_effect=_slow_process)
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()
await gate._handle_actionable( await gate._handle_actionable(
session_id="sess_001", session_id="sess_001",
...@@ -172,13 +163,6 @@ async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps): ...@@ -172,13 +163,6 @@ async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
bot_id_mapping={"main": "bot-001"}, bot_id_mapping={"main": "bot-001"},
) )
# 等待 task 启动
await asyncio.sleep(0.1)
assert "sess_001" in gate._running_tasks
# 等 task 完成
task = gate._running_tasks["sess_001"]
await task
gate.agent_hub.process_message.assert_awaited_once() gate.agent_hub.process_message.assert_awaited_once()
...@@ -198,11 +182,6 @@ async def test_actionable_extracts_file_url_from_file_type(message_gate_with_dep ...@@ -198,11 +182,6 @@ async def test_actionable_extracts_file_url_from_file_type(message_gate_with_dep
bot_id_mapping={"main": "bot-001"}, bot_id_mapping={"main": "bot-001"},
) )
# 等 task 完成
await asyncio.sleep(0.1)
if "sess_002" in gate._running_tasks:
await gate._running_tasks["sess_002"]
gate.agent_hub.process_message.assert_awaited_once() gate.agent_hub.process_message.assert_awaited_once()
# 验证 file_url 参数正确传递 # 验证 file_url 参数正确传递
call_kwargs = gate.agent_hub.process_message.call_args.kwargs call_kwargs = gate.agent_hub.process_message.call_args.kwargs
...@@ -225,10 +204,6 @@ async def test_actionable_still_extracts_image_url(message_gate_with_deps): ...@@ -225,10 +204,6 @@ async def test_actionable_still_extracts_image_url(message_gate_with_deps):
bot_id_mapping={"main": "bot-001"}, bot_id_mapping={"main": "bot-001"},
) )
await asyncio.sleep(0.1)
if "sess_003" in gate._running_tasks:
await gate._running_tasks["sess_003"]
call_kwargs = gate.agent_hub.process_message.call_args.kwargs call_kwargs = gate.agent_hub.process_message.call_args.kwargs
assert call_kwargs.get("file_url") == "https://oss.example.com/img.jpg" assert call_kwargs.get("file_url") == "https://oss.example.com/img.jpg"
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!