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 a1db4827
authored
May 23, 2026
by
sunqi02
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
灾后重建
1 parent
392bbb3e
Hide whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
814 additions
and
32 deletions
workspace/agent-admin/backend/app/api/v1/endpoints/agent_hub.py
workspace/agent-admin/backend/app/api/v1/router.py
workspace/agent-admin/backend/send_test.sh
workspace/agent-admin/backend/tests/test_agent_hub.py
workspace/agent-admin/backend/tests/test_agents_api.py
workspace/agent-admin/backend/tests/test_read_file_tool.py
workspace/agent-admin/backend/app/api/v1/endpoints/agent_hub.py
0 → 100644
View file @
a1db482
import
logging
from
fastapi
import
APIRouter
,
BackgroundTasks
,
Depends
,
HTTPException
from
pydantic
import
BaseModel
,
Field
from
typing
import
Optional
,
List
from
app.service.agent_hub
import
AgentHub
logger
=
logging
.
getLogger
(
__name__
)
router
=
APIRouter
()
# ── 新请求 Schema ──
class
GroupInfo
(
BaseModel
):
group_contact_id
:
Optional
[
str
]
=
Field
(
None
,
description
=
"群联系人ID"
)
group_name
:
Optional
[
str
]
=
Field
(
None
,
description
=
"群名称"
)
bot_code
:
Optional
[
str
]
=
Field
(
None
,
description
=
"机器人编码"
)
class
PositionInfo
(
BaseModel
):
position_id
:
Optional
[
int
]
=
Field
(
None
,
description
=
"岗位ID"
)
position_code
:
Optional
[
str
]
=
Field
(
None
,
description
=
"岗位编码"
)
position_name
:
Optional
[
str
]
=
Field
(
None
,
description
=
"岗位名称"
)
class
AgentInfo
(
BaseModel
):
agent_id
:
int
=
Field
(
...
,
description
=
"Agent ID,对应 agent.code"
)
agent_name
:
str
=
Field
(
...
,
description
=
"Agent 名称"
)
class
MessageInfo
(
BaseModel
):
msg_id
:
str
=
Field
(
...
,
description
=
"消息ID"
)
msg_time
:
str
=
Field
(
...
,
description
=
"消息时间"
)
sender_id
:
str
=
Field
(
...
,
description
=
"发送者ID"
)
sender_name
:
Optional
[
str
]
=
Field
(
None
,
description
=
"发送者名称"
)
msg_type
:
str
=
Field
(
...
,
description
=
"消息类型: text / image"
)
msg_content
:
str
=
Field
(
default
=
""
,
description
=
"消息内容(text 为文本,image 为图片 URL)"
)
payload
:
Optional
[
dict
]
=
Field
(
default_factory
=
dict
,
description
=
"扩展字段"
)
class
ChatRequest
(
BaseModel
):
session_id
:
str
=
Field
(
...
,
description
=
"会话ID"
)
group
:
Optional
[
GroupInfo
]
=
Field
(
default
=
None
,
description
=
"群信息"
)
position
:
Optional
[
PositionInfo
]
=
Field
(
default
=
None
,
description
=
"岗位信息"
)
agents
:
List
[
AgentInfo
]
=
Field
(
default_factory
=
list
,
description
=
"可用 Agent 列表"
)
messages
:
List
[
MessageInfo
]
=
Field
(
...
,
min_length
=
1
,
description
=
"消息列表"
)
def
get_agent_hub
():
from
app.main
import
agent_hub_instance
return
agent_hub_instance
@router.post
(
"/completions"
)
async
def
chat
(
request
:
ChatRequest
,
background_tasks
:
BackgroundTasks
,
agent_hub
:
AgentHub
=
Depends
(
get_agent_hub
),
):
"""
接收消息后立即返回 200,Agent 在后台异步处理。
处理结果通过 PostReplyHook 发送到 IM。
"""
# 1. 提取 query:text 消息的 msg_content 用 \n 拼接
text_parts
=
[]
file_url
:
Optional
[
str
]
=
None
for
msg
in
request
.
messages
:
if
msg
.
msg_type
==
"text"
:
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
# 取第一张图片 URL
query
=
"
\n
"
.
join
(
text_parts
)
if
not
query
:
raise
HTTPException
(
status_code
=
400
,
detail
=
"messages 中没有文本消息"
)
# 2. 提取 user_id:取最后一条消息的 sender_id
user_id
=
request
.
messages
[
-
1
]
.
sender_id
# 3. 提取 room_id
room_id
=
""
if
request
.
group
and
request
.
group
.
group_contact_id
:
room_id
=
request
.
group
.
group_contact_id
# 4. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射
allowed_agent_codes
:
Optional
[
list
]
=
None
if
request
.
agents
:
# 构建 agent.code → 内部名称(dict key)映射
code_to_name
=
{
cfg
.
code
:
name
for
name
,
cfg
in
agent_hub
.
agents
.
items
()
}
allowed_agent_codes
=
[]
for
agent_info
in
request
.
agents
:
agent_code_str
=
str
(
agent_info
.
agent_id
)
internal_name
=
code_to_name
.
get
(
agent_code_str
)
if
internal_name
and
internal_name
!=
"main"
:
allowed_agent_codes
.
append
(
internal_name
)
if
not
allowed_agent_codes
:
allowed_agent_codes
=
None
# 无有效子 agent,走默认路由
# 5. 后台异步处理
background_tasks
.
add_task
(
_process_message_async
,
agent_hub
=
agent_hub
,
session_id
=
request
.
session_id
,
room_id
=
room_id
,
user_id
=
user_id
,
user_query
=
query
,
file_url
=
file_url
,
allowed_agent_codes
=
allowed_agent_codes
,
)
return
{
"status"
:
"ok"
,
"session_id"
:
request
.
session_id
}
async
def
_process_message_async
(
agent_hub
:
AgentHub
,
session_id
:
str
,
room_id
:
str
,
user_id
:
str
,
user_query
:
str
,
file_url
:
Optional
[
str
],
allowed_agent_codes
:
Optional
[
list
],
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try
:
await
agent_hub
.
process_message
(
session_id
=
session_id
,
room_id
=
room_id
,
user_id
=
user_id
,
user_query
=
user_query
,
file_url
=
file_url
,
allowed_agent_codes
=
allowed_agent_codes
,
)
except
Exception
:
logger
.
exception
(
"Agent 后台处理失败: session=
%
s user=
%
s query=
%
s"
,
session_id
,
user_id
,
user_query
[:
50
],
)
workspace/agent-admin/backend/app/api/v1/router.py
View file @
a1db482
from
fastapi
import
APIRouter
from
fastapi
import
APIRouter
from
app.api.v1.endpoints
import
agent_group_helper
,
agents
,
position_tags
,
skills
,
routing
,
analytics
,
qrcode_channel
,
official_site_tab
,
official_site_agent_display
,
official_site_upload
,
official_site_home
,
methodology
,
wecom_sync
,
wecom_jobs
from
app.api.v1.endpoints
import
agent_group_helper
,
agent
_hub
,
agent
s
,
position_tags
,
skills
,
routing
,
analytics
,
qrcode_channel
,
official_site_tab
,
official_site_agent_display
,
official_site_upload
,
official_site_home
,
methodology
,
wecom_sync
,
wecom_jobs
api_router
=
APIRouter
()
api_router
=
APIRouter
()
api_router
.
include_router
(
agent_group_helper
.
router
,
tags
=
[
"agent-group-helper"
])
api_router
.
include_router
(
agent_group_helper
.
router
,
tags
=
[
"agent-group-helper"
])
...
@@ -16,3 +16,4 @@ api_router.include_router(official_site_home.router, tags=["official-site-home"]
...
@@ -16,3 +16,4 @@ api_router.include_router(official_site_home.router, tags=["official-site-home"]
api_router
.
include_router
(
methodology
.
router
,
tags
=
[
"methodology"
])
api_router
.
include_router
(
methodology
.
router
,
tags
=
[
"methodology"
])
api_router
.
include_router
(
wecom_sync
.
router
,
tags
=
[
"wecom-sync"
])
api_router
.
include_router
(
wecom_sync
.
router
,
tags
=
[
"wecom-sync"
])
api_router
.
include_router
(
wecom_jobs
.
router
,
tags
=
[
"wecom-jobs"
])
api_router
.
include_router
(
wecom_jobs
.
router
,
tags
=
[
"wecom-jobs"
])
api_router
.
include_router
(
agent_hub
.
router
,
prefix
=
"/api/v1/chat"
,
tags
=
[
"chat"
])
workspace/agent-admin/backend/send_test.sh
0 → 100644
View file @
a1db482
#!/bin/bash
# 模拟用户消息发送到 Agent 服务
# 用法: ./send_test.sh "你的问题"
# 例如: ./send_test.sh "帮我整理上周的会议纪要"
QUERY
=
"
${
1
:-
你好,请问你能帮我什么?
}
"
API_URL
=
"
${
API_URL
:-
http
://localhost:8000/api/v1/chat/completions
}
"
echo
"=========================================="
echo
" 发送测试消息到 AgentHub"
echo
"=========================================="
echo
""
echo
"提问:
${
QUERY
}
"
echo
""
# 用 jq 替换 messages[0].msg_content 字段
if
command
-v jq &> /dev/null;
then
PAYLOAD
=
$(
jq --arg q
"
${
QUERY
}
"
'.messages[0].msg_content = $q'
test_request.json
)
else
PAYLOAD
=
$(
sed
"s/{{QUERY}}/
${
QUERY
}
/g"
test_request.json
)
fi
echo
"--- 请求体 ---"
echo
"
${
PAYLOAD
}
"
| python3 -m json.tool 2>/dev/null
||
echo
"
${
PAYLOAD
}
"
echo
""
echo
"--- 开始请求 ---"
echo
"POST
${
API_URL
}
"
echo
""
HTTP_CODE
=
$(
curl -s -w
"
\n
%{http_code}"
-X POST
"
${
API_URL
}
"
\
-H
"Content-Type: application/json"
\
-d
"
${
PAYLOAD
}
"
)
# 分离 body 和 status code
BODY
=
$(
echo
"
${
HTTP_CODE
}
"
| sed
'$d'
)
STATUS
=
$(
echo
"
${
HTTP_CODE
}
"
| tail -n1
)
echo
"--- 响应 (HTTP
${
STATUS
}
) ---"
echo
"
${
BODY
}
"
| python3 -m json.tool 2>/dev/null
||
echo
"
${
BODY
}
"
echo
""
echo
"=========================================="
echo
" 完成"
echo
"=========================================="
workspace/agent-admin/backend/tests/test_agent_hub.py
0 → 100644
View file @
a1db482
import
pytest
from
unittest.mock
import
AsyncMock
,
MagicMock
,
patch
from
fastapi.testclient
import
TestClient
from
app.main
import
app
as
fastapi_app
# ── AgentHub 测试实例 ────────────────────────────────────────────
from
app.config.loader
import
ConfigLoader
from
app.service.active_session_service
import
ActiveSessionService
from
app.service.agent_hub
import
AgentHub
,
AgentHubError
from
app.service.memory
import
SessionMemory
def
_make_test_hub
():
session_service
=
ActiveSessionService
()
im_service
=
MagicMock
()
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
return
AgentHub
(
config_loader
=
ConfigLoader
(),
session_service
=
session_service
,
im_service
=
im_service
,
)
test_hub
=
_make_test_hub
()
def
_make_mock_model_reply
(
text
:
str
):
"""创建一个返回纯文本的 mock model,供 ReActAgent 内部调用。"""
def
_make_resp
(
blocks
):
r
=
MagicMock
()
r
.
content
=
blocks
return
r
async
def
side_effect
(
*
args
,
**
kwargs
):
return
_make_resp
([{
"type"
:
"text"
,
"text"
:
text
}])
mock
=
AsyncMock
(
side_effect
=
side_effect
)
mock
.
stream
=
False
# 关键:让 ReActAgent 走非流式路径
return
mock
async
def
_noop_format
(
msgs
):
"""透传 formatter,让 ReActAgent 直接传递 Msg 列表给 mock model。"""
return
msgs
def
_override_get_agent_hub
():
return
test_hub
from
app.api.v1.endpoints.agent_hub
import
get_agent_hub
fastapi_app
.
dependency_overrides
[
get_agent_hub
]
=
_override_get_agent_hub
client
=
TestClient
(
fastapi_app
)
# ── Helper: 构造新格式请求体 ──
def
_make_request
(
session_id
:
str
=
"sess_test"
,
query
:
str
=
"你好"
,
agents
:
list
=
None
,
group_contact_id
:
str
=
"room_001"
,
sender_id
:
str
=
"user_001"
,
extra_messages
:
list
=
None
,
)
->
dict
:
"""构造符合新 API 格式的请求体。"""
body
=
{
"session_id"
:
session_id
,
"group"
:
{
"group_contact_id"
:
group_contact_id
,
"group_name"
:
"测试群"
,
"bot_code"
:
"test_bot"
,
},
"position"
:
{
"position_id"
:
1
,
"position_code"
:
"store_sales"
,
"position_name"
:
"驻店销售岗"
,
},
"agents"
:
agents
or
[{
"agent_id"
:
101
,
"agent_name"
:
"会议纪要 Agent"
}],
"messages"
:
[
{
"msg_id"
:
"m1"
,
"msg_time"
:
"2026-05-23T10:00:00Z"
,
"sender_id"
:
sender_id
,
"sender_name"
:
"测试用户"
,
"msg_type"
:
"text"
,
"msg_content"
:
query
,
"payload"
:
{},
}
],
}
if
extra_messages
:
body
[
"messages"
]
.
extend
(
extra_messages
)
return
body
def
_get_session_messages
(
session_id
:
str
)
->
list
:
"""Helper: 从 SessionStore 获取消息历史"""
data
=
test_hub
.
session_service
.
store
.
get
(
session_id
)
if
data
:
return
data
.
get
(
"conversation_history"
,
[])
return
[]
# ═══════════════════════════════════════════════════════════════════
# API 层集成测试 — POST /api/v1/chat/completions (新异步格式)
# ═══════════════════════════════════════════════════════════════════
class
TestChatCompletionsAPI
:
def
test_returns_200_with_new_format
(
self
):
"""新格式请求 → 立即返回 200 + session_id"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"你好"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
_make_request
(
session_id
=
"sess_api_001"
,
query
=
"你好"
),
)
assert
resp
.
status_code
==
200
data
=
resp
.
json
()[
"data"
]
assert
data
[
"status"
]
==
"ok"
assert
data
[
"session_id"
]
==
"sess_api_001"
def
test_session_created_from_group_contact_id
(
self
):
"""group_contact_id → room_id, 会话被创建"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"收到"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
_make_request
(
session_id
=
"sess_api_002"
,
query
=
"测试"
,
group_contact_id
=
"grp_room_99"
,
),
)
assert
resp
.
status_code
==
200
session_data
=
test_hub
.
session_service
.
store
.
get
(
"sess_api_002"
)
assert
session_data
is
not
None
assert
session_data
[
"room_id"
]
==
"grp_room_99"
def
test_user_id_from_last_message_sender
(
self
):
"""user_id 从 messages 最后一条消息的 sender_id 推导"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"收到"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
_make_request
(
session_id
=
"sess_api_003"
,
query
=
"你好"
,
extra_messages
=
[
{
"msg_id"
:
"m2"
,
"msg_time"
:
"2026-05-23T10:01:00Z"
,
"sender_id"
:
"user_last"
,
"sender_name"
:
"最后发言者"
,
"msg_type"
:
"text"
,
"msg_content"
:
"第二条消息"
,
"payload"
:
{},
}
],
),
)
assert
resp
.
status_code
==
200
# 验证后台处理时 user_id 使用了最后一条 sender
messages
=
_get_session_messages
(
"sess_api_003"
)
# 至少有 user 消息被存储
assert
len
(
messages
)
>=
1
def
test_image_message_extracts_file_url
(
self
):
"""image 类型消息的 msg_content 作为图片 URL 传给 Agent"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"我看到了一张图片"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
{
"session_id"
:
"sess_img_001"
,
"messages"
:
[
{
"msg_id"
:
"m1"
,
"msg_time"
:
"2026-05-23T10:00:00Z"
,
"sender_id"
:
"user_001"
,
"msg_type"
:
"text"
,
"msg_content"
:
"这张图片是什么"
,
"payload"
:
{},
},
{
"msg_id"
:
"m2"
,
"msg_time"
:
"2026-05-23T10:00:01Z"
,
"sender_id"
:
"user_001"
,
"msg_type"
:
"image"
,
"msg_content"
:
"https://oss.example.com/img/photo.jpg"
,
"payload"
:
{},
},
],
},
)
assert
resp
.
status_code
==
200
def
test_agents_filter_allowed_codes
(
self
):
"""agents 数组中的 agent_id 映射为 allowed_agent_codes"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"回复"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
# agents 中包含 agent_id=101(meeting agent)
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
_make_request
(
session_id
=
"sess_agent_filter"
,
query
=
"你好"
,
agents
=
[{
"agent_id"
:
101
,
"agent_name"
:
"会议纪要 Agent"
}],
),
)
assert
resp
.
status_code
==
200
def
test_missing_messages_returns_400
(
self
):
"""缺少 messages 字段 → 400"""
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
{
"session_id"
:
"sess_no_msg"
},
)
assert
resp
.
status_code
==
400
def
test_empty_messages_returns_400
(
self
):
"""空 messages 数组 → 400"""
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
{
"session_id"
:
"sess_empty_msg"
,
"messages"
:
[],
},
)
assert
resp
.
status_code
==
400
def
test_text_only_messages_returns_400
(
self
):
"""只有 image 消息没有 text → 400"""
resp
=
client
.
post
(
"/api/v1/chat/completions"
,
json
=
{
"session_id"
:
"sess_img_only"
,
"messages"
:
[
{
"msg_id"
:
"m1"
,
"msg_time"
:
"2026-05-23T10:00:00Z"
,
"sender_id"
:
"user_001"
,
"msg_type"
:
"image"
,
"msg_content"
:
"https://example.com/img.jpg"
,
"payload"
:
{},
},
],
},
)
assert
resp
.
status_code
==
400
# ═══════════════════════════════════════════════════════════════════
# PostReplyHook 单元测试
# ═══════════════════════════════════════════════════════════════════
class
TestPostReplyHook
:
@pytest.mark.asyncio
async
def
test_strips_thinking_blocks_before_send
(
self
):
from
app.hooks.post_reply
import
PostReplyHook
mock_im
=
AsyncMock
()
mock_im
.
send_message
.
return_value
=
{
"code"
:
200
}
hook
=
PostReplyHook
(
im_service
=
mock_im
,
account_mapping
=
{
"main"
:
"bot_main_001"
}
)
await
hook
.
execute
(
{
"agent_name"
:
"main"
,
"response_content"
:
"正常回复<thinking>内部思考</thinking>继续回复"
,
"room_id"
:
"room_001"
,
"mentioned_list"
:
[
"user_001"
],
}
)
sent
=
mock_im
.
send_message
.
call_args
[
1
][
"content"
]
assert
"<thinking>"
not
in
sent
assert
"正常回复"
in
sent
assert
"继续回复"
in
sent
@pytest.mark.asyncio
async
def
test_skips_when_agent_name_missing
(
self
):
from
app.hooks.post_reply
import
PostReplyHook
mock_im
=
AsyncMock
()
hook
=
PostReplyHook
(
im_service
=
mock_im
,
account_mapping
=
{
"main"
:
"bot_main_001"
}
)
result
=
await
hook
.
execute
(
{
"response_content"
:
"内容"
,
"room_id"
:
"room_001"
}
)
assert
result
is
None
mock_im
.
send_message
.
assert_not_called
()
@pytest.mark.asyncio
async
def
test_skips_when_response_content_missing
(
self
):
from
app.hooks.post_reply
import
PostReplyHook
mock_im
=
AsyncMock
()
hook
=
PostReplyHook
(
im_service
=
mock_im
,
account_mapping
=
{
"main"
:
"bot_main_001"
}
)
result
=
await
hook
.
execute
(
{
"agent_name"
:
"main"
,
"room_id"
:
"room_001"
}
)
assert
result
is
None
mock_im
.
send_message
.
assert_not_called
()
@pytest.mark.asyncio
async
def
test_skips_for_unmapped_agent
(
self
):
from
app.hooks.post_reply
import
PostReplyHook
mock_im
=
AsyncMock
()
hook
=
PostReplyHook
(
im_service
=
mock_im
,
account_mapping
=
{
"main"
:
"bot_main_001"
}
)
result
=
await
hook
.
execute
(
{
"agent_name"
:
"unknown_agent"
,
"response_content"
:
"回复"
,
"room_id"
:
"room_001"
,
"mentioned_list"
:
[],
}
)
assert
result
is
None
mock_im
.
send_message
.
assert_not_called
()
@pytest.mark.asyncio
async
def
test_skips_when_content_empty_after_strip
(
self
):
from
app.hooks.post_reply
import
PostReplyHook
mock_im
=
AsyncMock
()
hook
=
PostReplyHook
(
im_service
=
mock_im
,
account_mapping
=
{
"main"
:
"bot_main_001"
}
)
result
=
await
hook
.
execute
(
{
"agent_name"
:
"main"
,
"response_content"
:
"<thinking>只有思考</thinking>"
,
"room_id"
:
"room_001"
,
"mentioned_list"
:
[],
}
)
assert
result
is
None
mock_im
.
send_message
.
assert_not_called
()
# ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试(直接调用 process_message)
# ═══════════════════════════════════════════════════════════════════
class
TestAgentHubRouting
:
@pytest.mark.asyncio
async
def
test_process_message_returns_routing_metadata
(
self
):
"""验证返回结构包含所有必需字段"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"回复内容"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_meta_001"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"测试问题"
,
)
assert
"session_id"
in
result
assert
result
[
"response_agent_code"
]
==
"main"
assert
result
[
"routing_reason"
]
==
"default"
assert
result
[
"response_content"
]
==
"回复内容"
assert
isinstance
(
result
[
"processing_time_ms"
],
float
)
assert
result
[
"processing_time_ms"
]
>=
0
@pytest.mark.asyncio
async
def
test_preserves_session_across_calls
(
self
):
"""同一 session_id 多次调用,消息累积在同一 session"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"回复"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
sid
=
"sess_persist_001"
await
test_hub
.
process_message
(
session_id
=
sid
,
room_id
=
"r1"
,
user_id
=
"u1"
,
user_query
=
"Q1"
)
await
test_hub
.
process_message
(
session_id
=
sid
,
room_id
=
"r1"
,
user_id
=
"u1"
,
user_query
=
"Q2"
)
messages
=
_get_session_messages
(
sid
)
assert
len
(
messages
)
==
4
# 2 user + 2 assistant
@pytest.mark.asyncio
async
def
test_default_routing_to_main
(
self
):
"""未指定 agent → 路由到 main"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"你好,我是智能助手"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_route_001"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"你好"
,
)
assert
result
[
"response_agent_code"
]
==
"main"
assert
result
[
"routing_reason"
]
==
"default"
assert
len
(
result
[
"response_content"
])
>
0
@pytest.mark.asyncio
async
def
test_mention_routing_to_sub_agent
(
self
):
"""mentioned_agent_code='meeting' → 直接路由到 meeting"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"已为你整理会议纪要"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_route_002"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"整理会议纪要"
,
mentioned_agent_code
=
"meeting"
,
)
assert
result
[
"response_agent_code"
]
==
"meeting"
assert
result
[
"routing_reason"
]
==
"mention"
@pytest.mark.asyncio
async
def
test_inheritance_routing
(
self
):
"""首次 meeting,第二次不 mention → 继承 meeting"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"会议纪要内容"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
sid
=
"sess_route_003"
r1
=
await
test_hub
.
process_message
(
session_id
=
sid
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"查会议纪要"
,
mentioned_agent_code
=
"meeting"
,
)
assert
r1
[
"response_agent_code"
]
==
"meeting"
r2
=
await
test_hub
.
process_message
(
session_id
=
sid
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"再查一个"
,
)
assert
r2
[
"response_agent_code"
]
==
"meeting"
assert
r2
[
"routing_reason"
]
==
"inheritance"
@pytest.mark.asyncio
async
def
test_messages_accumulate
(
self
):
"""同一 session 多次请求,消息累积"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"回复内容"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
sid
=
"sess_accumulate"
for
i
in
range
(
3
):
await
test_hub
.
process_message
(
session_id
=
sid
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
f
"问题{i + 1}"
,
)
messages
=
_get_session_messages
(
sid
)
assert
len
(
messages
)
==
6
# 3 user + 3 assistant
@pytest.mark.asyncio
async
def
test_channel_default_value
(
self
):
"""channel 字段默认为 wechat_group"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"收到"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
await
test_hub
.
process_message
(
session_id
=
"sess_channel"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"测试"
,
)
session_data
=
test_hub
.
session_service
.
store
.
get
(
"sess_channel"
)
assert
session_data
is
not
None
assert
session_data
[
"channel"
]
==
"wechat_group"
@pytest.mark.asyncio
async
def
test_image_url_appended_to_query
(
self
):
"""file_url 不为空时,图片 URL 追加到 query 中"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"我看到图片了"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_img"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"这张图片是什么"
,
file_url
=
"https://oss.example.com/img/photo.jpg"
,
)
assert
result
[
"response_content"
]
is
not
None
@pytest.mark.asyncio
async
def
test_allowed_agent_codes_restricts_routing
(
self
):
"""allowed_agent_codes 限制路由范围"""
with
patch
.
object
(
test_hub
,
'model'
,
new
=
_make_mock_model_reply
(
"回复"
)):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
# allowed 中不包含 meeting,mention meeting 应回退到 main
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_restricted"
,
room_id
=
"room_001"
,
user_id
=
"user_001"
,
user_query
=
"整理会议纪要"
,
mentioned_agent_code
=
"meeting"
,
allowed_agent_codes
=
[],
# 空列表,不允许任何子 agent
)
assert
result
[
"response_agent_code"
]
==
"main"
assert
result
[
"routing_reason"
]
==
"position_restricted"
# ═══════════════════════════════════════════════════════════════════
# 协作层集成测试 — call_sub_agent 串行链
# ═══════════════════════════════════════════════════════════════════
class
TestCollaboration
:
"""Serial chain collaboration integration tests — simulate multi-call ReAct with call_sub_agent."""
@pytest.mark.asyncio
async
def
test_serial_chain_two_sub_agents
(
self
):
"""Simulate: model calls meeting → then task → then returns integrated result."""
# Three model calls: tool_call(meeting) → tool_call(task) → text reply
responses
=
[
[{
"type"
:
"tool_use"
,
"id"
:
"call_1"
,
"name"
:
"call_sub_agent"
,
"input"
:
{
"agent_code"
:
"meeting"
,
"instruction"
:
"整理纪要"
}}],
[{
"type"
:
"tool_use"
,
"id"
:
"call_2"
,
"name"
:
"call_sub_agent"
,
"input"
:
{
"agent_code"
:
"task"
,
"instruction"
:
"提取待办"
}}],
[{
"type"
:
"text"
,
"text"
:
"已整理纪要并提取待办:1.提交方案 2.确认预算"
}],
]
call_count
=
[
0
]
def
_make_resp
(
blocks
):
r
=
MagicMock
()
r
.
content
=
blocks
return
r
async
def
model_side_effect
(
*
args
,
**
kwargs
):
idx
=
min
(
call_count
[
0
],
len
(
responses
)
-
1
)
result
=
_make_resp
(
responses
[
idx
])
call_count
[
0
]
+=
1
return
result
async
def
mock_sub_call
(
agent_code
,
instruction
):
if
agent_code
==
"meeting"
:
return
"纪要: 讨论了Q2预算和团队调整"
elif
agent_code
==
"task"
:
return
"待办: 1.提交Q2预算 2.人员调整方案"
return
""
model_mock
=
AsyncMock
(
side_effect
=
model_side_effect
)
model_mock
.
stream
=
False
with
patch
.
object
(
test_hub
,
'model'
,
new
=
model_mock
):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
with
patch
.
object
(
test_hub
,
'_call_sub_agent'
,
new
=
AsyncMock
(
side_effect
=
mock_sub_call
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_collab_001"
,
room_id
=
"room_001"
,
user_id
=
"u1"
,
user_query
=
"整理纪要并提取待办"
,
)
assert
"已整理"
in
result
[
"response_content"
]
@pytest.mark.asyncio
async
def
test_max_iterations_limit
(
self
):
"""Loop exceeding 10 iterations — ReActAgent generates summary, no exception."""
tool_call_blocks
=
[
{
"type"
:
"tool_use"
,
"id"
:
"call_x"
,
"name"
:
"call_sub_agent"
,
"input"
:
{
"agent_code"
:
"meeting"
,
"instruction"
:
"x"
}}
]
async
def
model_side_effect
(
prompt
,
tools
=
None
,
**
kwargs
):
r
=
MagicMock
()
if
tools
is
None
:
# _summarizing() call — return text
r
.
content
=
[{
"type"
:
"text"
,
"text"
:
"已达最大迭代次数,总结当前情况。"
}]
else
:
r
.
content
=
tool_call_blocks
return
r
async
def
mock_sub_call
(
*
args
,
**
kwargs
):
return
"result"
model_mock_2
=
AsyncMock
(
side_effect
=
model_side_effect
)
model_mock_2
.
stream
=
False
with
patch
.
object
(
test_hub
,
'model'
,
new
=
model_mock_2
):
with
patch
.
object
(
test_hub
.
formatter
,
'format'
,
new
=
AsyncMock
(
side_effect
=
_noop_format
)):
with
patch
.
object
(
test_hub
,
'_call_sub_agent'
,
new
=
AsyncMock
(
side_effect
=
mock_sub_call
)):
result
=
await
test_hub
.
process_message
(
session_id
=
"sess_limit_001"
,
room_id
=
"room_001"
,
user_id
=
"u1"
,
user_query
=
"test"
,
)
# ReActAgent hits max_iters and _summarizing() generates text
assert
result
[
"response_content"
]
is
not
None
assert
len
(
result
[
"response_content"
])
>
0
workspace/agent-admin/backend/tests/test_agents_api.py
View file @
a1db482
...
@@ -2,7 +2,7 @@ import pytest
...
@@ -2,7 +2,7 @@ import pytest
from
fastapi.testclient
import
TestClient
from
fastapi.testclient
import
TestClient
from
app.main
import
app
from
app.main
import
app
from
app.model.agent
import
Agent
,
AgentPosition
,
AgentSkill
,
AgentUser
from
app.model.agent
import
Agent
,
AgentPosition
,
AgentSkill
from
app.model.agent_group
import
QrcodeChannel
from
app.model.agent_group
import
QrcodeChannel
from
app.model.position_tag
import
PositionTag
from
app.model.position_tag
import
PositionTag
from
app.model.skill
import
Skill
from
app.model.skill
import
Skill
...
@@ -17,7 +17,6 @@ def clean_db():
...
@@ -17,7 +17,6 @@ def clean_db():
db
.
query
(
Skill
)
.
delete
()
db
.
query
(
Skill
)
.
delete
()
db
.
query
(
QrcodeChannel
)
.
delete
()
db
.
query
(
QrcodeChannel
)
.
delete
()
db
.
query
(
PositionTag
)
.
delete
()
db
.
query
(
PositionTag
)
.
delete
()
db
.
query
(
AgentUser
)
.
delete
()
db
.
query
(
AgentSkill
)
.
delete
()
db
.
query
(
AgentSkill
)
.
delete
()
db
.
query
(
AgentPosition
)
.
delete
()
db
.
query
(
AgentPosition
)
.
delete
()
db
.
query
(
Agent
)
.
delete
()
db
.
query
(
Agent
)
.
delete
()
...
...
workspace/agent-admin/backend/tests/test_read_file_tool.py
View file @
a1db482
...
@@ -6,7 +6,7 @@ from pathlib import Path
...
@@ -6,7 +6,7 @@ from pathlib import Path
from
unittest.mock
import
MagicMock
,
AsyncMock
from
unittest.mock
import
MagicMock
,
AsyncMock
from
app.config.loader
import
ConfigLoader
from
app.config.loader
import
ConfigLoader
from
app.service.
session_service
import
SessionService
from
app.service.
active_session_service
import
Active
SessionService
from
app.service.agent_hub
import
AgentHub
from
app.service.agent_hub
import
AgentHub
from
agentscope.message._message_block
import
TextBlock
from
agentscope.message._message_block
import
TextBlock
...
@@ -37,9 +37,9 @@ def sandbox_root(tmp_path):
...
@@ -37,9 +37,9 @@ def sandbox_root(tmp_path):
@pytest.fixture
@pytest.fixture
def
hub_with_sandbox
(
sandbox_root
,
db_session
):
def
hub_with_sandbox
(
sandbox_root
):
"""Create an AgentHub whose read_file tool is sandboxed to tmp_path."""
"""Create an AgentHub whose read_file tool is sandboxed to tmp_path."""
session_service
=
SessionService
(
db_session
)
session_service
=
ActiveSessionService
(
)
im_service
=
MagicMock
()
im_service
=
MagicMock
()
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
...
@@ -226,22 +226,12 @@ class TestReadFileToolRegistration:
...
@@ -226,22 +226,12 @@ class TestReadFileToolRegistration:
def
test_read_file_in_toolkit_schemas
(
self
):
def
test_read_file_in_toolkit_schemas
(
self
):
"""read_file 出现在 toolkit JSON schema 中"""
"""read_file 出现在 toolkit JSON schema 中"""
from
sqlalchemy
import
create_engine
from
sqlalchemy.orm
import
sessionmaker
from
sqlalchemy.pool
import
StaticPool
from
app.infrastructure.database
import
Base
engine
=
create_engine
(
"sqlite://"
,
connect_args
=
{
"check_same_thread"
:
False
},
poolclass
=
StaticPool
)
Base
.
metadata
.
create_all
(
bind
=
engine
)
Session
=
sessionmaker
(
bind
=
engine
)
db
=
Session
()
im_service
=
MagicMock
()
im_service
=
MagicMock
()
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
hub
=
AgentHub
(
hub
=
AgentHub
(
config_loader
=
ConfigLoader
(),
config_loader
=
ConfigLoader
(),
session_service
=
SessionService
(
db
),
session_service
=
ActiveSessionService
(
),
im_service
=
im_service
,
im_service
=
im_service
,
)
)
...
@@ -253,31 +243,17 @@ class TestReadFileToolRegistration:
...
@@ -253,31 +243,17 @@ class TestReadFileToolRegistration:
read_file_schema
=
next
(
s
for
s
in
schemas
if
s
[
"function"
][
"name"
]
==
"read_file"
)
read_file_schema
=
next
(
s
for
s
in
schemas
if
s
[
"function"
][
"name"
]
==
"read_file"
)
assert
"file_path"
in
read_file_schema
[
"function"
][
"parameters"
][
"properties"
]
assert
"file_path"
in
read_file_schema
[
"function"
][
"parameters"
][
"properties"
]
db
.
close
()
def
test_read_file_in_all_agent_toolkits
(
self
):
def
test_read_file_in_all_agent_toolkits
(
self
):
"""read_file 注册到所有 agent 的专属 toolkit"""
"""read_file 注册到所有 agent 的专属 toolkit"""
from
sqlalchemy
import
create_engine
from
sqlalchemy.orm
import
sessionmaker
from
sqlalchemy.pool
import
StaticPool
from
app.infrastructure.database
import
Base
engine
=
create_engine
(
"sqlite://"
,
connect_args
=
{
"check_same_thread"
:
False
},
poolclass
=
StaticPool
)
Base
.
metadata
.
create_all
(
bind
=
engine
)
Session
=
sessionmaker
(
bind
=
engine
)
db
=
Session
()
im_service
=
MagicMock
()
im_service
=
MagicMock
()
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
im_service
.
send_message
=
AsyncMock
(
return_value
=
{
"code"
:
200
})
hub
=
AgentHub
(
hub
=
AgentHub
(
config_loader
=
ConfigLoader
(),
config_loader
=
ConfigLoader
(),
session_service
=
SessionService
(
db
),
session_service
=
ActiveSessionService
(
),
im_service
=
im_service
,
im_service
=
im_service
,
)
)
for
agent_code
,
agent_tk
in
hub
.
agent_toolkits
.
items
():
for
agent_code
,
agent_tk
in
hub
.
agent_toolkits
.
items
():
names
=
[
s
[
"function"
][
"name"
]
for
s
in
agent_tk
.
get_json_schemas
()]
names
=
[
s
[
"function"
][
"name"
]
for
s
in
agent_tk
.
get_json_schemas
()]
assert
"read_file"
in
names
,
f
"read_file missing from {agent_code} toolkit"
assert
"read_file"
in
names
,
f
"read_file missing from {agent_code} toolkit"
db
.
close
()
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