"""幻觉调用检测 + 兼容降级的探针(需求 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)