内核一直是对的:speech.voice_for() 有'智能体 > 全局'的覆盖, /api/tts 和 /api/tts/stream 都收 agentId。 漏的是界面:client.speak(text) 只传正文,内核拿不到人就永远用全局音色 —— 用户在智能体编辑页选的音色配了等于没配。 · SpeechController 加 agentId: () -> String(lambda,切换智能体要跟着变) · KernelClient.speak / streamTts 加 agentId 参数 · ChatScreen 的 remember 里传 vm.state.settings.activeAgentId · 流式那条(自动朗读/长句)漏的是同一处,一起补 探针新增 16 节 4 项:界面侧没法测(Kotlin),所以钉**契约** —— 只要 agentId 传进来音色就必须跟着换、没配的回落全局。
493 lines
28 KiB
Python
493 lines
28 KiB
Python
"""智能体系统(需求 v1.1)的端到端探针 —— 不装机就能验整条链路。
|
||
|
||
## 怎么做到的
|
||
|
||
内核的存储层是**无状态**的(路径全靠 `paths.get()` 从数据目录推),
|
||
所以只要把 `DOUBAO_DATA` 指到一个临时目录,就能在一个进程里把
|
||
"建智能体 → 记东西 → 检索 → 拼提示词 → 导包 → 再导入"整条链路跑一遍。
|
||
|
||
比装机验证快得多,而且**能断言具体字段**(装机只能截图看个大概)。
|
||
|
||
## 覆盖
|
||
|
||
1. 建智能体拿到的是 UUID(需求附录 A)
|
||
2. 记忆增删改查 + 检索
|
||
3. pinned 保护(AI 改不动)
|
||
4. 情绪读写
|
||
5. Token 统计(按模型分桶、输入输出分开)
|
||
6. 世界观 + **共享记忆**(两个智能体共用一个空间)
|
||
7. 写入限权(只能删自己写的)
|
||
8. system prompt 注入(附录 C 的五段都在、空段被删掉)
|
||
9. 智能体包导出 → 导入(导入两次 = 两个独立实体)
|
||
10. 记忆导出/导入(合并按标题去重)
|
||
11. 资源 CRUD(世界观 / 模型列表 / Skill)
|
||
|
||
用法:
|
||
python scripts/probe-agent-system.py
|
||
"""
|
||
import io
|
||
import json
|
||
import os
|
||
import shutil
|
||
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, ".."))
|
||
KERNEL = os.path.join(REPO, "android", "kernel")
|
||
|
||
# ★ 必须在 import 内核之前设好:paths.get() 是**懒加载 + 缓存**的
|
||
DATA = tempfile.mkdtemp(prefix="doubao-agent-probe-")
|
||
os.environ["DOUBAO_DATA"] = DATA
|
||
sys.path.insert(0, KERNEL)
|
||
|
||
fails = []
|
||
|
||
|
||
def check(label, cond, detail=""):
|
||
if cond:
|
||
print(f" ✓ {label}")
|
||
else:
|
||
fails.append(label)
|
||
print(f" ✗ {label} {detail}")
|
||
|
||
|
||
def section(title):
|
||
print(f"\n=== {title} ===")
|
||
|
||
|
||
import agent_context # noqa: E402
|
||
import agent_tools # noqa: E402
|
||
import agentdb # noqa: E402
|
||
import store # noqa: E402
|
||
|
||
|
||
class FakeHandler:
|
||
"""冒充 app.py 的 Handler:只要 send_json / read_json_body 两个方法"""
|
||
|
||
def __init__(self):
|
||
self.status = 200
|
||
self.payload = None
|
||
|
||
def send_json(self, code, payload):
|
||
self.status = code
|
||
self.payload = payload
|
||
|
||
def read_json_body(self, *a, **k):
|
||
return self._body
|
||
|
||
def call(self, pathname, method, body=None):
|
||
body = body or {}
|
||
self._body = body
|
||
import agent_api
|
||
|
||
self.status, self.payload = 200, None
|
||
# ★ 内核从 `handler.path` 里读 query(`?space=own`),
|
||
# 所以这里必须把带 query 的路径原样塞回去
|
||
self.path = pathname
|
||
agent_api.handle(self, pathname.split('?')[0], method)
|
||
return self.payload or {}
|
||
|
||
|
||
def main():
|
||
print(f"临时数据目录:{DATA}")
|
||
h = FakeHandler()
|
||
|
||
# ---------------------------------------------------------------- 1
|
||
section("1. 智能体:UUID 主键 + 扩展字段")
|
||
a1 = store.create_agent({"name": "玄辰", "description": "仙门大师兄", "systemPrompt": "你是玄辰。"})
|
||
check("新建的 id 是 UUID", len(a1["id"]) == 36 and a1["id"].count("-") == 4, a1["id"])
|
||
check("description 存下来了", a1.get("description") == "仙门大师兄")
|
||
a1 = store.update_agent(a1["id"], {"tokenLimit": 5000, "emotionEnabled": True, "skillIds": []}) or a1
|
||
check("tokenLimit 存成数字", a1.get("tokenLimit") == 5000, repr(a1.get("tokenLimit")))
|
||
check("emotionEnabled 是布尔", a1.get("emotionEnabled") is True)
|
||
a2 = store.create_agent({"name": "仙辰"})
|
||
check("两个智能体 id 不同", a1["id"] != a2["id"])
|
||
# 内置的还在、短 id 没被动过
|
||
check("内置智能体保留了短 id", any(x["id"] == "a_doubao" for x in store.list_agents()))
|
||
|
||
# ---------------------------------------------------------------- 2
|
||
section("2. 记忆:增删改查 + 检索")
|
||
scope = agentdb.scope_of(a1["id"])
|
||
m1 = agentdb.memory_add(scope, "用户的名字", "他叫小林", author_agent=a1["id"])
|
||
m2 = agentdb.memory_add(scope, "喝咖啡", "每天早上喝一杯美式", author_agent=a1["id"])
|
||
check("加了两条", len(agentdb.memory_list(scope)) == 2)
|
||
check("检索命中正文", len(agentdb.memory_search(scope, "美式")) == 1)
|
||
check("检索命中标题", len(agentdb.memory_search(scope, "名字")) == 1)
|
||
check("检索无关词不命中", len(agentdb.memory_search(scope, "量子力学")) == 0)
|
||
agentdb.memory_update(m1["id"], content="他叫小林,做前端的")
|
||
check("改正文生效", "前端" in agentdb.memory_get(m1["id"])["content"])
|
||
agentdb.memory_forget(m2["id"])
|
||
check("删掉一条", len(agentdb.memory_list(scope)) == 1)
|
||
|
||
# ---------------------------------------------------------------- 3
|
||
section("3. pinned 保护(AI 改不动)")
|
||
agentdb.memory_set_pinned(m1["id"], True)
|
||
import tools_runtime
|
||
|
||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||
try:
|
||
agent_tools.memory_forget({"id": m1["id"]})
|
||
check("pinned 的删不掉", False, "居然删成功了")
|
||
except ValueError as exc:
|
||
check("pinned 的删不掉", "必须保留" in str(exc), str(exc))
|
||
try:
|
||
agent_tools.memory_update({"id": m1["id"], "content": "改了"})
|
||
check("pinned 的改不动", False, "居然改成功了")
|
||
except ValueError:
|
||
check("pinned 的改不动", True)
|
||
check("pinned 的还在", agentdb.memory_get(m1["id"]) is not None)
|
||
agentdb.memory_set_pinned(m1["id"], False)
|
||
|
||
# ---------------------------------------------------------------- 4
|
||
section("4. 工具:memory_add / emotion_set / get_token_usage")
|
||
r = agent_tools.memory_add({"title": "喜欢猫", "content": "他家有两只猫"})
|
||
check("memory_add 返回 id", bool(r.get("id")))
|
||
r = agent_tools.memory_search({"keyword": "猫"})
|
||
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
|
||
agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"})
|
||
check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"]))
|
||
agentdb.token_add(a1["id"], "doubao-pro", 1200, 800)
|
||
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
|
||
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
|
||
u = agent_tools.get_token_usage({})
|
||
check("总量 = 输入+输出", u["used"] == 1200 + 800 + 300 + 100 + 500 + 200, str(u["used"]))
|
||
check("输入输出分开", u["input"] == 2000 and u["output"] == 1100, f'{u["input"]}/{u["output"]}')
|
||
check("按模型分桶", len(u["byModel"]) == 2, str([m["model"] for m in u["byModel"]]))
|
||
check("剩余额度按限额算", u["remaining"] == 5000 - u["used"], str(u["remaining"]))
|
||
|
||
# ---------------------------------------------------------------- 5
|
||
section("5. 世界观 + 共享记忆")
|
||
wv = store.create_resource("worldviews", {"name": "九霄", "setting": "一个仙侠世界,灵气复苏。"})
|
||
check("世界观有 UUID", len(wv["id"]) == 36)
|
||
store.update_agent(a1["id"], {"worldviewId": wv["id"]})
|
||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
||
a1 = store.get_agent(a1["id"])
|
||
a2 = store.get_agent(a2["id"])
|
||
check("绑定后 scope 变成世界观的", agentdb.scope_of(a1["id"], a1["worldviewId"]).startswith("world:"))
|
||
wscope = agentdb.scope_of(a1["id"], a1["worldviewId"])
|
||
agentdb.memory_add(wscope, "共同约定", "两人都怕师父", author_agent=a1["id"])
|
||
check("共享空间两人都看得到", len(agentdb.memory_list(agentdb.scope_of(a2["id"], a2["worldviewId"]))) == 1)
|
||
|
||
# ---------------------------------------------------------------- 6
|
||
section("6. 写入限权:只能删自己写的")
|
||
tools_runtime.push_context(agentId=a2["id"], conversationId="c_test")
|
||
shared_item = agentdb.memory_list(wscope)[0]
|
||
try:
|
||
agent_tools.memory_forget({"id": shared_item["id"]})
|
||
check("删不了别人写的", False, "居然删成功了")
|
||
except ValueError as exc:
|
||
check("删不了别人写的", "其他智能体" in str(exc), str(exc))
|
||
# 自己写的能删
|
||
mine = agent_tools.memory_add({"title": "仙辰的事", "content": "他喜欢御剑"})
|
||
agent_tools.memory_forget({"id": mine["id"]})
|
||
check("自己的能删", agentdb.memory_get(mine["id"]) is None)
|
||
|
||
# ---------------------------------------------------------------- 7
|
||
section("7. 记忆空间的切换:绑定世界观之后,旧记忆不会「隐身」(复查 4.1)")
|
||
# a1 在第 5 节绑了世界观、第 2 节在私有空间里留过记忆 —— 正是"用户攒了
|
||
# 三个月私有记忆、一绑世界观列表就空了"的那个场景
|
||
active = h.call(f"/api/agents/{a1['id']}/memories", "GET")
|
||
check("当前空间是共享的", active.get("shared") is True)
|
||
check("**告诉界面私有空间还剩几条**", active.get("ownCount", 0) > 0, str(active.get("ownCount")))
|
||
old = h.call(f"/api/agents/{a1['id']}/memories?space=own", "GET")
|
||
check("?space=own 能读到旧私有记忆", old.get("own") is True and len(old.get("memories") or []) > 0,
|
||
str(old.get("error") or len(old.get("memories") or [])))
|
||
check("私有空间标成 own(界面据此说明「这是绑定前的」)", old.get("own") is True)
|
||
check("私有空间里不混入共享条目",
|
||
all("共同约定" != m.get("title") for m in old.get("memories") or []),
|
||
str([m.get("title") for m in old.get("memories") or []]))
|
||
check("共享空间里也不混入私有条目",
|
||
all("用户的名字" != m.get("title") for m in active.get("memories") or []),
|
||
str([m.get("title") for m in active.get("memories") or []]))
|
||
# 没绑世界观时不留 ownCount(否则界面会挂一个永远点不出东西的入口)
|
||
a_plain = store.create_agent({"name": "没绑世界观的"})
|
||
plain = h.call(f"/api/agents/{a_plain['id']}/memories", "GET")
|
||
check("没绑世界观时 ownCount = 0", plain.get("ownCount", 0) == 0, str(plain.get("ownCount")))
|
||
|
||
# ---------------------------------------------------------------- 8
|
||
section("8. system prompt 注入(附录 C)")
|
||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||
agentdb.emotion_set(a2["id"], "有点烦")
|
||
store.update_agent(a2["id"], {"emotionEnabled": True})
|
||
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
||
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
||
agentdb.memory_add(agentdb.scope_of(a1["id"], a1["worldviewId"]),
|
||
"用户的名字", "他叫小林,做前端的", author_agent=a1["id"])
|
||
# 感知开关先关掉,验证"没开就没有同伴情绪段"
|
||
store.update_agent(a1["id"], {"emotionEnabled": False})
|
||
a1 = store.get_agent(a1["id"])
|
||
sk = store.create_resource("skills", {"name": "写作", "content": "写东西要先列大纲。"})
|
||
agentdb.bind_skills(a1["id"], [sk["id"]])
|
||
prompt = agent_context.build_system_prompt(store.read_settings(), a1)
|
||
for tag in ("<skills>", "<worldview>", "<emotion>", "<memory>"):
|
||
check(f"{tag} 段在", tag in prompt)
|
||
check("人设在最前面", prompt.startswith("你是玄辰。"), prompt[:20])
|
||
check("世界观设定进去了", "灵气复苏" in prompt)
|
||
# ★ 共享空间的标题带作者署名(复查报告 5):不署名的后果是
|
||
# 别人写的经历被模型当成自己的过去
|
||
check("记忆进去了(标题+正文)", "用户的名字" in prompt and "前端" in prompt)
|
||
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
|
||
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
|
||
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
|
||
check("顺序:worldview 在 emotion 前", prompt.index("<worldview>") < prompt.index("<emotion>"))
|
||
check("顺序:emotion 在 memory 前", prompt.index("<emotion>") < prompt.index("<memory>"))
|
||
# ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的,
|
||
# AI 不知道有别人,就会把别人写的条目当成自己的经历
|
||
check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:])
|
||
check("但名单里**没有情绪**", "有点烦" not in prompt, prompt[-300:])
|
||
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
|
||
store.update_agent(a1["id"], {"emotionEnabled": True})
|
||
prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
|
||
check("开了感知后有同伴情绪", "<peer_emotions>" in prompt2 and "仙辰-有点烦" in prompt2, prompt2[-200:])
|
||
# 空段要整段删掉
|
||
a3 = store.create_agent({"name": "空白的"})
|
||
p3 = agent_context.build_system_prompt(store.read_settings(), a3)
|
||
check("没记忆时 <memory> 整段没了", "<memory>" not in p3, p3[-120:])
|
||
check("但 <skills> 还在(内置手册)", "<skills>" in p3)
|
||
|
||
# ---------------------------------------------------------------- 8
|
||
section("8. HTTP 接口")
|
||
r = h.call("/api/agents", "GET")
|
||
check("GET /api/agents", r.get("ok") and len(r["agents"]) >= 4)
|
||
r = h.call("/api/agents", "POST", {"name": "接口建的"})
|
||
new_id = (r.get("agent") or {}).get("id")
|
||
check("POST /api/agents", bool(new_id))
|
||
r = h.call(f"/api/agents/{new_id}", "PATCH", {"description": "改过的"})
|
||
check("PATCH 生效", (r.get("agent") or {}).get("description") == "改过的")
|
||
r = h.call("/api/agents/a_doubao", "DELETE")
|
||
check("内置的删不掉", r.get("ok") is False, str(r.get("error")))
|
||
check("内置的还在", store.get_agent("a_doubao") is not None)
|
||
r = h.call(f"/api/agents/{a1['id']}/memories", "GET")
|
||
check("GET 记忆列表", r.get("ok") and r.get("shared") is True)
|
||
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
|
||
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
|
||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"})
|
||
check("PUT 情绪", r.get("emotion") == "挺开心的")
|
||
r = h.call("/api/worldviews", "GET")
|
||
check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1)
|
||
r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8})
|
||
check("POST 模型列表", r.get("ok") and (r.get("item") or {}).get("id"))
|
||
r = h.call("/api/skills", "GET")
|
||
check("GET Skill 列表", r.get("ok") and len(r["items"]) == 1)
|
||
|
||
# ---------------------------------------------------------------- 9
|
||
section("9. 智能体包导出 / 导入")
|
||
r = h.call(f"/api/agents/{a1['id']}/package", "GET")
|
||
check("导出拿到 base64 zip", bool(r.get("data")), str(r.get("error")))
|
||
blob = r.get("data")
|
||
r = h.call("/api/agents/import", "POST", {"data": blob})
|
||
imported = r.get("agent") or {}
|
||
check("导入成功", bool(imported.get("id")), str(r.get("error")))
|
||
check("导入的是**新** UUID(不是原来那个)", imported.get("id") not in (None, a1["id"]))
|
||
check("名字带过来了", imported.get("name") == "玄辰")
|
||
check("提示词带过来了", imported.get("systemPrompt") == "你是玄辰。")
|
||
check("描述带过来了", imported.get("description") == "仙门大师兄")
|
||
check("**模型引用没带过来**(需求 2.5 的边界)", not imported.get("modelId"))
|
||
check("**世界观绑定没带过来**", not imported.get("worldviewId"))
|
||
check("**限额没带过来**", not imported.get("tokenLimit"))
|
||
r2 = h.call("/api/agents/import", "POST", {"data": blob})
|
||
check("同一个包导入两次 = 两个独立实体",
|
||
(r2.get("agent") or {}).get("id") not in (None, imported.get("id"), a1["id"]))
|
||
r = h.call("/api/agents/import", "POST", {"data": "bm90IGEgemlw"})
|
||
check("坏包报错而不是崩", r.get("ok") is False, str(r.get("error")))
|
||
|
||
# ---------------------------------------------------------------- 10
|
||
section("10. 记忆导出 / 导入(合并按标题去重)")
|
||
r = h.call(f"/api/agents/{a1['id']}/memories/export", "GET")
|
||
check("导出 type 正确", r.get("type") == "world-memory", str(r.get("type")))
|
||
check("导出带 version", r.get("version") == 1)
|
||
check("导出带 Emotion", "Emotion" in r)
|
||
check("导出**不含** author_agent",
|
||
all("author_agent" not in m for m in r.get("smartMemory") or []))
|
||
exported = dict(r)
|
||
exported["smartMemory"] = [
|
||
{"title": "新的一条", "content": "这是导入进来的", "pinned": False},
|
||
] + list(exported["smartMemory"])
|
||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"})
|
||
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
|
||
check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r))
|
||
check("合并模式:保留当前情绪", agentdb.emotion_get(a1["id"]) == "挺开心的")
|
||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST",
|
||
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
|
||
"mode": "replace"})
|
||
check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"]))
|
||
|
||
# ---------------------------------------------------------------- 11
|
||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||
entry = store.create_resource("models", {
|
||
"name": "DeepSeek R1", "apiBase": "https://api.deepseek.com/v1",
|
||
"apiKey": "sk-abc", "model": "deepseek-r1-250528", "provider": "deepseek",
|
||
})
|
||
store.update_agent(a1["id"], {"modelId": entry["id"]})
|
||
info = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||
check("地址来自模型列表那一项", info["baseUrl"] == "https://api.deepseek.com/v1", info["baseUrl"])
|
||
check("模型标识也来自它", info["model"] == "deepseek-r1-250528", info["model"])
|
||
check("提供商跟着换", info["provider"] == "deepseek", info["provider"])
|
||
# ★ Key 也必须换:只换 model 不换 Key 必然 401(这是"整组覆盖"的理由)
|
||
check("**Key 也是那一项的**(不是全局的)", info["apiKey"] == "sk-abc", info["apiKey"])
|
||
# 没引用时回落全局
|
||
store.update_agent(a1["id"], {"modelId": ""})
|
||
info2 = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||
check("没引用时回落全局", info2.get("modelEntryId") is None)
|
||
check("回落时不再带那一项的 Key", info2["apiKey"] != "sk-abc")
|
||
|
||
# ---------------------------------------------------------------- 12
|
||
section("12. 资源 CRUD + Skill 导入导出")
|
||
r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"})
|
||
sid = (r.get("item") or {}).get("id")
|
||
r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"})
|
||
check("PATCH skill", (r.get("item") or {}).get("content") == "改过的内容")
|
||
r = h.call(f"/api/skills/{sid}/export", "GET")
|
||
check("导出 skill 是单 JSON", r.get("json") and json.loads(r["json"])["type"] == "agent-skill")
|
||
r = h.call("/api/skills/import", "POST", {"data": json.loads(r["json"])})
|
||
check("导入 skill", (r.get("item") or {}).get("id") not in (None, sid))
|
||
r = h.call(f"/api/skills/{sid}", "DELETE")
|
||
check("删 skill", r.get("deleted") is True)
|
||
|
||
# ---------------------------------------------------------------- 13
|
||
section("13. 世界观的引用列表(谁绑了它)")
|
||
lonely = store.create_resource("worldviews", {"name": "没人用的世界", "setting": "空"})
|
||
r = h.call("/api/worldviews", "GET")
|
||
items = r.get("items") or []
|
||
check("列表每一项都带 agents 字段", items and all("agents" in it for it in items))
|
||
mine = next((it for it in items if it.get("id") == wv["id"]), None)
|
||
check("绑了它的两个智能体都在", mine is not None and len(mine.get("agents") or []) == 2,
|
||
str(mine and mine.get("agents")))
|
||
check("给的是名字而不是只有 id",
|
||
bool(mine) and all(a.get("name") for a in mine.get("agents") or []),
|
||
str(mine and mine.get("agents")))
|
||
empty = next((it for it in items if it.get("id") == lonely["id"]), None)
|
||
check("没人绑的世界观 agents 为空(能看出没人用)",
|
||
empty is not None and empty.get("agents") == [], str(empty and empty.get("agents")))
|
||
# 解绑之后要跟着变(缓存住了的话这里会露馅)
|
||
store.update_agent(a2["id"], {"worldviewId": ""})
|
||
again = next((it for it in (h.call("/api/worldviews", "GET").get("items") or [])
|
||
if it.get("id") == wv["id"]), None)
|
||
check("解绑之后列表跟着少一个", again is not None and len(again.get("agents") or []) == 1,
|
||
str(again and again.get("agents")))
|
||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
||
|
||
# ---------------------------------------------------------------- 14
|
||
section("14. 会话隔离:一个会话属于一个智能体(用户报的「串味」)")
|
||
# 场景:跟「豆包」聊了半天 → 切到「代码搭子」→ 接着聊。
|
||
# 以前 system prompt 换了、历史消息没换,新角色会把上一个角色说过的话
|
||
# 当成自己的经历 —— 用户的原话是"智能体怎么串味了"。
|
||
conv_a = store.create_conversation("A 的对话", agent_id=a1["id"])
|
||
check("新会话记住了主人", (store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"])
|
||
legacy = store.create_conversation("老会话")
|
||
check("不传主人时是空(老数据的样子)",
|
||
not (store.get_conversation(legacy["id"]) or {}).get("agentId"))
|
||
store.set_conversation_agent(legacy["id"], a2["id"])
|
||
check("没主人的老会话能被认领",
|
||
(store.get_conversation(legacy["id"]) or {}).get("agentId") == a2["id"])
|
||
# ★★ 这条是关键:有主人的会话**不许改嫁** —— 改名换姓就等于串味
|
||
store.set_conversation_agent(conv_a["id"], a2["id"])
|
||
check("已经有主人的不会被改嫁(那正是串味的来源)",
|
||
(store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"],
|
||
str((store.get_conversation(conv_a["id"]) or {}).get("agentId")))
|
||
|
||
# ---------------------------------------------------------------- 15
|
||
section("15. 记忆注入窗口 + 置顶保护(本次新增)")
|
||
w = store.create_agent({"name": "窗口测试"})
|
||
sc = agentdb.scope_of(w["id"])
|
||
for i in range(1, 11):
|
||
agentdb.memory_add(sc, f"第{i}条", f"内容{i}", author_agent=w["id"])
|
||
ids = agentdb.memory_list(sc)
|
||
agentdb.memory_set_pinned(ids[0]["id"], True) # 把**最旧**的一条置顶
|
||
# ★ SQLite 里的布尔是 0/1 整数,`is True` 永远是 False(这个坑探针自己踩了)
|
||
check("置顶的排在列表最前", bool(agentdb.memory_list(sc)[0]["pinned"]))
|
||
# 窗口设成 4:置顶的必须在,其余取最近的
|
||
store.write_settings({"memoryWindow": 4})
|
||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||
seg = p[p.find("<memory>"):p.find("</memory>")]
|
||
check("置顶的那条**在**(不受窗口限制)", "第1条" in seg, seg[-200:])
|
||
check("最近的在", "第10条" in seg and "第9条" in seg, seg[-200:])
|
||
check("中间的被裁掉了", "第5条" not in seg, seg[-200:])
|
||
check("裁掉多少写清楚了(告知可检索)", "memory_search" in seg, seg[-200:])
|
||
# 0 = 不限
|
||
store.write_settings({"memoryWindow": 0})
|
||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||
check("窗口 = 0 时全部注入", all(f"第{i}条" in p2 for i in range(1, 11)))
|
||
# 接口把窗口信息带给界面
|
||
mp = h.call(f"/api/agents/{w['id']}/memories", "GET")
|
||
check("界面拿得到窗口/置顶数/实际注入数",
|
||
all(k in mp for k in ("window", "pinnedCount", "injected")), str(sorted(mp)[:8]))
|
||
check("injected 算得对(先恢复窗口=4)",
|
||
(store.write_settings({"memoryWindow": 4}),
|
||
(h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected") == 4)[1],
|
||
str((h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected")))
|
||
|
||
# ---- ★ 可以**多个**置顶(用户明确要求)----
|
||
#
|
||
# 单条置顶是最容易蒙混过关的:只测一条的话,"置顶逻辑写成只能有一个"
|
||
# 也能通过。所以这里标**三条**,而且专挑**最早**的三条 ——
|
||
# 窗口只留最近的话它们本来就该被裁掉,只有置顶真的生效才会留下。
|
||
ids2 = agentdb.memory_list(sc)
|
||
for k in (0, 2, 4):
|
||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||
store.write_settings({"memoryWindow": 5})
|
||
p3 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||
seg3 = p3[p3.find("<memory>"):p3.find("</memory>")]
|
||
check("**多个置顶**都能留(标了三条最早的)",
|
||
all(f"第{i}条" in seg3 for i in (1, 3, 5)), seg3[-260:])
|
||
check("窗口剩下的名额给最近的", "第10条" in seg3, seg3[-260:])
|
||
check("置顶在正文里被标出来", seg3.count("置顶") >= 3, str(seg3.count("置顶")))
|
||
# 置顶比窗口还多的时候:置顶**全部**保留(窗口是给普通记忆设的,
|
||
# 不是用来否决用户明确置顶的东西)
|
||
for k in (6, 8, 9):
|
||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||
store.write_settings({"memoryWindow": 2})
|
||
p4 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||
seg4 = p4[p4.find("<memory>"):p4.find("</memory>")]
|
||
kept = sum(1 for i in range(1, 11) if f"第{i}条" in seg4)
|
||
check("置顶数超过窗口时,置顶的全部保留(6 条)", kept == 6, f"实际 {kept} 条:{seg4[-200:]}")
|
||
store.write_settings({"memoryWindow": 50})
|
||
|
||
# ---------------------------------------------------------------- 16
|
||
section("16. 语音:智能体自己的音色要真的生效(用户报的「语音没生效」)")
|
||
#
|
||
# 内核这边一直是对的(`voice_for` 做"智能体 > 全局"),
|
||
# 真正漏的是**界面朗读时不传 agentId** —— 于是内核拿不到人,
|
||
# 永远用全局那个嗓子,智能体编辑页里选的音色白配。
|
||
# 界面那一侧没法在这里测,所以这里把**契约**钉死:
|
||
# 只要 agentId 传进来,音色必须跟着换。
|
||
import speech
|
||
|
||
a_voice = store.create_agent({"name": "嗓音测试"})
|
||
store.update_agent(a_voice["id"], {"ttsVoice": "my-voice-123", "ttsEngine": "volc"})
|
||
st = store.read_settings()
|
||
merged = speech.voice_for(st, store.get_agent(a_voice["id"]))
|
||
check("智能体的音色覆盖了全局", merged.get("ttsVoice") == "my-voice-123", str(merged.get("ttsVoice")))
|
||
check("引擎也跟着覆盖", merged.get("ttsEngine") == "volc", str(merged.get("ttsEngine")))
|
||
plain = speech.voice_for(st, {})
|
||
check("没配的智能体回落全局", plain.get("ttsVoice") == speech.voice_for(st, {}).get("ttsVoice"))
|
||
# 半配:只设了音色、没设引擎 → 引擎回落,音色用它的
|
||
half = store.create_agent({"name": "半配"})
|
||
store.update_agent(half["id"], {"ttsVoice": "only-voice"})
|
||
m2 = speech.voice_for(st, store.get_agent(half["id"]))
|
||
check("只设音色时引擎回落全局", m2.get("ttsVoice") == "only-voice", str(m2.get("ttsVoice")))
|
||
|
||
# ---------------------------------------------------------------- 汇总
|
||
print()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for f in fails:
|
||
print(" -", f)
|
||
return 1
|
||
print("✅ 全部通过")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
code = main()
|
||
finally:
|
||
shutil.rmtree(DATA, ignore_errors=True)
|
||
sys.exit(code)
|