Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ai
/
ai-workflow
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 8ea607b3
authored
Jun 29, 2026
by
sunqi02
Committed by
胡悦
Jul 06, 2026
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat: 增加 fire-and-forget 机制以优化后台任务处理,异步化子Agent消息持久化和回复发送
1 parent
f54f1f43
Show whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
155 additions
and
53 deletions
workspace/agent-admin/backend/app/service/agent_hub.py
workspace/agent-admin/backend/test_request.json
workspace/agent-admin/backend/tests/test_agent_hub.py
workspace/agent-admin/backend/app/service/agent_hub.py
View file @
8ea607b
import
asyncio
import
logging
import
logging
import
time
import
time
from
contextvars
import
ContextVar
from
contextvars
import
ContextVar
...
@@ -47,6 +48,28 @@ class OpenAIChatFormatter(_OpenAIChatFormatter):
...
@@ -47,6 +48,28 @@ class OpenAIChatFormatter(_OpenAIChatFormatter):
logger
=
logging
.
getLogger
(
__name__
)
logger
=
logging
.
getLogger
(
__name__
)
# 跟踪所有 fire-and-forget 后台任务,防止 GC 回收
_background_tasks
:
set
[
asyncio
.
Task
]
=
set
()
def
_fire_and_forget
(
coro
,
task_name
:
str
=
"bg_task"
)
->
asyncio
.
Task
:
"""调度协程为 fire-and-forget 后台任务,异常被集中吞掉。"""
async
def
_wrapped
():
try
:
await
coro
except
asyncio
.
CancelledError
:
raise
except
Exception
:
logger
.
warning
(
"[bg_task]
%
s 异常(fire-and-forget,不影响主流程)"
,
task_name
,
exc_info
=
True
,
)
task
=
asyncio
.
create_task
(
_wrapped
())
_background_tasks
.
add
(
task
)
task
.
add_done_callback
(
_background_tasks
.
discard
)
return
task
# Per-request routing context, isolated per asyncio Task.
# Per-request routing context, isolated per asyncio Task.
# Used by process_message, _call_sub_agent, and call_sub_agent tool closure
# 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.
# to safely pass room_id/user_id/bot_id_mapping/call_count across async boundaries.
...
@@ -99,10 +122,37 @@ async def _im_post_reasoning_hook(
...
@@ -99,10 +122,37 @@ async def _im_post_reasoning_hook(
return
None
return
None
# 删除"下载"这个词
# 删除"下载"这个词
content
=
content
.
replace
(
"下载"
,
"点击"
)
content
=
content
.
replace
(
"下载"
,
"点击"
)
# 摘要化 thinking:调用模型总结为状态更新,不暴露内部推理
# 异步化:摘要 LLM + IM 发送不阻塞 ReAct 循环
bot_id_val
=
bot_id
agent_name
=
self
.
name
_fire_and_forget
(
_bg_summarize_thinking_and_send
(
content
=
content
,
summarize_thinking
=
summarize_thinking
,
im_service
=
im_service
,
bot_id
=
bot_id_val
,
room_id
=
room_id
,
agent_name
=
agent_name
,
),
task_name
=
f
"thinking_summary_{agent_name}"
,
)
async
def
_bg_summarize_thinking_and_send
(
content
:
str
,
summarize_thinking
,
im_service
,
bot_id
:
str
,
room_id
:
str
,
agent_name
:
str
,
):
"""Fire-and-forget: 摘要化 thinking 并通过 IM 发送。"""
if
summarize_thinking
:
if
summarize_thinking
:
content
=
await
summarize_thinking
(
content
)
content
=
await
summarize_thinking
(
content
)
logger
.
info
(
f
"[Hook 发送 IM] agent={self.name} bot_id={bot_id} content={content[:50]}..."
)
logger
.
info
(
"[Hook 发送 IM] agent=
%
s bot_id=
%
s content=
%
s..."
,
agent_name
,
bot_id
,
content
[:
50
],
)
try
:
try
:
await
im_service
.
send_message
(
await
im_service
.
send_message
(
bot_id
=
bot_id
,
content
=
content
,
bot_id
=
bot_id
,
content
=
content
,
...
@@ -111,7 +161,71 @@ async def _im_post_reasoning_hook(
...
@@ -111,7 +161,71 @@ async def _im_post_reasoning_hook(
except
Exception
:
except
Exception
:
logger
.
warning
(
logger
.
warning
(
"[Hook IM 发送失败] agent=
%
s room=
%
s(不影响推理流程)"
,
"[Hook IM 发送失败] agent=
%
s room=
%
s(不影响推理流程)"
,
self
.
name
,
room_id
,
exc_info
=
True
,
agent_name
,
room_id
,
exc_info
=
True
,
)
async
def
_bg_finalize_sub_agent
(
hub
:
"AgentHub"
,
sub_agent
,
sub_session_id
:
str
,
agent_code
:
str
,
ctx
:
dict
,
response_text
:
str
,
):
"""Fire-and-forget: 持久化子 Agent 消息 + 发送最终回复。"""
try
:
hub
.
session_service
.
get_or_create_session
(
session_id
=
sub_session_id
,
room_id
=
agent_code
,
channel
=
"sub_agent"
,
)
sub_memory_msgs
=
await
sub_agent
.
memory
.
get_memory
()
from
app.service.memory
import
SessionMemory
sub_session_memory
=
SessionMemory
(
session_id
=
sub_session_id
,
store
=
hub
.
session_service
.
store
,
)
for
msg
in
sub_memory_msgs
:
sub_session_memory
.
add
(
role
=
msg
.
role
,
content
=
msg
.
content
,
name
=
msg
.
name
,
)
await
asyncio
.
to_thread
(
hub
.
session_service
.
save_to_db
,
sub_session_id
)
logger
.
info
(
"[子Agent 保存] sub_session=
%
s messages=
%
d"
,
sub_session_id
,
len
(
sub_memory_msgs
),
)
except
Exception
:
logger
.
warning
(
"[子Agent 保存失败] sub_session=
%
s(不影响推理流程)"
,
sub_session_id
,
exc_info
=
True
,
)
try
:
await
hub
.
post_reply_hook
.
execute
({
"agent_name"
:
agent_code
,
"response_content"
:
response_text
,
"room_id"
:
ctx
[
"room_id"
],
"mentioned_list"
:
[
ctx
[
"user_id"
]],
"bot_id_mapping"
:
ctx
[
"bot_id_mapping"
],
})
except
Exception
:
logger
.
warning
(
"[子Agent IM 发送失败] agent=
%
s room=
%
s(不影响推理流程)"
,
agent_code
,
ctx
.
get
(
"room_id"
),
exc_info
=
True
,
)
async
def
_bg_save_to_db
(
save_fn
,
session_id
:
str
):
"""Fire-and-forget: 将同步 save_to_db 放入线程池执行。"""
try
:
await
asyncio
.
to_thread
(
save_fn
,
session_id
)
except
Exception
:
logger
.
warning
(
"[bg_task] save_to_db 异常 session=
%
s(不影响推理流程)"
,
session_id
,
exc_info
=
True
,
)
)
...
@@ -586,21 +700,23 @@ class AgentHub:
...
@@ -586,21 +700,23 @@ class AgentHub:
session_id
,
exc_info
=
True
,
session_id
,
exc_info
=
True
,
)
)
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory
.
add
(
"assistant"
,
response_raw
,
name
=
target_agent_name
)
call_count
=
_route_context_var
.
get
()
.
get
(
"call_count"
,
0
)
call_count
=
_route_context_var
.
get
()
.
get
(
"call_count"
,
0
)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
# 2. call_count >= 1:主Agent 静默,不保存最终回复("已委派"废话)
# 子Agent(含发言人)已各自通过 PostReplyHook 发送回复
if
call_count
>=
1
:
if
call_count
>=
1
:
memory
.
remove_last
()
logger
.
info
(
logger
.
info
(
"[主Agent 静默] call_count=
%
d,
已剔除
主Agent 最终回复,子Agent(含发言人)已发送回复"
,
"[主Agent 静默] call_count=
%
d,
跳过保存
主Agent 最终回复,子Agent(含发言人)已发送回复"
,
call_count
,
call_count
,
)
)
else
:
memory
.
add
(
"assistant"
,
response_raw
,
name
=
target_agent_name
)
# 4. 持久化(仅一次)
# 4. 异步持久化(不阻塞主流程)
self
.
session_service
.
save_to_db
(
session_id
)
_fire_and_forget
(
_bg_save_to_db
(
self
.
session_service
.
save_to_db
,
session_id
),
task_name
=
f
"save_db_{session_id}"
,
)
# 5. call_count == 0 时正常发 IM;>= 1 时不发
# 5. call_count == 0 时正常发 IM;>= 1 时不发
if
call_count
==
0
:
if
call_count
==
0
:
...
@@ -730,44 +846,17 @@ class AgentHub:
...
@@ -730,44 +846,17 @@ class AgentHub:
response_text
=
response
.
get_text_content
()
response_text
=
response
.
get_text_content
()
logger
.
info
(
"[子Agent 完成] agent_code=
%
s response_len=
%
d"
,
agent_code
,
len
(
response_text
)
if
response_text
else
0
)
logger
.
info
(
"[子Agent 完成] agent_code=
%
s response_len=
%
d"
,
agent_code
,
len
(
response_text
)
if
response_text
else
0
)
# 保存子 Agent 的 ReAct 消息到独立 KV + DB
# 异步化:保存子 Agent 消息 + 发送最终回复不阻塞主 Agent
try
:
_fire_and_forget
(
self
.
session_service
.
get_or_create_session
(
_bg_finalize_sub_agent
(
session_id
=
sub_session_id
,
hub
=
self
,
room_id
=
agent_code
,
sub_agent
=
sub_agent
,
channel
=
"sub_agent"
,
sub_session_id
=
sub_session_id
,
)
agent_code
=
agent_code
,
sub_memory_msgs
=
await
sub_agent
.
memory
.
get_memory
()
ctx
=
ctx
,
for
msg
in
sub_memory_msgs
:
response_text
=
response_text
,
sub_session_memory
.
add
(
),
role
=
msg
.
role
,
task_name
=
f
"finalize_sub_{agent_code}"
,
content
=
msg
.
content
,
name
=
msg
.
name
,
)
self
.
session_service
.
save_to_db
(
sub_session_id
)
logger
.
info
(
"[子Agent 保存] sub_session=
%
s messages=
%
d"
,
sub_session_id
,
len
(
sub_memory_msgs
),
)
except
Exception
:
logger
.
warning
(
"[子Agent 保存失败] sub_session=
%
s(不影响推理流程)"
,
sub_session_id
,
exc_info
=
True
,
)
# 子 Agent 用自己的 bot 账号发送最终回复
try
:
await
self
.
post_reply_hook
.
execute
({
"agent_name"
:
agent_code
,
"response_content"
:
response_text
,
"room_id"
:
ctx
[
"room_id"
],
"mentioned_list"
:
[
ctx
[
"user_id"
]],
"bot_id_mapping"
:
ctx
[
"bot_id_mapping"
],
})
except
Exception
:
logger
.
warning
(
"[子Agent IM 发送失败] agent=
%
s room=
%
s(不影响推理流程)"
,
agent_code
,
ctx
.
get
(
"room_id"
),
exc_info
=
True
,
)
)
return
response_text
return
response_text
...
...
workspace/agent-admin/backend/test_request.json
View file @
8ea607b
...
@@ -15,7 +15,7 @@
...
@@ -15,7 +15,7 @@
"sender_id"
:
""
,
"sender_id"
:
""
,
"sender_name"
:
"孙奇"
,
"sender_name"
:
"孙奇"
,
"msg_type"
:
"text"
,
"msg_type"
:
"text"
,
"msg_content"
:
"
我想知道问界延保的价格
"
,
"msg_content"
:
"
问界M8的价格和吸引客户的亮点
"
,
"payload"
:
{}
"payload"
:
{}
}
}
]
]
...
...
workspace/agent-admin/backend/tests/test_agent_hub.py
View file @
8ea607b
import
asyncio
import
pytest
import
pytest
from
unittest.mock
import
AsyncMock
,
MagicMock
,
patch
from
unittest.mock
import
AsyncMock
,
MagicMock
,
patch
from
fastapi.testclient
import
TestClient
from
fastapi.testclient
import
TestClient
...
@@ -7,10 +8,18 @@ from app.main import app as fastapi_app
...
@@ -7,10 +8,18 @@ from app.main import app as fastapi_app
# ── AgentHub 测试实例 ────────────────────────────────────────────
# ── AgentHub 测试实例 ────────────────────────────────────────────
from
app.config.settings
import
AgentConfig
from
app.config.settings
import
AgentConfig
from
app.service.active_session_service
import
ActiveSessionService
from
app.service.active_session_service
import
ActiveSessionService
from
app.service.agent_hub
import
AgentHub
,
AgentHubError
,
_route_context_var
from
app.service.agent_hub
import
AgentHub
,
AgentHubError
,
_route_context_var
,
_background_tasks
from
app.service.memory
import
SessionMemory
from
app.service.memory
import
SessionMemory
async
def
_drain_background_tasks
():
"""等待所有 fire-and-forget 后台任务完成(测试用)。"""
tasks
=
list
(
_background_tasks
)
_background_tasks
.
clear
()
if
tasks
:
await
asyncio
.
gather
(
*
tasks
,
return_exceptions
=
True
)
# 测试用 agent keys(替代原来的 "main" / "meeting")
# 测试用 agent keys(替代原来的 "main" / "meeting")
STEWARD_KEY
=
"agent_steward_test"
STEWARD_KEY
=
"agent_steward_test"
MEETING_KEY
=
"agent_meeting_test"
MEETING_KEY
=
"agent_meeting_test"
...
@@ -911,6 +920,8 @@ async def test_hook_summarizes_thinking_before_send():
...
@@ -911,6 +920,8 @@ async def test_hook_summarizes_thinking_before_send():
summarize_thinking
=
mock_summarize
,
summarize_thinking
=
mock_summarize
,
)
)
# 让 fire-and-forget 后台任务执行完再断言
await
_drain_background_tasks
()
mock_summarize
.
assert_called_once
()
mock_summarize
.
assert_called_once
()
sent_content
=
mock_im
.
send_message
.
call_args
[
1
][
"content"
]
sent_content
=
mock_im
.
send_message
.
call_args
[
1
][
"content"
]
assert
sent_content
==
"正在处理会议纪要"
assert
sent_content
==
"正在处理会议纪要"
...
@@ -942,8 +953,8 @@ async def test_hook_summarizes_even_short_thinking():
...
@@ -942,8 +953,8 @@ async def test_hook_summarizes_even_short_thinking():
summarize_thinking
=
mock_summarize
,
summarize_thinking
=
mock_summarize
,
)
)
#
不论长短都应调用摘要化
#
让 fire-and-forget 后台任务执行完再断言
mock_summarize
.
assert_called_once
()
await
_drain_background_tasks
()
@pytest.mark.asyncio
@pytest.mark.asyncio
...
@@ -1042,6 +1053,8 @@ class TestSubAgentPostReply:
...
@@ -1042,6 +1053,8 @@ class TestSubAgentPostReply:
with
patch
.
object
(
hub
,
'thinking_summary_model'
,
new
=
mock_reply
):
with
patch
.
object
(
hub
,
'thinking_summary_model'
,
new
=
mock_reply
):
with
patch
.
object
(
hub
.
post_reply_hook
,
'execute'
,
new
=
mock_execute
):
with
patch
.
object
(
hub
.
post_reply_hook
,
'execute'
,
new
=
mock_execute
):
result
=
await
hub
.
_call_sub_agent
(
MEETING_KEY
,
"处理会议录音"
)
result
=
await
hub
.
_call_sub_agent
(
MEETING_KEY
,
"处理会议录音"
)
# 在 with 块内让后台任务执行,确保 mock_execute 仍生效
await
_drain_background_tasks
()
finally
:
finally
:
_route_context_var
.
reset
(
token
)
_route_context_var
.
reset
(
token
)
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment