diff --git a/README.md b/README.md index 9f5752c..b870d7f 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,63 @@ mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权 它们的时长取决于你什么时候点,给上限等于"你想久了 AI 就自己编"。 > 想让 AI 别等太久?把「AI 提问等多久」填个有限值就行。但**不建议**: -> 你去忙一会儿回来,AI 已经按自己猜的答案往下写了,而它并不知道自己在猜。 +> 你去忙一会儿回来,AI 已经按自己猜的答案往下跑了,而它并不知道自己在猜。 + +--- + +### 3.14 智能体系统(记忆 / 情绪 / Token / 世界观 / 技能 / 多模型) + +按《智能体系统需求文档 v1.1》实现。**详细文档在 +[`docs/智能体系统.md`](docs/智能体系统.md)**(需求项 → 文件对照、数据分界、踩过的坑、 +接口一览),这里只说结论。 + +![选择智能体](docs/screenshots/agent-select.png) + +**选择界面**:左列表 + 右侧四层叠加(背景图 / 主体边框 / 角色图 / 介绍边框), +切换按 0.3s 出 → 0.5s 间隔 → 0.4s 换框 → 0.3s 入的四阶段走(连点立即打断、 +从眼前画面接着走)。圆形「更多」按钮进用量页。缺哪张图就走内置默认, +**最差也是「默认人物 + 默认背景 + 方框边框」**,不会有空白展示区。 + +![资源管理](docs/screenshots/agent-resources.png) + +**六个能力**(都能在界面上单独关掉或不管它): + +| | 一句话 | +|---|---| +| Token | 按智能体独立统计、**按模型分桶**、输入输出分开;能设上限,用满时发起前拦住并附一句告别 | +| 记忆 | 无上限、AI 自己记,**用户能改能删**(兜底);「必须保留」的 AI 改不动 | +| 情绪 | 每个智能体一个当前情绪,写进提示词;**绑同一世界观也不共享**(需求明确要求) | +| 世界观 | 独立资源。绑了它的智能体**共用一份记忆**,但**只能改自己写的**那几条 | +| 技能 | 纯文本手册,按绑定顺序注入;内置那份默认就生效 | +| 多模型 | 全局模型列表 + UUID 引用。引用了就**整组覆盖**(地址/Key/模型一起换) | + +**两处需要解释的设计**: + +1. **数据分界**:记忆/情绪/Token/Skill 绑定进 SQLite(条目无上限、每轮全量读、 + 要检索、要按行改删),其余仍是 JSON(量级小、要人肉可读)。 + 判据写在 `android/kernel/agentdb.py` 文件头,加新数据时先按那张表判一次。 + +2. **幻觉调用检测**:模型很容易在"该记东西"的时候只在正文里说一句"我记住了" + —— 用户当场看不出来,下次发现它完全不记得,信任就没了。所以由程序比对 + 「说了什么」和「做了什么」,对不上就在那条回复下面挂一条警示。 + 判宽比判窄更糟(误伤几次之后用户就不看那个警示了),所以只收明确句式。 + +**验证**(都不需要装机、不需要网络): + +```bash +python scripts/probe-agent-system.py # 12 节 70+ 项:UUID、记忆、限权、注入顺序、 + # 20 多个接口、包的边界、多模型解析 +python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calling 的降级 +``` + +> ⚠️ **改完内核记得跑一次 `py_compile`**:Gradle 不编译 Python +> (Chaquopy 只是把 `.py` 打进 APK),语法错误要等手机上启动内核才炸, +> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸, +> 但它拦的是"打包",不是"你刚改的那一行"。 + +**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 —— +按仓库约定"引擎改了另一端必须跟上",这是欠账。 + --- diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 5eb9873..561ee5d 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,4 +1,4 @@ -plugins { +plugins { id("com.android.application") id("org.jetbrains.kotlin.android") id("org.jetbrains.kotlin.plugin.compose") @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 246 - versionName = "2.0.46" + versionCode = 247 + versionName = "2.0.47" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt index 208c44c..5c60501 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt @@ -1,4 +1,4 @@ -package com.doubao.lynxclone.ui +package com.doubao.lynxclone.ui import android.util.Base64 import androidx.activity.compose.rememberLauncherForActivityResult @@ -25,6 +25,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -102,6 +103,23 @@ fun AgentEditScreen( }.onFailure { vm.showHint("读不出这张图") } } + // 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。 + // ★ 包里**只有**名字/介绍/提示词/外观四件套 —— 模型引用、世界观绑定、限额 + // 一律不进包(需求 2.5 的"包的边界约定"),更不会有 API Key。 + var pendingZip by remember { mutableStateOf(null) } + val saveZip = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("application/zip"), + ) { uri -> + val data = pendingZip + pendingZip = null + if (uri != null && data != null) { + runCatching { + ctx.contentResolver.openOutputStream(uri) + ?.use { it.write(Base64.decode(data, Base64.DEFAULT)) } + }.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") } + } + } + FullScreen( title = if (isNew) "新建智能体" else "编辑智能体", subtitle = if (isNew) "保存后可以加外观图片" else draft.name, @@ -296,9 +314,31 @@ fun AgentEditScreen( ) } - /* ---------------- 删除 ---------------- */ - if (!isNew && !draft.builtin) { + /* ---------------- 导出 / 删除 ---------------- */ + if (!isNew) { Spacer(Modifier.height(10.dp)) + Column( + Modifier.fillMaxWidth().padding(horizontal = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + RowAction("导出这个智能体(.zip)") { + vm.exportPackage("agents", draft.id) { content, _ -> pendingZip = content } + } + Text( + "包里只有名字、介绍、提示词和外观图片;模型、世界观、限额不进包,更没有 API Key。", + fontSize = 10.sp, + lineHeight = 14.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + if (pendingZip != null) { + LaunchedEffect(pendingZip) { + saveZip.launch("${draft.name.ifBlank { "agent" }}.zip") + } + } + } + if (!isNew && !draft.builtin) { Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) { RowAction("删除这个智能体", danger = true) { vm.deleteAgentFull(draft.id) { onDone() } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt index 0ef8630..04b1ac7 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt @@ -1,4 +1,4 @@ -package com.doubao.lynxclone.ui +package com.doubao.lynxclone.ui import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background @@ -74,10 +74,30 @@ import com.doubao.lynxclone.data.VoiceOption fun AgentsScreen(vm: AppViewModel) { var confirmDelete by remember { mutableStateOf(null) } + // ★ 导入智能体包(需求 2.5):zip → base64 → 内核解包。 + // 不走 Kotlin 解压是因为安卓的 `ZipInputStream` **读不出**这类 zip + // (Termux bootstrap 那个坑,见 TermuxInstaller 的注释), + // 而内核的 Python `zipfile` 没这个问题 —— 少踩一次已知的坑。 + val ctx = androidx.compose.ui.platform.LocalContext.current + val importPackage = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + runCatching { + ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) + }.onSuccess { bytes -> + vm.importPackage("agents", android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP), "") + }.onFailure { vm.showHint("读不出这个文件") } + } + } + val activeId = vm.state.activeAgent?.id.orEmpty() Column(Modifier.fillMaxSize()) { ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) { + TextButton(onClick = { + importPackage.launch(arrayOf("application/zip", "application/octet-stream", "*/*")) + }) { Text("导入", fontSize = 13.sp) } TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) } } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index 1c129b3..e26ee14 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -1,4 +1,4 @@ -package com.doubao.lynxclone.ui +package com.doubao.lynxclone.ui import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf @@ -283,6 +283,7 @@ class AppViewModel(val client: KernelClient) : ViewModel() { apiKey = extra["apiKey"] as? String ?: "", provider = extra["provider"] as? String ?: "", pricePerK = (extra["pricePerK"] as? Double) ?: 0.0, + noTools = (extra["noTools"] as? Boolean) ?: false, ), id, ) diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index 9514f68..3674c42 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -627,6 +627,29 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: } } + // ★ 幻觉调用检测的警示(需求 3.7):它说了"我记住了"但这一轮没调工具。 + // + // 放在正文**下面**而不是塞进正文:这是"系统对这条回复的批注", + // 不是 AI 说的话 —— 混进正文里,用户会以为 AI 自己在自我怀疑。 + if (msg.hallucination) { + Spacer(Modifier.height(6.dp)) + Row( + Modifier + .clip(RoundedCornerShape(8.dp)) + .background(Color(0x1AF29900)) + .padding(horizontal = 8.dp, vertical = 5.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "⚠ 它说记住了,但这一轮并没有真的调用记忆工具 —— 下次可能就不记得了。", + fontSize = 10.sp, + lineHeight = 14.sp, + color = Color(0xFF8A6100), + modifier = Modifier.widthIn(max = 280.dp), + ) + } + } + if (!msg.pending && msg.content.isNotBlank() && !msg.error) { Spacer(Modifier.height(8.dp)) Row(verticalAlignment = Alignment.CenterVertically) { diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ResourcesScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ResourcesScreen.kt index 5a2fef2..8899fb5 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ResourcesScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ResourcesScreen.kt @@ -73,6 +73,8 @@ private data class Field( val multiline: Boolean = false, val password: Boolean = false, val number: Boolean = false, + /** 开关:值的约定是 `"1"` = 开、`""` = 关(不弹键盘,点一下切换) */ + val toggle: Boolean = false, ) private val WORLD_FIELDS = listOf( @@ -100,6 +102,12 @@ private val MODEL_FIELDS = listOf( Field("apiKey", "API Key", "留空则用全局设置里那个", password = true), Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"), Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true), + Field( + "noTools", "不支持工具调用", + "这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," + + "改成让它在正文里写调用,内核执行完再剥掉 —— 记忆和情绪照常能用。", + toggle = true, + ), ) /** 三张表:kind → (标题、字段、说明、是不是包) */ @@ -322,6 +330,7 @@ private fun ResourceEditScreen( "name" to it.name, "apiBase" to it.apiBase, "model" to it.model, "apiKey" to "", "provider" to it.provider, "pricePerK" to if (it.pricePerK > 0) it.pricePerK.toString() else "", + "noTools" to if (it.noTools) "1" else "", ) } ?: emptyMap() } @@ -366,6 +375,7 @@ private fun ResourceEditScreen( extra["apiKey"] = values["apiKey"].orEmpty() extra["provider"] = values["provider"].orEmpty() extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0 + extra["noTools"] = values["noTools"] == "1" } if (kind.id == "worldviews") extra["image"] = worldImage vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() } @@ -383,6 +393,42 @@ private fun ResourceEditScreen( .padding(14.dp), ) { for (f in kind.fields) { + // ---- 开关型字段:点一下切换,不弹键盘 ---- + if (f.toggle) { + val on = values[f.key] == "1" + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(f.label, fontSize = 13.sp, color = doubaoText()) + if (f.placeholder.isNotBlank()) { + Text( + f.placeholder, + fontSize = 10.sp, + lineHeight = 15.sp, + color = doubaoTextSecondary(), + ) + } + } + Spacer(Modifier.width(10.dp)) + Box( + Modifier + .size(width = 44.dp, height = 26.dp) + .clip(RoundedCornerShape(13.dp)) + .background(if (on) Doubao.Blue else Doubao.Border) + .clickable { values = values + (f.key to if (on) "" else "1") }, + contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart, + ) { + Box( + Modifier + .padding(horizontal = 3.dp) + .size(20.dp) + .clip(RoundedCornerShape(10.dp)) + .background(Color.White), + ) + } + } + Spacer(Modifier.height(12.dp)) + continue + } Text(f.label, fontSize = 13.sp, color = doubaoText()) Spacer(Modifier.height(4.dp)) OutlinedTextField( diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index 30c56b9..c17451e 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -1,4 +1,4 @@ -""" +""" Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。 对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式: @@ -10,6 +10,7 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。 """ import json +import re from typing import Callable, Optional import agent_context @@ -53,6 +54,130 @@ def usage_pair(usage) -> tuple: return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0) +# --------------------------------------------------------------------------- # +# 幻觉调用检测(需求 3.7) +# --------------------------------------------------------------------------- # +# +# 「嘴上说记住了、实际没调工具」是这类有记忆的助手最常见、也最伤信任的毛病: +# 用户当场看不出来(那句"我记住了"说得很自然),下次对话发现它完全不记得, +# 从此就不信这个功能了。 +# +# 而"它打算记"和"它真的记了"在**正文里看不出区别**,只能由程序比对 +# 「说了什么」和「做了什么」。所以这里做一次兜底。 + +#: 「声称记住了」的措辞。 +# ★ 宁可漏判也别误伤:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了 +# (比没有还糟)。所以只收明确说"我记住了"的句式,不收"我会记得的"这种客套。 +_CLAIM_RE = re.compile( + r'我(已经)?(记住|记下|记好)了|已(经)?(记住|记下)|记到(我的)?记忆|' + r'存(进|入)(了)?(我的)?记忆|我把它记|已经帮你记|记在小本本' +) + + +def detects_memory_claim(content: str) -> bool: + """这句话里有没有"我记住了"这类断言""" + return bool(_CLAIM_RE.search(content or '')) + + +def check_hallucinated_memory(content: str, tool_call_count: int, tools_available: bool) -> bool: + """ + 这一轮该不该打「⚠ 声称记忆但未实际调用」的标记(需求 3.7)。 + + ★ [tools_available] 是必须的:如果用户把 Python 工具整个关了, + 模型**想调也调不了**,那时警告它"没调用工具"是冤枉它 —— + 而且警告会一直挂着,用户会以为坏了。 + """ + if not tools_available: + return False + if tool_call_count > 0: + return False + return detects_memory_claim(content) + + +# --------------------------------------------------------------------------- # +# 兼容降级:不支持 function calling 的模型(需求 3.3) +# --------------------------------------------------------------------------- # +# +# 有些模型(本地小模型、老网关)根本不支持 tools 参数 —— 传过去轻则被忽略、 +# 重则直接 400。而"记忆/情绪"这些能力**恰恰靠工具**,没有降级的话, +# 用户换上这类模型之后会发现"记忆功能突然全废了",而且看不出原因。 +# +# 降级做法:不传 tools,改成**在提示词里约定一种正文内的调用格式**, +# 回复回来后由内核解析、执行、并从正文里剥掉。用户看到的还是干净的回答。 +# +# ★ 为什么选"代码块里写 JSON"而不是别的: +# · 模型对"输出 JSON"这件事训练得很充分,比自创的标记语法可靠得多 +# · 代码块有明确的边界,正则能稳稳地切出来;万一没被剥掉, +# 用户看到的也是一段像模像样的 JSON,而不是一堆乱码 + +DEGRADED_HINT = '\n'.join([ + '', + '【工具调用】你**不能直接调用函数**,但需要用到工具时,请在回复里单独写一段:', + '', + '```doubao-call', + '{"tool": "memory_add", "args": {"title": "标题", "content": "内容"}}', + '```', + '', + '可用的工具:memory_add、memory_update、memory_forget、memory_search、' + 'emotion_set、get_token_usage。', + '这一段会被系统执行并从你的回复里**去掉**,用户看不到它。', + '★ 需要记住什么的时候,**必须**写这一段 —— 只在正文里说"我记住了"是没用的,' + '那样你其实什么都没记。', +]) + +_RE_DEGRADED_CALL = re.compile(r'```doubao-call\s*\n(.*?)\n?```', re.S) + + +def run_degraded_calls(content: str, settings: dict) -> tuple: + """ + 执行降级模式写在正文里的结构化调用。 + + 返回 `(剥掉调用块之后的正文, 执行记录)`。 + + ★ 解析不了的块**原样留在正文里**:与其默默删掉(用户永远不知道它想干什么), + 不如让用户看见"它写了一段系统没认出来的东西" —— 那说明模型该换了。 + """ + import agent_tools + + records = [] + + def _one(match): + raw = (match.group(1) or '').strip() + try: + payload = json.loads(raw) + except Exception: # noqa: BLE001 - 解析不了就留着,见 docstring + return match.group(0) + if not isinstance(payload, dict): + return match.group(0) + name = str(payload.get('tool') or '').strip() + args = payload.get('args') if isinstance(payload.get('args'), dict) else {} + entry = agent_tools.AGENT_TOOLS.get(name) + rec = { + 'id': f'degraded_{len(records)}', + 'name': name or '(没写工具名)', + 'args': args, + 'ok': False, + 'result': '', + 'error': '', + } + if entry is None: + rec['error'] = f'没有这个工具:{name}' + else: + try: + out = entry['run'](args) + rec['ok'] = True + rec['result'] = json.dumps(out, ensure_ascii=False)[:2000] + except Exception as exc: # noqa: BLE001 - 工具报错不该让整轮回答失败 + rec['error'] = str(exc) + records.append(rec) + return '' + + stripped = _RE_DEGRADED_CALL.sub(_one, content or '') + # 调用块被剥掉之后往往留下两三行空白,压一压 + stripped = re.sub(r'\n{3,}', '\n\n', stripped).strip() + return stripped, records + + def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str: """工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。""" if isinstance(text, str): @@ -152,6 +277,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic # ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。 if tools_runtime.ui_tools_enabled(settings): system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip() + + # ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。 + # + # 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、 + # 老网关很多不支持 function calling(传 tools 过去轻则被忽略、重则 400)。 + # 不降级的话,用户换上这类模型会发现"记忆功能突然全废了",还看不出原因。 + # + # 判定依据是**模型列表那一项上的开关**(用户在界面上打的标记), + # 不做自动探测:各家"不支持"的报错方式五花八门,猜错的代价是 + # 把一个本来能用的模型降级掉 —— 那比不降级更糟。 + degraded = bool(provider.get('noTools')) + if degraded: + tool_defs = [] + system_prompt = (system_prompt + '\n' + DEGRADED_HINT).strip() thinking_level = settings.get('thinkingLevel') or 'auto' emit({ @@ -243,16 +382,31 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic usage = add_usage(usage, event.get('usage')) if not tool_calls: + # 降级模式(需求 3.3):模型不会 function calling,改成让它把调用 + # **写在正文里**(```doubao-call 代码块),这里执行掉并从正文里剥掉。 + # 执行记录照常发 tool_call / tool_result 事件,所以界面上的工具痕迹、 + # 幻觉检测这些下游逻辑完全不用改。 + final = answer + if degraded: + final, records = run_degraded_calls(answer, settings) + for r in records: + emit({'type': 'tool_call', 'id': r['id'], 'name': r['name'], 'args': r.get('args')}) + emit({ + 'type': 'tool_result', 'id': r['id'], 'name': r['name'], + 'ok': r['ok'], 'result': r['result'], 'error': r['error'], + }) + if records: + tool_call_count += len(records) emit({ 'type': 'done', - 'content': answer, + 'content': final, 'reasoning': reasoning_all, 'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage, }) return { - 'content': answer, 'reasoning': reasoning_all, + 'content': final, 'reasoning': reasoning_all, 'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage, } diff --git a/android/kernel/app.py b/android/kernel/app.py index 296cdc7..349c568 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -1727,6 +1727,14 @@ class KernelHandler(BaseHTTPRequestHandler): 'reasoning': result.get('reasoning', '') or '', 'agentId': agent_id, 'usage': {'input': in_tok, 'output': out_tok}, + # ★ 幻觉调用检测(需求 3.7):嘴上说记住了、实际没调工具。 + # 界面据此显示一个 ⚠ 标记 —— 用户当场看不出来, + # 但下次发现它"完全不记得"时就晚了。 + 'hallucination': agent_loop.check_hallucinated_memory( + result.get('content') or '', + int(result.get('toolCalls') or 0), + bool((settings.get('tools') or {}).get('python', True)), + ), 'at': store.now_iso(), }]) # ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。 diff --git a/android/kernel/store.py b/android/kernel/store.py index 18e77b1..db614ae 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -287,6 +287,8 @@ def provider_info(settings: dict, agent: dict = None) -> dict: # "只覆盖 model 不覆盖 Key"必然 401,见上面的注释 'apiKey': (entry.get('apiKey') or '').strip() or settings.get('apiKey') or '', 'modelEntryId': model_id, + # ★ 兼容降级(需求 3.3):这个模型不支持 tools 参数 + 'noTools': bool(entry.get('noTools')), } provider_key = (agent.get('provider') or '').strip() or settings.get('provider') @@ -1134,6 +1136,9 @@ RESOURCES = { 'key': 'models', 'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'), 'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算 + # ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。 + # 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。 + 'bool': ('noTools',), 'label': '模型', }, # Skill(需求 3.7):纯文本的"工具使用手册" diff --git a/docs/智能体系统.md b/docs/智能体系统.md new file mode 100644 index 0000000..5c5b139 --- /dev/null +++ b/docs/智能体系统.md @@ -0,0 +1,220 @@ +# 智能体系统(需求 v1.1) + +这份文档对应《智能体系统需求文档 v1.1》。它不讲"应该怎么做"(那在需求里), +只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、当时为什么这么选、 +出了问题去哪儿看。 + +--- + +## 1. 需求 → 实现对照 + +| 需求 | 实现位置 | +|---|---| +| 2.1 选择界面(左列表 + 右四层展示) | `ui/AgentSelectScreen.kt` | +| 2.2 资源格式(GIF/SVG/PNG/JPG) | `ui/AssetImage.kt` | +| 2.3 切换动画(1.5s 四阶段) | `ui/AgentSelectScreen.kt` 顶部常量 + `LaunchedEffect` | +| 2.4 圆形「更多」按钮 → 用量 | `ui/AgentSelectScreen.kt` + `ui/TokenUsageScreen.kt` | +| 2.5 智能体包(zip + smartInfo.json) | `kernel/agent_api.py`(`_export_agent` / `_import_agent`) | +| 2.6 默认资源回退 | 内核导入时落定;界面兜最后一级(内置两张图在 `res/drawable/`) | +| 3.1 Token 统计与限额 | `kernel/agentdb.py` + `kernel/app.py`(发起前检查)+ `ui/TokenUsageScreen.kt` | +| 3.2 独立记忆 | `kernel/agentdb.py` + `kernel/agent_tools.py` + `ui/MemoryScreen.kt` | +| 3.3 多模型 | `kernel/store.py: provider_info` + `ui/ResourcesScreen.kt`(模型 Tab) | +| 3.3 兼容降级 | `kernel/agent_loop.py`(`DEGRADED_HINT` / `run_degraded_calls`) | +| 3.4 记忆导入导出 | `kernel/agent_api.py`(`_memory_export` / `_memory_import`) | +| 3.5 情绪系统 | `kernel/agentdb.py`(`emotion_*`)+ 编辑界面开关 | +| 3.6 世界观 | `kernel/store.py: RESOURCES` + `ui/ResourcesScreen.kt` | +| 3.7 Skill 机制 | `kernel/defaults.py: BUILTIN_SKILL` + `kernel/agent_context.py` | +| 3.7 幻觉调用检测 | `kernel/agent_loop.py: check_hallucinated_memory` + 对话页警示条 | +| 4.1 本次对话用量 | `ui/ChatScreen.kt: SessionUsageBar` | +| 附录 A UUID 主键 | `kernel/store.py: create_agent` / `create_resource` | +| 附录 B 六个工具 | `kernel/agent_tools.py: AGENT_TOOLS` | +| 附录 C 提示词模板 | `kernel/agent_context.py` + `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` | +| 附录 D 包格式 | `kernel/agent_api.py` + `docs/智能体系统.md` 第 4 节 | + +--- + +## 2. 数据存在哪(以及为什么) + +这是这个功能里**最需要解释的一个决定**,因为仓库里本来就写着一句 +"为什么用 JSON 而不是 SQLite"(`kernel/store.py` 文件头)。 + +分界线是**数据的形状**,不是"新旧": + +| 存哪 | 什么 | 判据 | +|---|---|---| +| **SQLite**(`agent.db`) | 记忆、情绪、Token 统计、Skill 绑定 | 条目**无上限**(记忆);每轮**全量读取**;要 LIKE 检索;要按行改删 | +| **JSON**(照旧) | 设置、会话、智能体、世界观、模型列表、Skill 内容 | 量级是"几个到几十个";而且**要人肉可读**(你会想直接看自己写的世界观长什么样) | + +`agentdb.py` 的文件头写了同样一段。**加新的数据时先按这张表判一次**, +不要因为"智能体系统用了 SQLite"就把什么都往里塞。 + +### 表结构 + +```sql +memories(id, scope, title, content, pinned, author_agent, created_at) +emotions(agent_id, emotion, updated_at) +token_usage(id, agent_id, model, input, output, created_at) +agent_skills(agent_id, skill_id, ord) +``` + +`scope` 是记忆的归属: + +- `agent:` —— 私有记忆(没绑世界观时) +- `world:` —— 共享记忆(绑了世界观时,同世界观的智能体共用一份) + +**绑定关系一改,scope 就跟着变**,没有"迁移"这一步 —— 记忆留在原地, +只是从这个空间换到那个空间去读。这样"解绑"不会丢东西。 + +--- + +## 3. 三个容易踩的地方 + +### 3.1 模型引用是**整组覆盖**,不是只换 model + +`store.provider_info` 的优先级: + +``` +模型列表那一项(地址 / Key / 模型标识) + ↓ 没引用 +智能体自己的 provider/model/baseUrl + ↓ 留空 +全局设置 + ↓ 还没填 +提供商预设 +``` + +**为什么整组覆盖**:只覆盖 `model` 而 `apiKey` 还用全局的,必然出现 +"选了 DeepSeek 的模型、拿方舟的 Key 去调" → 401。 +而模型列表存在的意义就是"配一次到处用、改 Key 只改一处"。 + +⚠️ 这里曾经有过一个**假功能**:界面能选、字段能存,但 `provider_info` +根本不看 `modelId` —— 引用了照样走全局。界面看起来完全正常, +所以最难发现。`scripts/probe-agent-system.py` 第 11 节专门钉住它。 + +### 3.2 提示词每轮重拼,不缓存 + +`agent_context.build_system_prompt` 在**每一轮**都重新拼一遍。原因很直接: +记忆和情绪**随时会变**,而且 AI 自己就能改它们。缓存住的表现是 +"我明明让它记住了,下一句它又忘了"—— 用户会当成"记忆功能坏了"。 + +顺序固定(附录 C):`{prompt}` → `` → `` → `` → +`` → ``。**空段整段删掉**,不留空标签。 + +### 3.3 幻觉检测的三个条件 + +`check_hallucinated_memory` 只有在**同时**满足时才算: + +1. 正文里说了"我记住了"这类话 +2. 这一轮**没有任何工具调用** +3. **工具是可用的**(用户没把它关掉) + +第 3 条最容易被忽略:Python 工具整个关掉时模型**想调也调不了**, +那时警告它"没调用工具"是冤枉它,而且警告会一直挂着,用户会以为坏了。 + +判宽的代价 > 判窄:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了。 + +--- + +## 4. 包格式(附录 D) + +### 智能体包(`.zip`) + +``` +smartInfo.json # {"name":…, "description":…, "prompt":…, "image":{…}} +assets/… # 四件套图片(front / back / border-main / border-info) +``` + +**包里不进的东西**(需求 2.5 的边界约定): + +- 模型引用、世界观绑定、Token 限额 +- 记忆、情绪、Skill 绑定 +- **API Key**(这是安全底线) + +导入两次 = **两个互相独立的智能体**(不做按名字去重)。重名时界面显示 +`玄辰` / `玄辰(2)`。 + +### 记忆文件(`.json`) + +```json +{ + "type": "agent-memory" | "world-memory", + "version": 1, + "smartMemory": [{"title": …, "content": …, "pinned": false}], + "Emotion": "……" +} +``` + +- 导出**不含** `author_agent`(那是内部字段) +- 导入两种模式:`merge`(默认,按标题去重、保留当前 Emotion)/ `replace` + +--- + +## 5. 怎么验证 + +| 脚本 | 验什么 | +|---|---| +| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 | +| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 | + +两个都**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录, +内核的存储层是无状态的,整条链路就能在一个进程里跑完。 + +**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。 + +### 改内核之后必须做的一件事 + +```bash +python -c "import py_compile,glob; [py_compile.compile(p,doraise=True) for p in glob.glob('android/kernel/*.py')]" +``` + +**Gradle 不编译 Python。** Chaquopy 只是把 `.py` 打进 APK,语法错误要等 +手机上"启动内核"那一刻才炸 —— 而那时整个 App 都不可用。 +`scripts/build-apk.mjs` 里已经加了这道自检,但改完随手跑一下更快。 + +--- + +## 6. 接口一览 + +全部在 `kernel/agent_api.py`,由 `app.py` 的第一条路由接管 +(老的那三个 `/api/agents` 路由**删掉了**,避免两份实现)。 + +``` +GET /api/agents 列表 +POST /api/agents 新建(返回 UUID) +PATCH /api/agents/ 改(全字段,按类型规整) +DELETE /api/agents/ 删(内置的拒绝) +GET /api/agents//package 导出包(base64 zip) +POST /api/agents/import 导入包 +POST /api/agents//asset 设置外观某一槽位 + +GET /api/agents//memories 记忆空间快照 +POST /api/agents//memories 加一条 +GET /api/agents//memories/export 导出 +POST /api/agents//memories/import 导入(merge / replace) +POST /api/agents//memories/summarize AI 整理(一次独立 LLM 调用) +PATCH /api/memories/ 改一条 +DELETE /api/memories/ 删一条 +POST /api/memories//pin 标记「必须保留」 + +GET /api/agents//usage 累计用量(按模型分桶) +POST /api/agents//usage 清零 +GET /api/agents//emotion 读情绪 +PUT /api/agents//emotion 写情绪 +PUT /api/agents//skills 绑定 Skill(按顺序) + +GET/POST /api/worldviews /api/model-entries /api/skills +PATCH/DELETE /api/<资源>/ +GET /api/<资源>//package|export +POST /api/<资源>/import +POST /api/worldviews//asset +``` + +--- + +## 7. 已知限制 + +- **Node 端(Web / exe)还没跟上这一版**:安卓端是完整的,Web 端的智能体 + 系统还是旧的那套(没有记忆/情绪/Token/世界观)。按仓库约定"引擎改了 + 另一端必须跟上",这是欠账。 +- 用量页**不做历史曲线**(需求原话"当前不做曲线"),时间戳只是为将来预留。 +- 情绪是**私有**的:绑同一个世界观也不会共享(需求 3.5 明确要求)。 diff --git a/scripts/probe-degraded.py b/scripts/probe-degraded.py new file mode 100644 index 0000000..3cbbd9f --- /dev/null +++ b/scripts/probe-degraded.py @@ -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)