## 私聊(§3.9 形态 B) 新增 `kernel/private_chat.py` + `POST /api/private-chat`。 **三个必须想清楚的点**(都写进了模块头注释): **① "安全网"防的是什么** 两个 AI 互相对话最大的风险是**停不下来**:A 说一句、B 接一句、A 再接回来…… 它们没有"该结束了"的内在信号(用户不在场,没人喊停)。 所以轮数上限(默认 10,可配)不是优化,是**防失控**。 另加硬顶 60 轮 —— 一轮两次 LLM 调用,100 轮就是 200 次,那不是"聊天"。 **② "不撑独角戏"** 一方 Token 触顶时,**不能**让另一方继续自言自语。需求的做法是: 另一方**单方面收尾**(说一句结语)然后立刻结束。 不收尾直接断的话对话会停在一句没头没尾的话上;继续说的话就成了独白, 读起来怪而且白花钱。 **③ 每轮的"用户"是谁** 对 A 来说 B 说的话就是**用户消息**,对 B 来说反过来。 这是私聊能跑起来的关键 —— 两个 AI 各自都在"跟对方聊天", 而不是"在同一个上下文里各写各的"。探针专门钉了这条视角转换。 **摘要写进共享记忆**:写到两人的**共享空间**(`world:<id>`), 这样以后两人聊天时都"记得"这次私聊。没有共同世界观时**不写** —— 硬塞进某一个人的私有空间,等于替他记了一件他没参与的事。 ## 仲裁接进对话循环 `_perform_chat` 里:群聊时按 `group_chat.resolve()` 换掉 `agent`, 并 emit 一个 `speaker` 事件(界面据此显示"这一轮谁在说、为什么是他")。 单聊时这是**恒等操作**(判断收在 `is_group` 里),所以不用加 if。 ★ 这一步是必须的 —— 不接的话仲裁模块就是个孤岛, 群聊行为跟单聊一模一样("数据接上了但没挂上去"是这个项目反复出现的失败类)。 ## 验证 `probe-group-chat.py` 扩到 11 节:私聊 20+ 项。 ★ 关键的一节是**用 mock 替掉大模型**测编排逻辑: 真跑的话一次测试要烧 20 次 API 调用,而且测的是模型输出而不是我的逻辑。 mock 之后能精确断言"说到 3 轮就停(6 句)"、 "一方触顶时另一方收尾后立刻结束"、"触顶那个没有继续说话"。 ★ 探针自己又错了一次:设 `tokenLimit: 1` 但那个智能体**用量是 0**, 0 >= 1 是 False,根本没触顶。加了"前置条件:b 确实触顶了"这条断言之后, 这种"测试本身没生效"的情况下次会立刻暴露 —— 这是写安全网测试时的 通用教训:**先断言前置条件成立**。 八个探针全绿。
295 lines
15 KiB
Python
295 lines
15 KiB
Python
"""群聊仲裁的探针(v1.2 §3.9)。
|
||
|
||
点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
|
||
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
|
||
"AI 卡住了",而不是"这一轮没人说话")。
|
||
|
||
用法:`python scripts/probe-group-chat.py`
|
||
"""
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-group-")
|
||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||
|
||
fails = []
|
||
|
||
|
||
def check(label, cond, detail=""):
|
||
if cond:
|
||
print(f" ✓ {label}")
|
||
else:
|
||
fails.append(label)
|
||
print(f" ✗ {label} {detail}")
|
||
|
||
|
||
import agent_tools # noqa: E402
|
||
import group_chat as G # noqa: E402
|
||
import store # noqa: E402
|
||
import tools_runtime # noqa: E402
|
||
|
||
|
||
def main():
|
||
world = store.create_resource('worldviews', {'name': '九州'})
|
||
a = store.create_agent({'name': '玄辰'})
|
||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||
a = store.get_agent(a['id'])
|
||
b = store.create_agent({'name': '仙辰'})
|
||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||
b = store.get_agent(b['id'])
|
||
outsider = store.create_agent({'name': '外人'})
|
||
|
||
print("\n=== 1. 会话字段(type / participants)===")
|
||
conv = store.create_conversation('群聊', agent_id=a['id'], kind='group',
|
||
participants=[a['id'], b['id']])
|
||
check("type 存下来了", conv.get('type') == 'group', str(conv.get('type')))
|
||
check("participants 存下来了", len(G.member_ids(conv)) == 2, str(G.member_ids(conv)))
|
||
check("主智能体 = 成员列表第一个", G.host_id(conv) == a['id'], G.host_id(conv))
|
||
old = store.create_conversation('老会话')
|
||
check("老会话默认是 single", (old.get('type') or 'single') == 'single')
|
||
check("非法 type 会被规整成 single",
|
||
store.create_conversation('x', kind='乱写').get('type') == 'single')
|
||
|
||
print("\n=== 2. 仲裁:五种分支 ===")
|
||
names = [(x['id'], x['name']) for x in store.list_agents()]
|
||
# ① 用户 @
|
||
want = G.mention_in('@仙辰 你觉得呢', names)
|
||
check("@ 能解析出人", want == b['id'], str(want))
|
||
r = G.resolve(conv, want=want)
|
||
check("① 被 @ 的人发言", r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||
# ② AI 移交
|
||
r = G.resolve(conv, passed=b['id'], handoffs=0)
|
||
check("② AI 移交的人发言", r['speaker'] == b['id'] and r['reason'] == 'handoff', str(r))
|
||
# ③ 兜底
|
||
r = G.resolve(conv)
|
||
check("③ 没人点名时主智能体兜底(永不冷场)",
|
||
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
|
||
# ④ 被点的人死亡
|
||
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
|
||
check("④ **死亡的人接不了,回主智能体**",
|
||
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
|
||
check("④ 而且说明了原因(界面/日志能看懂)", '死亡' in str(r.get('note')), str(r.get('note')))
|
||
# ⑤ 一轮内重复移交
|
||
r = G.resolve(conv, passed=b['id'], handoffs=G.MAX_HANDOFF_PER_ROUND)
|
||
check("⑤ 一轮内第二次移交被拒(回主智能体)",
|
||
r['speaker'] == a['id'] and r['reason'] == 'handoff_denied', str(r))
|
||
# 用户 @ 不受"一轮一次"约束(那条只管 AI 的移交)
|
||
r = G.resolve(conv, want=b['id'], handoffs=99)
|
||
check("用户 @ 不受「一轮一次」限制(用户主权)", r['speaker'] == b['id'], str(r))
|
||
|
||
print("\n=== 3. @ 的解析细节 ===")
|
||
names2 = [(a['id'], '玄辰'), (b['id'], '玄辰二号')]
|
||
check("有重名前缀时取**最长**匹配(@玄辰二号 不该命中玄辰)",
|
||
G.mention_in('@玄辰二号', names2) == b['id'],
|
||
str(G.mention_in('@玄辰二号', names2)))
|
||
check("精确匹配短的也对", G.mention_in('@玄辰', names2) == a['id'])
|
||
check("没有 @ 时返回空", G.mention_in('随便说点什么', names2) == '')
|
||
check("@ 不在成员里时返回空", G.mention_in('@路人', names2) == '')
|
||
|
||
print("\n=== 4. 成员增删(用户主权)===")
|
||
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
|
||
participants=[a['id']])
|
||
check("能加成员", G.add_member(c2, b['id']) is True)
|
||
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
|
||
check("**主智能体不能被移出**(移掉就没兜底了)", G.remove_member(c2, a['id']) is False)
|
||
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
|
||
# 单聊拉人 → 转成群聊
|
||
single = store.create_conversation('单聊', agent_id=a['id'])
|
||
check("单聊不是群聊", not G.is_group(single))
|
||
G.promote(single, b['id'])
|
||
check("拉人之后转成了群聊", G.is_group(single), str(single.get('type')))
|
||
check("单聊原来那个人还在", a['id'] in G.member_ids(single), str(G.member_ids(single)))
|
||
|
||
print("\n=== 5. invite_agent 工具 ===")
|
||
tools_runtime.push_context(agentId=a['id'], conversationId=single['id'])
|
||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||
check("已在群里时返回 already(不报错)", r.get('already') is True, str(r))
|
||
# 跨世界观
|
||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||
try:
|
||
agent_tools.invite_agent({'target': '外人'})
|
||
check("**跨世界观拉人一律拒绝**", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("**跨世界观拉人一律拒绝**", '世界观' in str(exc), str(exc))
|
||
try:
|
||
agent_tools.invite_agent({'target': '玄辰'})
|
||
check("拉自己被拒", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("拉自己被拒", '自己' in str(exc), str(exc))
|
||
# 需确认模式:不直接拉人,让 AI 去问
|
||
store.update_agent(a['id'], {'inviteMode': 'confirm'})
|
||
a2 = store.get_agent(a['id'])
|
||
tools_runtime.push_context(agentId=a2['id'], conversationId=c2['id'])
|
||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||
check("**需确认模式不直接拉人**", r.get('needConfirm') is True, str(r))
|
||
check("需确认模式下人**没有**进群",
|
||
b['id'] not in G.member_ids(store.get_conversation(c2['id']) or {}),
|
||
str(G.member_ids(store.get_conversation(c2['id']) or {})))
|
||
check("提示 AI 去问用户", '问' in str(r.get('note')), str(r.get('note')))
|
||
# 静默模式:直接拉
|
||
store.update_agent(a['id'], {'inviteMode': 'silent'})
|
||
a3 = store.get_agent(a['id'])
|
||
tools_runtime.push_context(agentId=a3['id'], conversationId=c2['id'])
|
||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||
check("静默模式直接进群", r.get('joined') == '仙辰', str(r))
|
||
check("人真的进群了",
|
||
b['id'] in G.member_ids(store.get_conversation(c2['id']) or {}))
|
||
|
||
print("\n=== 6. pass_turn 工具 ===")
|
||
# ★ 每次都 push 完整上下文 —— `push_context` 是**替换**语义,
|
||
# 只补一个键会把 agentId / conversationId 冲掉(这个坑踩过)
|
||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||
r = agent_tools.pass_turn({'target': '仙辰'})
|
||
check("移交成功", r.get('handed_to') == '仙辰', str(r))
|
||
check("上下文里记了移交标记", tools_runtime.current_context().get('handoffUsed') is True)
|
||
check("也记了交给谁", tools_runtime.current_context().get('handoffTo') == b['id'])
|
||
# 一轮内第二次:拒
|
||
try:
|
||
agent_tools.pass_turn({'target': '仙辰'})
|
||
check("**一轮最多移交一次**", False, "第二次数居然允许了")
|
||
except ValueError as exc:
|
||
check("**一轮最多移交一次**", '已经移交过' in str(exc), str(exc))
|
||
# 死亡目标:拒,而且理由是"死亡"不是"已移交"
|
||
import agentdb
|
||
dead = store.create_agent({'name': '死者'})
|
||
store.update_agent(dead['id'], {'worldviewId': world['id']})
|
||
agentdb.emotion_set(dead['id'], preset='死亡')
|
||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||
try:
|
||
agent_tools.pass_turn({'target': '死者'})
|
||
check("**死亡目标移交无效**", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("**死亡目标移交无效**", '死亡' in str(exc), str(exc))
|
||
check("理由说的是死亡,不是别的", '已经移交过' not in str(exc), str(exc))
|
||
try:
|
||
agent_tools.pass_turn({'target': '玄辰'})
|
||
check("交给自己被拒", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("交给自己被拒", '自己' in str(exc), str(exc))
|
||
|
||
print("\n=== 7. 附录 B 的工具清单齐了吗 ===")
|
||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status',
|
||
'invite_agent', 'pass_turn'):
|
||
check(f"有 {want}", want in agent_tools.AGENT_TOOLS)
|
||
# 附录 B 列了 10 个工具,外加"建议机制"(memory_suggest_summary)= 11
|
||
check("一共 11 个(附录 B 的 10 个 + 建议机制)", len(agent_tools.AGENT_TOOLS) == 11,
|
||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||
|
||
print("\n=== 8. 私聊:轮数解析与额度判据 ===")
|
||
import private_chat as P
|
||
|
||
check("默认 10 轮(需求定的)", P.resolve_rounds({}) == 10, str(P.resolve_rounds({})))
|
||
check("全局设置能改", P.resolve_rounds({'privateChatRounds': 6}) == 6)
|
||
check("本次调用能改(压过全局)",
|
||
P.resolve_rounds({'privateChatRounds': 6}, {'maxRounds': 3}) == 3)
|
||
check("有硬顶(不让人调成刷爆账单的规模)",
|
||
P.resolve_rounds({}, {'maxRounds': 99999}) == P.MAX_ROUNDS_CAP,
|
||
str(P.resolve_rounds({}, {'maxRounds': 99999})))
|
||
check("乱填回落默认", P.resolve_rounds({'privateChatRounds': 'x'}) == 10)
|
||
check("额度为 0 表示无限制", P.limit_hit({'id': a['id'], 'tokenLimit': 0}) is False)
|
||
import agentdb as _db
|
||
|
||
_db.token_add(a['id'], 'm', 100, 50)
|
||
check("没超限额时 false", P.limit_hit({**a, 'tokenLimit': 1000}) is False)
|
||
check("超了才是 true", P.limit_hit({**a, 'tokenLimit': 100}) is True)
|
||
|
||
print("\n=== 9. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
|
||
turns = [
|
||
{'agentId': a['id'], 'name': '玄辰', 'content': '你来了。'},
|
||
{'agentId': b['id'], 'name': '仙辰', 'content': '嗯,路上耽搁了。'},
|
||
]
|
||
ha = P._history_for(a['id'], turns)
|
||
hb = P._history_for(b['id'], turns)
|
||
check("对 A 来说:自己说的是 assistant", ha[0]['role'] == 'assistant', str(ha))
|
||
check("对 A 来说:**对方说的是 user**", ha[1]['role'] == 'user', str(ha))
|
||
check("对 B 来说正好反过来",
|
||
hb[0]['role'] == 'user' and hb[1]['role'] == 'assistant', str(hb))
|
||
|
||
print("\n=== 10. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||
#
|
||
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
|
||
# 两个 AI 互相对话最大的风险就是**停不下来**(用户不在场,没人喊停)。
|
||
#
|
||
# mock 掉真正的大模型调用:这里要测的是**编排逻辑**,不是模型输出。
|
||
# 真跑的话一次测试要烧 20 次 API 调用。
|
||
import agent_loop
|
||
|
||
real_run_agent = agent_loop.run_agent
|
||
|
||
def fake(**kw):
|
||
who = (kw.get('agent') or {}).get('name') or '?'
|
||
fake.calls.append(who)
|
||
return {'content': f'{who} 说了第 {len(fake.calls)} 句'}
|
||
|
||
fake.calls = []
|
||
agent_loop.run_agent = fake
|
||
try:
|
||
r = P.run_pair(store.read_settings(), a, b, max_rounds=3)
|
||
check("跑完了", r.get('ok') is True, str(r.get('error')))
|
||
check("**说到 3 轮就停**(一轮 = A 一次 + B 一次)",
|
||
r.get('rounds') == 6, str(r.get('rounds')))
|
||
check("结束原因标成 rounds", r.get('endReason') == 'rounds', str(r.get('endReason')))
|
||
check("两个人都说了话", set(fake.calls) == {'玄辰', '仙辰'}, str(fake.calls))
|
||
conv2 = store.get_conversation(r['conversationId']) or {}
|
||
check("会话类型是 private", conv2.get('type') == 'private', str(conv2.get('type')))
|
||
check("两个参与者都在", set(conv2.get('participants') or []) == {a['id'], b['id']},
|
||
str(conv2.get('participants')))
|
||
check("完整记录落库(用户能翻看)", len(conv2.get('messages') or []) == 6,
|
||
str(len(conv2.get('messages') or [])))
|
||
check("摘要写进了**共享记忆**", bool(r.get('summary')), str(r.get('summary')))
|
||
shared = _db.memory_list(_db.world_scope(world['id']))
|
||
check("记忆里能查到这条摘要",
|
||
any('私下交谈' in (m.get('title') or '') for m in shared),
|
||
str([m.get('title') for m in shared]))
|
||
|
||
# ★ 一方触顶:另一方**单方面收尾**后立即结束
|
||
#
|
||
# 注意:光设 `tokenLimit: 1` 是不够的 —— 判据是"用掉的总量 >= 上限",
|
||
# 而 b 这时候还没说过话(用量 0),0 >= 1 是 False,根本没触顶。
|
||
# 得让它**真的用过**才算超。
|
||
store.update_agent(b['id'], {'tokenLimit': 1})
|
||
_db.token_add(b['id'], 'm', 100, 50)
|
||
b_limited = store.get_agent(b['id'])
|
||
check("前置条件:b 确实触顶了", P.limit_hit(b_limited) is True, str(b_limited.get('tokenLimit')))
|
||
fake.calls = []
|
||
r2 = P.run_pair(store.read_settings(), a, b_limited, max_rounds=5)
|
||
check("**一方触顶时立刻结束**", r2.get('endReason') == 'limit', str(r2.get('endReason')))
|
||
check("标了是谁触顶的", r2.get('endedBy') == '仙辰', str(r2.get('endedBy')))
|
||
check("**另一方做了收尾**(不是一句话没有就断)",
|
||
len(r2.get('turns') or []) >= 2, str(len(r2.get('turns') or [])))
|
||
check("**没撑独角戏**(触顶那个没继续说话)",
|
||
sum(1 for t in (r2.get('turns') or []) if t.get('name') == '仙辰') <= 1,
|
||
str([t.get('name') for t in r2.get('turns') or []]))
|
||
store.update_agent(b['id'], {'tokenLimit': 0})
|
||
finally:
|
||
agent_loop.run_agent = real_run_agent
|
||
|
||
print("\n=== 11. 私聊的边界 ===")
|
||
check("没有共同世界观时不写记忆(不替人记他没参与的事)",
|
||
P.summarize_to_memory(a, {'id': 'x', 'worldviewId': ''}, turns) == '')
|
||
check("没说话时不写摘要", P.summarize_to_memory(a, b, []) == '')
|
||
check("缺参数时返回错误而不是抛异常",
|
||
P.run_pair(store.read_settings(), {}, {}, max_rounds=1).get('ok') is False)
|
||
|
||
print()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for f in fails:
|
||
print(" -", f)
|
||
return 1
|
||
print("✅ 全部通过")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|