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 a49b026c
authored
Jun 04, 2026
by
sunqi02
Committed by
胡悦
Jul 06, 2026
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat: 增强 MessageGate 的分类和重写逻辑,支持子 agent 的 prompt 注入和状态判断
1 parent
8d8f1799
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
173 additions
and
19 deletions
workspace/agent-admin/backend/app/service/message_gate.py
workspace/agent-admin/backend/tests/test_message_gate.py
workspace/agent-admin/backend/app/service/message_gate.py
View file @
a49b026
...
@@ -212,10 +212,20 @@ class MessageGate:
...
@@ -212,10 +212,20 @@ class MessageGate:
data
=
store
.
get
(
session_id
)
or
{}
data
=
store
.
get
(
session_id
)
or
{}
history
=
(
data
.
get
(
"conversation_history"
)
or
[])[
-
10
:]
history
=
(
data
.
get
(
"conversation_history"
)
or
[])[
-
10
:]
# 构建子 agent 的 prompts(过滤 is_steward=True 的主 agent)
agent_prompts
:
Dict
[
str
,
str
]
=
{}
if
agent_codes
:
for
code
in
agent_codes
:
cfg
=
self
.
agent_hub
.
agents
.
get
(
code
)
if
hasattr
(
self
.
agent_hub
,
"agents"
)
else
None
if
cfg
and
not
getattr
(
cfg
,
"is_steward"
,
False
):
agent_prompts
[
code
]
=
getattr
(
cfg
,
"prompt"
,
""
)
# 取 base_messages(intent_session フィールド,冷恢复或上次写入)
# 取 base_messages(intent_session フィールド,冷恢复或上次写入)
base_messages
=
data
.
get
(
"intent_session"
)
base_messages
=
data
.
get
(
"intent_session"
)
if
not
isinstance
(
base_messages
,
list
)
or
not
base_messages
:
if
not
isinstance
(
base_messages
,
list
)
or
not
base_messages
:
base_messages
=
self
.
_build_default_classify_messages
(
agent_codes
or
[])
base_messages
=
self
.
_build_default_classify_messages
(
agent_codes
=
agent_codes
or
[],
agent_prompts
=
agent_prompts
,
)
# 抽 system(不含 history)
# 抽 system(不含 history)
system_msg
=
next
(
system_msg
=
next
(
...
@@ -225,7 +235,9 @@ class MessageGate:
...
@@ -225,7 +235,9 @@ class MessageGate:
if
not
system_msg
:
if
not
system_msg
:
system_msg
=
{
system_msg
=
{
"role"
:
"system"
,
"role"
:
"system"
,
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
or
[]),
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
or
[],
agent_prompts
=
agent_prompts
,
),
}
}
# 拼 intent_session 中的非 system 消息(incomplete 路径追加的追问上下文)
# 拼 intent_session 中的非 system 消息(incomplete 路径追加的追问上下文)
...
@@ -267,9 +279,20 @@ class MessageGate:
...
@@ -267,9 +279,20 @@ class MessageGate:
return
self
.
_parse_decision_json
(
text
)
return
self
.
_parse_decision_json
(
text
)
def
_build_classify_prompt
(
self
,
agent_codes
:
List
[
str
])
->
str
:
def
_build_classify_prompt
(
"""构造不含 history 段的 system prompt。"""
self
,
agent_codes
:
List
[
str
],
agent_prompts
:
Dict
[
str
,
str
]
agent_text
=
", "
.
join
(
agent_codes
)
if
agent_codes
else
"(未指定)"
)
->
str
:
"""构造不含 history 段的 system prompt,注入子 agent 人设。"""
if
agent_prompts
:
lines
=
[]
for
code
in
agent_codes
:
p
=
agent_prompts
.
get
(
code
)
if
p
:
lines
.
append
(
f
"- {code}: {p}"
)
agent_section
=
"
\n
"
.
join
(
lines
)
if
lines
else
"(未指定任何子 Agent)"
else
:
agent_section
=
"(未指定任何子 Agent)"
return
f
"""你是 MessageGate 助手,负责:
return
f
"""你是 MessageGate 助手,负责:
1. 识别用户消息的意图(actionable / casual / incomplete / ignore)
1. 识别用户消息的意图(actionable / casual / incomplete / ignore)
2. 将用户消息重写为完整、明确的指令
2. 将用户消息重写为完整、明确的指令
...
@@ -279,23 +302,38 @@ class MessageGate:
...
@@ -279,23 +302,38 @@ class MessageGate:
- 简洁,不超过 50 字
- 简洁,不超过 50 字
- emoji 适度
- emoji 适度
## 消息格式说明
## 当前会话可用的 Agent 及其职责
- 用户直接发送的文件/图片会被标记为 [文件: URL] 或 [图片: URL],此时消息内容仅是一个链接,无其他文字
{agent_section}
- 用户输入的文本消息保持原样,即使文本中包含 URL,也属于用户主动表达意图的一部分
## 意图分类
## 消息结构说明
- actionable: 有明确任务意图 + 信息充足(文本消息中含 URL 且意图清晰时,应判为 actionable)
- 以 `## 当前用户消息` 标记的内容为**本轮输入**,是你需要分类和重写的目标
- casual: 打招呼、感谢、确认、闲聊
- 其余消息(不含该标记的)是历史上下文,仅供理解对话背景,**不作为本轮输入**
- incomplete: 仅有 [文件: URL] / [图片: URL] 标记而无意图说明,或意图模糊缺少关键信息
- ignore: 纯表情、无意义字符、系统通知
## 当前会话可用的 Agent
## 判定规则(必须遵守)
{agent_text}
分类和重写时,**只依据 `## 当前用户消息` 标记的内容**。
- **actionable**: 任务类型明确 + `## 当前用户消息` 中已提供所需资源 + 可独立执行
- 在已有对话上下文内可完成的任务(追问细节、引用历史结论、修改上一轮输出)也属此类
- **casual**: 打招呼、感谢、确认、闲聊
- **incomplete**: 满足以下任一:
- 任务需要文件/数据等资源但 `## 当前用户消息` 中未提供(根据 Agent 职责判断需要什么)
- 任务类型明确但缺少关键参数(收件人、目标语言等)
- 意图模糊、缺少关键信息
- **ignore**: 纯表情、无意义字符、系统通知
## 追问规范
- reply 必须明确点出缺什么("请提供需要处理的音频文件"、"请补充收件人邮箱")
- 若历史上下文中有相关资源,可在 reply 中反问确认("您是想处理刚才的 xxx.mp3 吗?"),但**不能把历史资源写入 rewritten_query**
## 消息格式说明
- 用户直接发送的文件/图片会被标记为 [文件: URL] 或 [图片: URL]
- 用户输入的文本消息保持原样
- `## 当前用户消息` 中的 URL 是用户本轮主动提供的,应保留到 rewritten_query
## 输出格式(严格 JSON)
## 输出格式(严格 JSON)
{{
{{
"intent": "actionable|casual|incomplete|ignore",
"intent": "actionable|casual|incomplete|ignore",
"rewritten_query": "完整指令
,必须保留原始消息中的所有 URL(actionable 时必填)
",
"rewritten_query": "完整指令
(actionable 时必填)。只包含 `## 当前用户消息` 中的内容,不从历史消息中提取链接或文件
",
"reply": "回复文本(casual/incomplete 时必填)"
"reply": "回复文本(casual/incomplete 时必填)"
}}
}}
"""
"""
...
@@ -303,10 +341,12 @@ class MessageGate:
...
@@ -303,10 +341,12 @@ class MessageGate:
def
_build_default_classify_messages
(
def
_build_default_classify_messages
(
self
,
self
,
agent_codes
:
List
[
str
],
agent_codes
:
List
[
str
],
agent_prompts
:
Dict
[
str
,
str
],
)
->
List
[
Dict
[
str
,
Any
]]:
)
->
List
[
Dict
[
str
,
Any
]]:
"""默认 messages(KV 完全空 / 损坏时用)。"""
"""默认 messages(KV 完全空 / 损坏时用)。"""
return
[
return
[
{
"role"
:
"system"
,
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
)},
{
"role"
:
"system"
,
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
,
agent_prompts
=
agent_prompts
)},
{
"role"
:
"user"
,
"content"
:
""
},
{
"role"
:
"user"
,
"content"
:
""
},
]
]
...
@@ -436,9 +476,12 @@ class MessageGate:
...
@@ -436,9 +476,12 @@ class MessageGate:
logger
.
warning
(
"[MessageGate] session=
%
s actionable 但无 query,跳过"
,
session_id
)
logger
.
warning
(
"[MessageGate] session=
%
s actionable 但无 query,跳过"
,
session_id
)
return
return
# 安全网:从 pending 原始内容中提取 URL,补齐 rewritten_query 可能丢弃的链接
# 安全网:从 text 消息中提取 URL,补齐 rewritten_query 可能丢弃的链接
# 只补 text 类型(用户主动写的 URL),不补 file/image 类型的历史残留链接
URL_RE
=
re
.
compile
(
r'https?://[^\s<>"{}|\\^`\[\]]+'
)
URL_RE
=
re
.
compile
(
r'https?://[^\s<>"{}|\\^`\[\]]+'
)
for
m
in
pending
:
for
m
in
pending
:
if
m
.
get
(
"msg_type"
)
!=
"text"
:
continue
mc
=
m
.
get
(
"msg_content"
,
""
)
mc
=
m
.
get
(
"msg_content"
,
""
)
for
url
in
URL_RE
.
findall
(
mc
):
for
url
in
URL_RE
.
findall
(
mc
):
if
url
not
in
query
:
if
url
not
in
query
:
...
...
workspace/agent-admin/backend/tests/test_message_gate.py
View file @
a49b026
...
@@ -49,6 +49,7 @@ def message_gate_with_deps():
...
@@ -49,6 +49,7 @@ def message_gate_with_deps():
post_reply_hook
.
execute
=
AsyncMock
()
post_reply_hook
.
execute
=
AsyncMock
()
agent_hub
=
MagicMock
()
agent_hub
=
MagicMock
()
agent_hub
.
process_message
=
AsyncMock
()
agent_hub
.
process_message
=
AsyncMock
()
agent_hub
.
agents
=
{}
# MessageGate._classify_and_rewrite 会读写此属性
# 提供 mock model,避免真实加载 models.json
# 提供 mock model,避免真实加载 models.json
mock_model
=
MagicMock
()
mock_model
=
MagicMock
()
...
@@ -267,4 +268,114 @@ async def test_classify_file_only_as_incomplete(message_gate_with_deps):
...
@@ -267,4 +268,114 @@ async def test_classify_file_only_as_incomplete(message_gate_with_deps):
call_args
=
gate
.
model
.
call_args
call_args
=
gate
.
model
.
call_args
messages
=
call_args
[
1
][
"messages"
]
if
"messages"
in
call_args
[
1
]
else
call_args
[
0
][
0
]
messages
=
call_args
[
1
][
"messages"
]
if
"messages"
in
call_args
[
1
]
else
call_args
[
0
][
0
]
user_content
=
messages
[
1
][
"content"
]
user_content
=
messages
[
1
][
"content"
]
assert
"[文件:"
in
user_content
\ No newline at end of file
\ No newline at end of file
assert
"[文件:"
in
user_content
@pytest.mark.asyncio
async
def
test_classify_task_without_resource_is_incomplete
(
message_gate_with_deps
):
"""纯文字 '帮我整理会议纪要' 无文件 → incomplete(不能复用历史链接)。"""
gate
=
message_gate_with_deps
from
app.config.settings
import
AgentConfig
gate
.
agent_hub
.
agents
=
{
"agent_meeting"
:
AgentConfig
(
name
=
"会议Agent"
,
code
=
"17"
,
prompt
=
"你是广联数科的会议纪要助手,职责包括:音频转写、会议纪要整理。"
,
is_steward
=
False
,
skills
=
[
"meeting_minutes"
],
),
}
fake_response
=
'{"intent": "incomplete", "reply": "请提供需要处理的音频文件"}'
gate
.
model
=
AsyncMock
(
return_value
=
MagicMock
(
content
=
[{
"type"
:
"text"
,
"text"
:
fake_response
}]
))
pending
=
[{
"msg_id"
:
"m1"
,
"msg_type"
:
"text"
,
"msg_content"
:
"帮我整理成会议纪要"
,
"sender_id"
:
"u1"
,
"msg_time"
:
"t"
}]
decision
=
await
gate
.
_classify_and_rewrite
(
session_id
=
"sess_002"
,
pending
=
pending
,
agent_codes
=
[
"agent_meeting"
],
)
assert
decision
.
intent
==
"incomplete"
assert
"音频"
in
(
decision
.
reply
or
""
)
# 验证 system prompt 注入了 agent 职责
call_args
=
gate
.
model
.
call_args
messages
=
call_args
[
1
][
"messages"
]
if
"messages"
in
call_args
[
1
]
else
call_args
[
0
][
0
]
system_content
=
messages
[
0
][
"content"
]
assert
"音频转写"
in
system_content
@pytest.mark.asyncio
async
def
test_classify_actionable_with_resource_present
(
message_gate_with_deps
):
"""有文件+意图 → actionable(文件在文本消息中作为 URL)。"""
gate
=
message_gate_with_deps
from
app.config.settings
import
AgentConfig
gate
.
agent_hub
.
agents
=
{
"agent_meeting"
:
AgentConfig
(
name
=
"会议Agent"
,
code
=
"17"
,
prompt
=
"你是广联数科的会议纪要助手,职责包括:音频转写。"
,
is_steward
=
False
,
skills
=
[
"meeting_minutes"
],
),
}
fake_response
=
'{"intent": "actionable", "rewritten_query": "将音频转文字并整理会议纪要"}'
gate
.
model
=
AsyncMock
(
return_value
=
MagicMock
(
content
=
[{
"type"
:
"text"
,
"text"
:
fake_response
}]
))
pending
=
[
{
"msg_id"
:
"m1"
,
"msg_type"
:
"text"
,
"msg_content"
:
"https://example.com/audio.mp3"
,
"sender_id"
:
"u1"
,
"msg_time"
:
"t"
},
{
"msg_id"
:
"m2"
,
"msg_type"
:
"text"
,
"msg_content"
:
"帮我整理成会议纪要"
,
"sender_id"
:
"u1"
,
"msg_time"
:
"t"
},
]
decision
=
await
gate
.
_classify_and_rewrite
(
session_id
=
"sess_003"
,
pending
=
pending
,
agent_codes
=
[
"agent_meeting"
],
)
assert
decision
.
intent
==
"actionable"
assert
"音频"
in
(
decision
.
rewritten_query
or
""
)
@pytest.mark.asyncio
async
def
test_steward_agent_excluded_from_prompt
(
message_gate_with_deps
):
"""is_steward=True 的主 agent 不注入 system prompt。"""
gate
=
message_gate_with_deps
from
app.config.settings
import
AgentConfig
gate
.
agent_hub
.
agents
=
{
"agent_main"
:
AgentConfig
(
name
=
"管家Agent"
,
code
=
"11"
,
prompt
=
"你是管家,负责协调各岗位Agent。"
,
is_steward
=
True
,
skills
=
[],
),
"agent_meeting"
:
AgentConfig
(
name
=
"会议Agent"
,
code
=
"17"
,
prompt
=
"会议纪要助手,职责:音频转写。"
,
is_steward
=
False
,
skills
=
[
"meeting_minutes"
],
),
}
fake_response
=
'{"intent": "incomplete", "reply": "请提供音频文件"}'
gate
.
model
=
AsyncMock
(
return_value
=
MagicMock
(
content
=
[{
"type"
:
"text"
,
"text"
:
fake_response
}]
))
pending
=
[{
"msg_id"
:
"m1"
,
"msg_type"
:
"text"
,
"msg_content"
:
"帮我整理纪要"
,
"sender_id"
:
"u1"
,
"msg_time"
:
"t"
}]
await
gate
.
_classify_and_rewrite
(
session_id
=
"sess_004"
,
pending
=
pending
,
agent_codes
=
[
"agent_main"
,
"agent_meeting"
],
)
# 验证 system prompt 不含管家 agent 的 prompt
call_args
=
gate
.
model
.
call_args
messages
=
call_args
[
1
][
"messages"
]
if
"messages"
in
call_args
[
1
]
else
call_args
[
0
][
0
]
system_content
=
messages
[
0
][
"content"
]
assert
"音频转写"
in
system_content
# 子 agent 注入
assert
"协调各岗位"
not
in
system_content
# 主 agent 不注入
\ No newline at end of file
\ No newline at end of file
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