feat(agent-v1.1): 第四阶段 —— 幻觉检测 + 兼容降级 + 包导入导出界面 + 文档(v2.0.47)

按需求 v1.1 把最后三项补齐,然后发版。

## 幻觉调用检测(需求 3.7)

模型很容易在"该记东西"的时候只在正文里说一句「我记住了」——
用户当场看不出来(那句话说得太自然了),等到下次发现它完全不记得,
信任就没了。而"打算记"和"真的记了"在正文里看不出区别,只能由程序
比对「说了什么」和「做了什么」。

三个条件**同时**满足才算:
  ① 正文里有"我记住了"这类断言
  ② 这一轮没有任何工具调用
  ③ 工具是**可用的**

第③条最容易被忽略:Python 工具整个关掉时模型想调也调不了,
那时警告它"没调用工具"是冤枉它,而且警告会一直挂着,用户会以为坏了。

判宽比判窄更糟 —— 误伤会让用户看到莫名其妙的警告,几次之后他就不看
那个警示了(比没有还糟)。所以只收明确句式,`我记得 Python 的字典是有序的`
这种不报。界面在正文**下面**挂一条黄色警示(不塞进正文:那是系统批注,
不是 AI 说的话)。

## 兼容降级(需求 3.3)

本地小模型、老网关很多不支持 `tools` 参数(轻则忽略、重则 400),
而记忆/情绪**全靠工具** —— 不降级的话用户换上这类模型会发现
"记忆功能突然全废了",还看不出原因。

做法:模型列表项加一个「不支持工具调用」开关,打开后不传 tools、
改成在提示词里约定正文内的调用格式(```doubao-call 代码块 + JSON),
内核解析 → 执行 → **从正文里剥掉**,执行记录照常发 tool_call/tool_result
事件 —— 所以界面上的工具痕迹、幻觉检测这些下游逻辑一行都不用改。

★ 做成**用户手动打的标记**而不是自动探测:各家"不支持"的报错方式
五花八门,猜错的代价是把一个本来能用的模型降级掉,那比不降级更糟。

解析不了的块**原样留在正文里**:与其默默删掉(用户永远不知道它想干什么),
不如让他看见"它写了一段系统没认出来的东西" —— 那说明模型该换了。

## 包导入导出界面(需求 2.5)

- `AgentsScreen` 顶栏加「导入」(zip → base64 → 内核解包)。
  不走 Kotlin 解压是因为安卓的 `ZipInputStream` 读不出这类 zip
  (Termux bootstrap 那个坑),而内核的 Python `zipfile` 没问题。
- 编辑界面底部加「导出这个智能体(.zip)」,并写明**包里只有**
  名字/介绍/提示词/外观 —— 模型、世界观、限额不进包,更没有 API Key。

## 文档

新增 `docs/智能体系统.md`:需求项 → 文件对照、数据分界(为什么一半
SQLite 一半 JSON)、三个容易踩的地方、包格式、接口一览、验证方法、
已知限制。README 加 §3.14 摘要。

## 验证

- `scripts/probe-degraded.py`(新增):幻觉检测的**误伤**和**漏判**两头都钉
  ("我记得 Python 的字典是有序的"不许报)、三个条件缺一不可、
  降级调用的解析/执行/剥离/坏 JSON/未知工具/工具抛错/pinned 保护。
- `scripts/probe-agent-system.py`:12 节 70+ 项仍全绿。
- 装机回归:内核正常启动、选择界面四层叠加与默认回退完好。
This commit is contained in:
l
2026-10-16 13:34:15 +08:00
parent a6840f383e
commit d557dbd2e3
12 changed files with 727 additions and 12 deletions

142
scripts/probe-degraded.py Normal file
View File

@@ -0,0 +1,142 @@
"""幻觉调用检测 + 兼容降级的探针(需求 3.3 / 3.7)。
这两件事都是**纯函数**,但都容易"看起来对、实际不对":
· 幻觉检测判宽了 → 用户老看到莫名其妙的警告,几次之后就不看了(比没有还糟)
· 幻觉检测判窄了 → 该提醒的不提醒,等于没做
· 降级解析多剥一块 → 把模型的正常回答吃掉
· 降级解析少剥一块 → 用户看到一坨 JSON
所以逐条钉住。用法:`python scripts/probe-degraded.py`
"""
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, ".."))
DATA = tempfile.mkdtemp(prefix="doubao-degraded-")
os.environ["DOUBAO_DATA"] = DATA
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_loop as A # noqa: E402
import agentdb # noqa: E402
def main():
print("\n=== 1. 幻觉检测:该报的报 ===")
for text in (
"好的,我记住了!",
"已经记住啦",
"我记下了,下次不会再问",
"已经记到记忆里了",
"这个我把它记下来了",
"OK,已经帮你记好了",
):
check(f"「{text}」→ 报警", A.detects_memory_claim(text))
print("\n=== 2. 幻觉检测:**不该**报的别报(误伤比漏判更糟)===")
for text in (
"这段代码会返回 3",
"我记得 Python 的字典是有序的", # 是"我记得"但不是"我记住了"
"你可以把它记在笔记里", # 是让**用户**记
"好的,我明白了",
"计算结果:42",
"我已经把文件读完了", # 「已经…了」但不是记忆
):
check(f"「{text}」→ 不报", not A.detects_memory_claim(text))
print("\n=== 3. 三个条件缺一不可 ===")
check("说了 + 没调工具 + 工具可用 → 报", A.check_hallucinated_memory("我记住了", 0, True))
check("说了 + **调了**工具 → 不报", not A.check_hallucinated_memory("我记住了", 1, True))
check("说了 + 调了 3 个 → 不报", not A.check_hallucinated_memory("我记住了", 3, True))
# ★ 工具整个关掉时不能报:模型想调也调不了,警告会一直挂着
check("说了 + 工具**被关** → 不报", not A.check_hallucinated_memory("我记住了", 0, False))
check("没说什么 → 不报", not A.check_hallucinated_memory("今天天气不错", 0, True))
print("\n=== 4. 降级调用:解析 + 执行 + 剥离 ===")
a1 = __import__("store").create_agent({"name": "降级测试"})
import tools_runtime
tools_runtime.push_context(agentId=a1["id"], conversationId="c_probe")
body = "\n".join([
"好的,我记下来了。",
"",
"```doubao-call",
'{"tool": "memory_add", "args": {"title": "咖啡", "content": "他每天喝美式"}}',
"```",
"",
"还有别的要记的吗?",
])
out, records = A.run_degraded_calls(body, {})
check("调用块被剥掉了", "doubao-call" not in out, out)
check("正文保留完整", "好的,我记下来了。" in out and "还有别的要记的吗?" in out, out)
check("没有留下多余空行", "\n\n\n" not in out, repr(out))
check("记录了一条", len(records) == 1, str(len(records)))
check("记录说成功了", records and records[0]["ok"], str(records))
check("带的工具名对", records and records[0]["name"] == "memory_add")
# ★ 真的写进去了吗 —— 这才是"降级之后记忆还能用"的证据
scope = agentdb.scope_of(a1["id"])
check("**记忆真的落库了**", any("美式" in m["content"] for m in agentdb.memory_list(scope)),
str([m["title"] for m in agentdb.memory_list(scope)]))
print("\n=== 5. 降级调用:坏输入不许吃掉正文、也不许崩 ===")
bad = "前面的正文\n\n```doubao-call\n{这不是 JSON}\n```\n\n后面的正文"
out2, rec2 = A.run_degraded_calls(bad, {})
check("坏 JSON 原样留着(让用户看见)", "{这不是 JSON}" in out2, out2)
check("坏 JSON 不产生执行记录", not rec2, str(rec2))
check("正文没被吃掉", "前面的正文" in out2 and "后面的正文" in out2)
unknown = '```doubao-call\n{"tool": "没这个工具", "args": {}}\n```'
out3, rec3 = A.run_degraded_calls(unknown, {})
check("不认识的工具:剥掉但记失败", "doubao-call" not in out3 and rec3 and not rec3[0]["ok"])
check("失败原因写得清楚", rec3 and "没有这个工具" in rec3[0]["error"], str(rec3))
# 工具自己抛错(pinned 的保护)也不能让整轮回答失败
item = agentdb.memory_add(scope, "锁住的", "不许改", author_agent=a1["id"])
agentdb.memory_set_pinned(item["id"], True)
pinned = '```doubao-call\n{"tool": "memory_forget", "args": {"id": "%s"}}\n```' % item["id"]
out4, rec4 = A.run_degraded_calls(pinned, {})
check("工具抛错:剥掉 + 记失败", "doubao-call" not in out4 and rec4 and not rec4[0]["ok"])
check("失败原因带上了工具的原话", rec4 and "必须保留" in rec4[0]["error"], str(rec4))
check("pinned 那条**没被删掉**", agentdb.memory_get(item["id"]) is not None)
print("\n=== 6. 没有调用块时应当原样返回 ===")
plain = "就是一段普通的回答,没有代码块。"
out5, rec5 = A.run_degraded_calls(plain, {})
check("正文不变", out5 == plain, out5)
check("没有记录", not rec5)
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)