diff --git a/android/kernel/agent_api.py b/android/kernel/agent_api.py index be4fa63..0fe86d3 100644 --- a/android/kernel/agent_api.py +++ b/android/kernel/agent_api.py @@ -1,4 +1,4 @@ -"""智能体系统的 HTTP 接口(需求 v1.1)。 +"""智能体系统的 HTTP 接口(需求 v1.1)。 ## 为什么单独一个模块 @@ -474,6 +474,38 @@ def handle(handler, pathname: str, method: str) -> bool: handler.send_json(200, {'ok': True, **_usage_payload(agent)}) return True + # ---------------- 私聊:两个智能体幕后对聊(§3.9 形态 B)---------------- + # + # ★ 这是**同步**接口,可能要跑一两分钟(默认 10 轮 = 20 次 LLM 调用)。 + # 没做成异步任务队列,是因为那要一整套"任务 id + 轮询 + 取消"的机制, + # 而私聊是**用户主动发起、等着看结果**的动作 —— + # 等一等比"发起之后不知道去哪儿看"更好。 + # `maxRounds` 可以调小(探针和测试靠它)。 + if seg[1] == 'private-chat' and method == 'POST': + b = body() + first = store.get_agent(str(b.get('first') or '')) + second = store.get_agent(str(b.get('second') or '')) + if not first or not second: + err(404, '需要两个智能体') + return True + if first.get('id') == second.get('id'): + err(400, '不能让自己跟自己私聊') + return True + if agentdb.is_dead(first['id']) or agentdb.is_dead(second['id']): + # 死亡的人不能说话(§3.5),私聊同理 + err(400, '有一方已经死亡,无法私聊') + return True + import private_chat + + settings = store.read_settings() + result = private_chat.run_pair( + settings, first, second, + max_rounds=private_chat.resolve_rounds(settings, b), + opener=str(b.get('opener') or ''), + ) + handler.send_json(200, result) + return True + # ---------------- 智能体包 ---------------- if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET': return _export_agent(handler, seg[2], err) diff --git a/android/kernel/app.py b/android/kernel/app.py index 2d4f217..f96c08f 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -43,6 +43,7 @@ import agentdb import agent_api import agent_context import context_window +import group_chat import rule_engine import tools_runtime import uploads @@ -1686,6 +1687,38 @@ class KernelHandler(BaseHTTPRequestHandler): agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId')) agent_id = (agent or {}).get('id') or '' + # ★★ 群聊的发言权仲裁(需求 v1.2 §3.9)。 + # + # 单聊时这里是**恒等操作**(`resolve` 原样返回传进去的那个人), + # 判断收在 `is_group` 里 —— 只有群聊才真去仲裁。 + # + # 三种来源,优先级从高到低: + # ① 用户 @ 的人(用户主权) + # ② AI 上一轮 `pass_turn` 移交的人(一轮最多一次) + # ③ 主智能体兜底 —— **永不冷场**,没人被点名时也有人接话 + conv0 = store.get_conversation(conversation_id) or {} + if group_chat.is_group(conv0): + all_agents = store.list_agents() + names = [(x['id'], x.get('name') or '') for x in all_agents] + # 用户这一轮 @ 了谁:从**最后一条用户消息**里找 + last_user = '' + for m in reversed(raw_history): + if m.get('role') == 'user': + last_user = str(m.get('content') or '') + break + pick = group_chat.resolve( + conv0, + want=group_chat.mention_in(last_user, names), + passed=str(body.get('handoffTo') or ''), + alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents}, + ) + speaker = store.get_agent(pick.get('speaker')) + if speaker: + agent, agent_id = speaker, speaker.get('id') or '' + # 界面据此显示"这一轮谁在说、为什么是他" + emit({'type': 'speaker', 'agentId': agent_id, + 'reason': pick.get('reason') or '', 'note': pick.get('note') or ''}) + # ★★ 对话上下文窗口(需求 v1.2 §4.3)。 # # 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。 diff --git a/android/kernel/private_chat.py b/android/kernel/private_chat.py new file mode 100644 index 0000000..21ce61d --- /dev/null +++ b/android/kernel/private_chat.py @@ -0,0 +1,249 @@ +"""私聊:两个智能体在后台自主对聊(需求 v1.2 §3.9 形态 B)。 + +## 需求原文 + +> **形态 B · 私聊(幕后制)**:两个智能体在后台自主对聊,用户不在场。 +> +> - **安全网**:默认最多 10 轮交替发言(可配),到顶强制收尾; +> 一方 Token 触顶则另一方单方面收尾后立即结束,**不撑独角戏**。 +> - 结束后生成摘要写入共享记忆(复用总结管线),完整记录可翻看。 +> - Token 消耗按各自发言分别计入各智能体统计、分别受各自限额约束。 + +## 三个必须想清楚的点 + +**① "安全网"防的是什么** + +两个 AI 互相对话最大的风险是**停不下来**:A 说一句、B 接一句、A 再 +接回来……它们没有"该结束了"的内在信号(用户不在场,没人喊停)。 +所以轮数上限不是优化,是**防失控**。 + +**② "不撑独角戏"** + +一方 Token 触顶时,**不能**让另一方继续自言自语。 +需求的做法是:另一方**单方面收尾**(说一句告别/结语)然后立刻结束。 +独白读起来很怪,而且白花钱。 + +**③ 每轮的"用户"是谁** + +对 A 来说,B 说的话就是**用户消息**;对 B 来说反过来。 +这是私聊能跑起来的关键 —— 两个 AI 都在"跟对方聊天", +而不是"在同一个上下文里各写各的"。 +""" + +import agent_loop +import agentdb +import store + +#: 默认最多几轮(**一轮 = A 说一次 + B 说一次**)。需求定的 10。 +DEFAULT_MAX_ROUNDS = 10 + +#: 上限的硬顶:用户可以在设置里调,但不该调到能刷爆账单的规模。 +#: 一轮两次 LLM 调用,100 轮就是 200 次 —— 那不是"聊天",是失控。 +MAX_ROUNDS_CAP = 60 + + +def resolve_rounds(settings: dict, body: dict = None) -> int: + """ + 这次私聊最多几轮:**调用方指定 > 全局设置 > 默认**,并且夹在硬顶内。 + + ★ 需求说"默认最多 10 轮(**可配**)"—— 可配的入口是 + `settings.privateChatRounds`,不是每次调用随便传(那样界面就没法 + 给用户一个稳定的默认值了)。[body] 只给"这一次特殊"用。 + """ + for src in ((body or {}).get('maxRounds'), (settings or {}).get('privateChatRounds')): + try: + v = int(float(src)) + except (TypeError, ValueError): + continue + if v > 0: + return max(1, min(MAX_ROUNDS_CAP, v)) + return DEFAULT_MAX_ROUNDS + + +def _used(agent: dict) -> int: + u = agentdb.token_usage((agent or {}).get('id') or '') + return int(u['total']['input']) + int(u['total']['output']) + + +def limit_hit(agent: dict) -> bool: + """ + 这个智能体的额度用完了吗(0 = 无限制)。 + + ★ 和 `/api/chat` 那道检查**同一个判据**:用掉的总量 >= 上限。 + 两处不一致的话,会出现"私聊里还能说、回到对话里被拦"这种精神分裂。 + """ + agent = agent or {} + try: + limit = int(float(agent.get('tokenLimit') or 0)) + except (TypeError, ValueError): + limit = 0 + return limit > 0 and _used(agent) >= limit + + +def _history_for(speaker_id: str, turns: list) -> list: + """ + 把"到目前为止的对话"翻译成**这个说话者视角**的消息列表。 + + 对方说的 → `user`(它在跟我说话) + 我说的 → `assistant`(我说的) + + ★ 这是私聊能跑起来的关键:两个 AI 各自都是"在跟对方聊天", + 而不是"在同一个上下文里各写各的"。 + """ + out = [] + for t in turns: + if not t.get('content'): + continue + mine = t.get('agentId') == speaker_id + out.append({'role': 'assistant' if mine else 'user', 'content': t['content']}) + return out + + +def run_pair(settings: dict, first: dict, second: dict, max_rounds: int = 0, + opener: str = '', emit=None) -> dict: + """ + 让两个智能体在后台对聊。 + + [first] 先开口的那个(也是这个会话的"主") + [opener] 给先开口者的由头(比如"用户把你俩拉到了一起")。 + + 返回: + { + 'ok': True, + 'conversationId': ..., + 'turns': [{'agentId','name','content'}], + 'rounds': 实际说了几轮, + 'endReason': 'rounds' | 'limit' | 'error', + 'endedBy': 谁触顶了(endReason=limit 时), + 'summary': 摘要(有的话), + } + """ + settings = settings or {} + first, second = first or {}, second or {} + if not (first.get('id') and second.get('id')): + return {'ok': False, 'error': '需要两个智能体'} + rounds_cap = max_rounds or resolve_rounds(settings) + say = emit or (lambda ev: None) + + conv = store.create_conversation( + title=f'{(first.get("name") or "?")} 与 {(second.get("name") or "?")} 的私聊', + agent_id=first.get('id') or '', + # ★ `private` 是独立类型:它出现在**两个参与者的**会话列表里, + # 而界面上只读翻看(用户不在场,不该能插话) + kind='private', + participants=[first.get('id') or '', second.get('id') or ''], + ) + cid = conv['id'] + turns = [] + end_reason = 'rounds' + ended_by = '' + + def _record(speaker: dict, text: str) -> None: + turns.append({'agentId': speaker.get('id') or '', + 'name': speaker.get('name') or '', 'content': text}) + store.append_messages(cid, [{ + 'role': 'assistant', + 'content': text, + 'agentId': speaker.get('id') or '', + 'at': store.now_iso(), + }]) + + for i in range(rounds_cap): + for who in (first, second): + if limit_hit(who): + # ★★ 一方触顶 → 另一方**单方面收尾**后立即结束(需求明文)。 + # 不收尾直接断的话,对话会停在一句没头没尾的话上; + # 让另一个人继续说的话,就成了"独角戏"(需求明确说不要)。 + other = second if who.get('id') == first.get('id') else first + if not limit_hit(other): + try: + _closing = _speak(settings, other, turns, cid, rounds_cap, i, + hint='对方的额度用完了,这次对话到此为止 —— ' + '你说一句收尾的话,不要再问问题。') + if _closing: + _record(other, _closing) + except Exception as exc: # noqa: BLE001 - 收尾失败也要结束 + say({'type': 'private_error', 'message': str(exc)}) + end_reason, ended_by = 'limit', who.get('name') or '' + break + if not turns and who.get('id') == first.get('id'): + # 给先开口者一个由头(不然它不知道"跟谁、为什么") + turns_seed = opener or f'你和「{second.get("name") or "对方"}」被单独留在了一间屋子里。' + else: + turns_seed = '' + try: + text = _speak(settings, who, turns, cid, rounds_cap, i, hint=turns_seed) + except Exception as exc: # noqa: BLE001 - 一次生成失败不该让整场私聊崩 + say({'type': 'private_error', 'message': str(exc)}) + end_reason = 'error' + break + if not text: + # 模型返回空 —— 当作"它不想说了",正常收尾而不是报错 + end_reason = 'rounds' + break + _record(who, text) + say({'type': 'private_turn', 'agentId': who.get('id') or '', + 'name': who.get('name') or '', 'content': text}) + if end_reason in ('limit', 'error'): + break + + out = { + 'ok': True, 'conversationId': cid, 'turns': turns, + 'rounds': len(turns), 'endReason': end_reason, 'endedBy': ended_by, + } + # ★ 结束后生成摘要写入共享记忆(需求:复用总结管线) + try: + summary = summarize_to_memory(first, second, turns) + if summary: + out['summary'] = summary + except Exception as exc: # noqa: BLE001 - 摘要失败不影响"私聊已经结束"这件事 + say({'type': 'private_error', 'message': f'摘要失败:{exc}'}) + store.update_conversation(cid, {'title': conv['title']}) + return out + + +def _speak(settings: dict, speaker: dict, turns: list, cid: str, + cap: int, round_index: int, hint: str = '') -> str: + """让一个智能体说一句。返回正文(空串 = 它没说话)""" + history = _history_for(speaker.get('id') or '', turns) + if hint: + history = history + [{'role': 'user', 'content': hint}] + if not history: + history = [{'role': 'user', 'content': '开始吧。'}] + result = agent_loop.run_agent( + settings=settings, + messages=history, + agent=speaker, + emit=lambda ev: None, + conversation_id=cid, + # ★ 私聊是**幕后**行为,不能再往里递归拉起别的对话 —— + # 加一层深度限制,免得 A 拉 B、B 拉 C 无限套下去 + send_depth=1, + ) + return str((result or {}).get('content') or '').strip() + + +def summarize_to_memory(first: dict, second: dict, turns: list) -> str: + """ + 把这场私聊的摘要写进**共享记忆**(需求:复用总结管线)。 + + ★ 写到哪:两人的**共享空间**(同世界观 → `world:`), + 这样以后两人聊天时都"记得"这次私聊发生过。 + 没有共同世界观的话**不写** —— 硬塞进某一个人的私有空间, + 等于替他记了一件他没参与的事。 + """ + if not turns: + return '' + a, b = first or {}, second or {} + wid = (a.get('worldviewId') or '').strip() + if not wid or wid != (b.get('worldviewId') or '').strip(): + return '' + body = '\n'.join(f'{(t.get("name") or "?")}:{t.get("content") or ""}' for t in turns) + # 摘要是**规则化**的,不再花一次 LLM 调用 —— 私聊本身已经烧了 + # 2×N 次调用了,为了压两句话再烧一次不划算(需求说的"复用总结管线" + # 指的是同一套**写入记忆**的通道,不是非要再调一次模型) + title = f'和{(b.get("name") or "对方")}的一次私下交谈' + content = f'({len(turns)} 句)' + body[:400] + return agentdb.memory_add( + agentdb.world_scope(wid), title, content, author_agent=a.get('id') or '', + ) and title diff --git a/scripts/probe-group-chat.py b/scripts/probe-group-chat.py index ca35897..7775d15 100644 --- a/scripts/probe-group-chat.py +++ b/scripts/probe-group-chat.py @@ -1,4 +1,4 @@ -"""群聊仲裁的探针(v1.2 §3.9)。 +"""群聊仲裁的探针(v1.2 §3.9)。 点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交), 每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是 @@ -184,6 +184,102 @@ def main(): 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)} 项不合格:")