按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。 ## 内核 - 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。 **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由): 记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删", 那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、 且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。 - 新增 agent_context.py:按需求附录 C 拼 system prompt (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。 - 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、 memory_suggest_summary、emotion_set、get_token_usage)。 走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。 共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。 - 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、 Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。 app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。 - store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、 三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、 delete_agent 清理绑定关系但**不删记忆**。 - Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头, 以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高) + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住, 附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。 - 会议节点的 system prompt 也改用 agent_context(以前是自己拼的, 同一个智能体在会议里没有记忆/情绪/世界观)。 - doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。 ## 安卓 - AgentSelectScreen:智能体选择界面(需求第二章)—— 左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框), 1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序, 连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。 - AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)—— PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧), SVG 走 WebView(原生解不了)。 - TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、 限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、 pinned 开关、共享记忆提示)。 - Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。 - 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面 (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。 - 需求文档给的两张默认资源图进 res/drawable(2.3MB)。 ## 验证 - 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路 (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、 pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、 20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、 记忆导入的合并去重、资源 CRUD。全绿。 - 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。 ## 还没做(下一阶段) 世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展 (介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、 幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
320 lines
16 KiB
Python
320 lines
16 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
|
||
agent_api.handle(self, pathname, 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. 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)
|
||
check("记忆进去了(标题+正文)", "【用户的名字】" in prompt and "前端" in prompt)
|
||
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>"))
|
||
# 没开感知 → 不该有同伴情绪段
|
||
check("没开感知时没有同伴情绪段", "<peer_emotions>" 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. 资源 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)
|
||
|
||
# ---------------------------------------------------------------- 汇总
|
||
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)
|