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 2e85b37e
authored
Jun 12, 2026
by
sunqi02
Committed by
胡悦
Jul 01, 2026
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
refactor: simplify MessageGate to activation recognition, add _handle_chat
1 parent
3aa2b07a
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
42 additions
and
230 deletions
workspace/agent-admin/backend/app/service/message_gate.py
workspace/agent-admin/backend/app/service/message_gate.py
View file @
2e85b37
...
...
@@ -121,56 +121,24 @@ class MessageGate:
buffer
.
clear_pending
()
return
# 步骤 7:调 LLM
分类 + 重写
# 步骤 7:调 LLM
做激活识别(无历史上下文)
pending
=
buffer
.
get_pending
()
if
not
pending
:
logger
.
warning
(
"[MessageGate] session=
%
s buffer 为空,跳过"
,
session_id
)
return
decision
=
await
self
.
_classify_and_rewrite
(
session_id
=
session_id
,
pending
=
pending
,
agent_codes
=
list
(
bot_id_mapping
.
keys
()),
)
decision
=
await
self
.
_classify_and_rewrite
(
pending
=
pending
)
# 步骤 8:根据 intent 分支
if
decision
.
intent
==
"ignore"
:
# 按 msg_id 移除本批次
ids
=
[
m
[
"msg_id"
]
for
m
in
pending
if
"msg_id"
in
m
]
buffer
.
remove_by_msg_ids
(
ids
)
# 清空 intent_session 并持久化
data
=
store
.
get
(
session_id
)
or
{}
data
[
"intent_session"
]
=
""
store
.
set
(
session_id
,
data
)
self
.
session_service
.
save_to_db
(
session_id
)
return
if
decision
.
intent
==
"casual"
:
await
self
.
_handle_casual
(
if
decision
.
intent
==
"chat"
:
await
self
.
_handle_chat
(
session_id
=
session_id
,
room_id
=
room_id
,
user_id
=
user_id
,
decision
=
decision
,
pending
=
pending
,
bot_id_mapping
=
bot_id_mapping
,
)
buffer
.
clear_pending
()
return
if
decision
.
intent
==
"incomplete"
:
await
self
.
_handle_incomplete
(
session_id
=
session_id
,
room_id
=
room_id
,
user_id
=
user_id
,
decision
=
decision
,
pending
=
pending
,
bot_id_mapping
=
bot_id_mapping
,
)
# 不清空 buffer:用户后续补充的消息需要合并
return
# actionable
# pass
await
self
.
_handle_actionable
(
session_id
=
session_id
,
room_id
=
room_id
,
...
...
@@ -183,169 +151,49 @@ class MessageGate:
async
def
_classify_and_rewrite
(
self
,
session_id
:
str
,
pending
:
List
[
Dict
[
str
,
Any
]],
agent_codes
:
Optional
[
List
[
str
]]
=
None
,
)
->
"GateDecision"
:
"""调 LLM 进行意图分类 + query 重写。"""
from
app.infrastructure.session_store
import
SessionStore
store
=
SessionStore
()
# 合并 pending 消息文本:text 类型原文照录,非 text 标记为文件
parts
=
[]
for
m
in
pending
:
mt
=
m
.
get
(
"msg_type"
,
""
)
mc
=
m
.
get
(
"msg_content"
,
""
)
if
mt
==
"text"
and
mc
:
parts
.
append
(
mc
)
elif
mc
:
parts
.
append
(
f
"[文件: {mc}]"
)
merged_text
=
"
\n
"
.
join
(
parts
)
if
parts
else
"(空消息)"
# 加载 KV data
data
=
store
.
get
(
session_id
)
or
{}
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
=
data
.
get
(
"intent_session"
)
if
not
isinstance
(
base_messages
,
list
)
or
not
base_messages
:
base_messages
=
self
.
_build_default_classify_messages
(
agent_codes
=
agent_codes
or
[],
agent_prompts
=
agent_prompts
,
)
# 抽 system(不含 history)
system_msg
=
next
(
(
m
for
m
in
base_messages
if
m
.
get
(
"role"
)
==
"system"
),
None
,
)
if
not
system_msg
:
system_msg
=
{
"role"
:
"system"
,
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
or
[],
agent_prompts
=
agent_prompts
,
),
}
# 拼 intent_session 中的非 system 消息(incomplete 路径追加的追问上下文)
messages
=
[
system_msg
]
for
m
in
base_messages
:
content
=
(
m
.
get
(
"content"
)
or
""
)
.
strip
()
if
m
.
get
(
"role"
)
!=
"system"
and
content
:
messages
.
append
({
"role"
:
m
[
"role"
],
"content"
:
m
.
get
(
"content"
,
""
)})
# 拼 history 成多轮 messages 对
for
h
in
history
:
if
h
.
get
(
"role"
)
in
(
"user"
,
"assistant"
):
messages
.
append
({
"role"
:
h
[
"role"
],
"content"
:
h
.
get
(
"content"
,
""
)})
# 加 user current
user_prompt
=
f
"## 当前用户消息
\n
{merged_text}
\n\n
请按 system 指令输出 JSON。"
messages
.
append
({
"role"
:
"user"
,
"content"
:
user_prompt
})
# 调 LLM
response
=
await
self
.
model
(
messages
=
messages
)
"""调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。
# 解析 JSON
text
=
self
.
_extract_text
(
response
)
logger
.
debug
(
"[MessageGate] LLM raw response type=
%
s, extracted text=
%
s"
,
type
(
response
)
.
__name__
,
text
[:
300
],
Returns:
GateDecision with intent="chat" or "pass"
"""
merged_text
=
self
.
_merge_text_from_pending
(
pending
)
if
not
merged_text
:
return
GateDecision
(
intent
=
"chat"
)
prompt
=
(
"你是助手激活识别器。判断当前消息是否需要AI助手响应。
\n
"
"- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默
\n
"
"- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手
\n
"
"
\n
只输出
\"
chat
\"
或
\"
pass
\"
。
\n
"
"
\n
当前消息:
\n
"
+
merged_text
)
messages
=
[{
"role"
:
"user"
,
"content"
:
prompt
}]
# 写回 intent_session:保留 system + incomplete 追问上下文 + 本次 user_current
# "## 当前用户消息" 前缀的消息是历次 classify 的 user_current,丢弃
intent_session
=
[
system_msg
]
for
m
in
base_messages
:
content
=
(
m
.
get
(
"content"
)
or
""
)
.
strip
()
if
m
.
get
(
"role"
)
!=
"system"
and
"## 当前用户消息"
not
in
content
and
content
:
intent_session
.
append
({
"role"
:
m
[
"role"
],
"content"
:
m
.
get
(
"content"
,
""
)})
# 截断超长 user_prompt,防止 intent_session 列写入超限(VARCHAR 8192)
MAX_USER_PROMPT
=
2000
stored_prompt
=
user_prompt
if
len
(
user_prompt
)
<=
MAX_USER_PROMPT
else
user_prompt
[:
MAX_USER_PROMPT
]
+
"...[已截断]"
intent_session
.
append
({
"role"
:
"user"
,
"content"
:
stored_prompt
})
data
[
"intent_session"
]
=
intent_session
store
.
set
(
session_id
,
data
)
self
.
session_service
.
save_to_db
(
session_id
)
response
=
await
self
.
model
(
messages
=
messages
)
text
=
self
.
_extract_text
(
response
)
.
strip
()
.
lower
()
logger
.
debug
(
"[MessageGate] activation response:
%
s"
,
text
)
return
self
.
_parse_decision_json
(
text
)
def
_build_classify_prompt
(
self
,
agent_codes
:
List
[
str
],
agent_prompts
:
Dict
[
str
,
str
]
)
->
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 助手,负责:
1. 识别用户消息的意图(actionable / casual / incomplete / ignore)
2. 将用户消息重写为完整、明确的指令
## 风格指南
- 保持自然、说人话,不官方
- 简洁,不超过 50 字
- emoji 适度
## 当前会话可用的 Agent 及其职责
{agent_section}
## 消息结构说明
- 以 `## 当前用户消息` 标记的内容为**本轮输入**,是你需要分类和重写的目标
- 其余消息(不含该标记的)是历史上下文,仅供理解对话背景,**不作为本轮输入**
## 判定规则(必须遵守)
分类和重写时,**只依据 `## 当前用户消息` 标记的内容**。
- **actionable**: 任务类型明确 + `## 当前用户消息` 中已提供所需资源 + 可独立执行
- 在已有对话上下文内可完成的任务(追问细节、引用历史结论、修改上一轮输出)也属此类
- **casual**: 打招呼、感谢、确认、闲聊
- **incomplete**: 满足以下任一:
- 任务需要文件/数据等资源但 `## 当前用户消息` 中未提供(根据 Agent 职责判断需要什么)
- 任务类型明确但缺少关键参数(收件人、目标语言等)
- 意图模糊、缺少关键信息
- **ignore**: 纯表情、无意义字符、系统通知
## 追问规范
- reply 必须明确点出缺什么("请提供需要处理的音频文件"、"请补充收件人邮箱")
- 若历史上下文中有相关资源,可在 reply 中反问确认("您是想处理刚才的 xxx.mp3 吗?"),但**不能把历史资源写入 rewritten_query**
## 消息格式说明
- 非 text 消息(文件、图片等)会被标记为 [文件: URL]
- 用户输入的文本消息保持原样
- `## 当前用户消息` 中的 URL 是用户本轮主动提供的,应保留到 rewritten_query
## 输出格式(严格 JSON)
{{
"intent": "actionable|casual|incomplete|ignore",
"rewritten_query": "完整指令(actionable 时必填)。只包含 `## 当前用户消息` 中的内容,不从历史消息中提取链接或文件",
"reply": "回复文本(casual/incomplete 时必填)"
}}
"""
if
text
==
"pass"
:
return
GateDecision
(
intent
=
"pass"
)
return
GateDecision
(
intent
=
"chat"
)
# 兜底默认:chat
def
_build_default_classify_messages
(
async
def
_handle_chat
(
self
,
agent_codes
:
List
[
str
],
agent_prompts
:
Dict
[
str
,
str
],
)
->
List
[
Dict
[
str
,
Any
]]:
"""默认 messages(KV 完全空 / 损坏时用)。"""
return
[
{
"role"
:
"system"
,
"content"
:
self
.
_build_classify_prompt
(
agent_codes
=
agent_codes
,
agent_prompts
=
agent_prompts
)},
{
"role"
:
"user"
,
"content"
:
""
},
]
session_id
:
str
,
pending
:
List
[
Dict
[
str
,
Any
]],
)
->
None
:
"""chat 分支:追加用户消息到 conversation_history,不触发 AgentHub,不发 IM。"""
from
app.service.memory
import
SessionMemory
from
app.infrastructure.session_store
import
SessionStore
store
=
SessionStore
()
mem
=
SessionMemory
(
session_id
,
store
)
for
m
in
pending
:
if
m
.
get
(
"msg_type"
)
==
"text"
and
m
.
get
(
"msg_content"
):
mem
.
add
(
"user"
,
m
[
"msg_content"
])
self
.
session_service
.
save_to_db
(
session_id
)
@staticmethod
def
_extract_text
(
response
:
Any
)
->
str
:
...
...
@@ -372,28 +220,6 @@ class MessageGate:
parts
.
append
(
f
"[文件: {mc}]"
)
return
"
\n
"
.
join
(
parts
)
if
parts
else
""
@staticmethod
def
_parse_decision_json
(
text
:
str
)
->
"GateDecision"
:
"""解析 LLM 返回的 JSON 字符串为 GateDecision。"""
import
json
import
re
# 尝试提取 JSON 块(可能包在 ```json 中)
match
=
re
.
search
(
r"\{.*\}"
,
text
,
re
.
DOTALL
)
if
not
match
:
logger
.
warning
(
"MessageGate LLM 输出无 JSON:
%
s"
,
text
[:
200
])
return
GateDecision
(
intent
=
"ignore"
)
try
:
data
=
json
.
loads
(
match
.
group
(
0
))
return
GateDecision
(
intent
=
data
.
get
(
"intent"
,
"ignore"
),
rewritten_query
=
data
.
get
(
"rewritten_query"
),
reply
=
data
.
get
(
"reply"
),
)
except
json
.
JSONDecodeError
:
logger
.
warning
(
"MessageGate LLM 输出 JSON 解析失败:
%
s"
,
text
[:
200
])
return
GateDecision
(
intent
=
"ignore"
)
async
def
_handle_casual
(
self
,
session_id
:
str
,
...
...
@@ -480,15 +306,8 @@ class MessageGate:
pending
:
List
[
Dict
[
str
,
Any
]],
bot_id_mapping
:
Dict
[
str
,
str
],
)
->
None
:
"""actionable 分支:分发到 AgentHub。"""
rewritten
=
decision
.
rewritten_query
or
""
original
=
self
.
_merge_text_from_pending
(
pending
)
if
rewritten
and
original
and
original
not
in
rewritten
:
query
=
f
"{rewritten}
\n\n
---
\n
{original}"
elif
rewritten
:
query
=
rewritten
else
:
query
=
original
"""pass 分支:分发到 AgentHub。"""
query
=
self
.
_merge_text_from_pending
(
pending
)
if
not
query
:
logger
.
warning
(
"[MessageGate] session=
%
s actionable 但无 query,跳过"
,
session_id
)
...
...
@@ -505,13 +324,6 @@ class MessageGate:
if
url
not
in
query
:
query
=
f
"{query}
\n
{url}"
# 清空 intent_session(AgentHub 内部的 save_to_db 会顺带写库)
from
app.infrastructure.session_store
import
SessionStore
store
=
SessionStore
()
data
=
store
.
get
(
session_id
)
or
{}
data
[
"intent_session"
]
=
""
store
.
set
(
session_id
,
data
)
# 提取 file_url(取第一个非 text 消息的 URL)
file_url
=
None
for
m
in
pending
:
...
...
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