Commit 2d5caff0 by sunqi02 Committed by 胡悦

fix: 修复并发会话串群 Bug — 用 ContextVar 替换 _current_route_ctx

AgentHub._current_route_ctx 是单例上的共享实例属性,并发请求在
agent.reply() yield 点后相互覆盖,导致子Agent 回复发到错误房间。

用 contextvars.ContextVar 替换,每个 asyncio Task 持有独立上下文。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 66604370
import logging
import time
from contextvars import ContextVar
from datetime import datetime, timezone
from functools import partial
from pathlib import Path
......@@ -46,6 +47,11 @@ from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__)
# Per-request routing context, isolated per asyncio Task.
# Used by process_message, _call_sub_agent, and call_sub_agent tool closure
# to safely pass room_id/user_id/bot_id_mapping/call_count across async boundaries.
_route_context_var: ContextVar[dict] = ContextVar('route_context')
# sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出
SUB_AGENT_TEMPERATURE = 0.2
......@@ -472,11 +478,12 @@ class AgentHub:
session_id, user_query[:100], file_url,
)
# 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
self._current_route_ctx = dict(
# 暂存路由上下文(per-asyncio-Task,并发安全),
# 供 _call_sub_agent 创建子 Agent 时注册 hook 和发 IM
_route_context_var.set(dict(
room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
call_count=0,
)
))
session = self.session_service.get_or_create_session(
session_id=session_id,
......@@ -489,8 +496,6 @@ class AgentHub:
store=self.session_service.store,
max_rounds=20,
)
self._current_route_ctx["session_memory"] = memory
messages = memory.get_messages(max_rounds=10)
# 始终路由到 steward agent
......@@ -569,7 +574,7 @@ class AgentHub:
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory.add("assistant", response_raw, name=target_agent_name)
call_count = self._current_route_ctx.get("call_count", 0)
call_count = _route_context_var.get().get("call_count", 0)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
if call_count >= 1:
......@@ -688,7 +693,7 @@ class AgentHub:
)
# 为子 Agent 注册 IM hook(post_reasoning → thinking 摘要)
ctx = self._current_route_ctx
ctx = _route_context_var.get()
self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])
response = await sub_agent.reply(Msg("user", instruction, "user"))
......@@ -808,7 +813,7 @@ class AgentHub:
))]
)
# 新增:递增调用计数
ctx = getattr(self, "_current_route_ctx", None)
ctx = _route_context_var.get(None)
if ctx:
ctx["call_count"] = ctx.get("call_count", 0) + 1
call_no = ctx["call_count"]
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!