fix(agent): 会话隔离(用户报的'串味')+ 记忆注入窗口与置顶(v2.0.52)
## 串味:会话没做隔离 会话本来就有 agentId 字段,但两处都没用: · 新建会话时从来不填 → 所有会话的主人都空着 · 取历史消息时从来不检查 → 切了智能体还在同一会话里接着聊 于是历史消息是上一个角色说的、system prompt 却是新角色的, 新角色把别人的话当成自己的经历接着聊。 修法:一个会话属于一个智能体。 · 新建时记住主人 · 换人时界面主动换会话(useAgent → newTopic) · 内核兜底:取历史时发现主人不对就另起一个,并发 rebased 事件让界面切 · 老会话(没主人)认领而不是另起,否则历史会话第一次聊天就跳走 · 已有主人的会话不许改嫁 ## 记忆的窗口和置顶(用户选的 A 方案) '无上限 + 每轮全量注入'长期矛盾:几百条时提示词被撑爆, 而且早期的记忆反而把最近的对话上下文挤掉。 · memoryWindow(默认 50,0 = 不限):每轮最多注入多少条 · 置顶的永远注入、排最前,不受窗口限制 · 被裁掉的没丢,memory_search 还能搜到(降级为仅可检索) · 记忆页顶部显示'这一轮会带进去 N / M 条',可就地调整 · 「必须保留」改叫「置顶」 ## 探针 新增 14 节(会话隔离 4 项)和 15 节(窗口与置顶 8 项)。 顺带修掉两个真问题: · set_conversation_agent 绕过内存缓存直接读写文件(会话有缓存) · 探针自己的 pinned is True —— SQLite 布尔是 0/1 整数
This commit is contained in:
@@ -30,8 +30,8 @@ android {
|
|||||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||||
* 改小了会装不上)。
|
* 改小了会装不上)。
|
||||||
*/
|
*/
|
||||||
versionCode = 251
|
versionCode = 252
|
||||||
versionName = "2.0.51"
|
versionName = "2.0.52"
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package com.doubao.lynxclone.ui
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
@@ -271,6 +271,7 @@ fun AppRoot(
|
|||||||
onTogglePin = { _, _ -> },
|
onTogglePin = { _, _ -> },
|
||||||
onSummarize = {},
|
onSummarize = {},
|
||||||
onExport = {},
|
onExport = {},
|
||||||
|
onSetWindow = {},
|
||||||
onImportClick = {},
|
onImportClick = {},
|
||||||
onOpenOwn = {},
|
onOpenOwn = {},
|
||||||
onBackToActive = {},
|
onBackToActive = {},
|
||||||
@@ -324,6 +325,7 @@ fun AppRoot(
|
|||||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||||
onSummarize = { vm.summarizeMemories() },
|
onSummarize = { vm.summarizeMemories() },
|
||||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||||
|
onSetWindow = { vm.setMemoryWindow(it) },
|
||||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
||||||
|
|||||||
@@ -499,6 +499,26 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调**注入窗口**:每轮最多把多少条记忆放进提示词(0 = 不限)。
|
||||||
|
*
|
||||||
|
* ★ 这是全局设置(不是每个智能体一份):它防的是"提示词被记忆撑爆",
|
||||||
|
* 而那是个和上下文长度有关的问题,跟具体哪个角色无关。
|
||||||
|
* 放在记忆页顶部就地调,是因为**你看到"300 条里只进去 50 条"的那一刻
|
||||||
|
* 才是你想改它的时候** —— 让用户去设置页翻三层,他就不改了。
|
||||||
|
*/
|
||||||
|
fun setMemoryWindow(n: Int) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
client.saveSettings(JSONObject().put("memoryWindow", n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
if (memoryAgentId.isNotBlank()) refreshMemories()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun refreshMemories() {
|
fun refreshMemories() {
|
||||||
val id = memoryAgentId
|
val id = memoryAgentId
|
||||||
if (id.isBlank()) return
|
if (id.isBlank()) return
|
||||||
@@ -1027,7 +1047,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
|
|
||||||
fun newTopic() {
|
fun newTopic() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
val conv = runCatching {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
// ★ 新会话记住它属于哪个智能体 —— 会话隔离的依据就是它
|
||||||
|
client.newConversation(agentId = activeAgent?.id.orEmpty())
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
refresh()
|
refresh()
|
||||||
if (conv != null) {
|
if (conv != null) {
|
||||||
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||||
@@ -1154,6 +1179,11 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// ★ 内核说"这个会话不是当前智能体的,我另起了一个"(兜底路径)。
|
||||||
|
// 界面必须跟着切,否则会继续往老会话上追加 —— 还是串味。
|
||||||
|
is StreamEvent.Rebased -> {
|
||||||
|
if (event.conversationId.isNotBlank()) openConversation(event.conversationId)
|
||||||
|
}
|
||||||
is StreamEvent.Failure -> {
|
is StreamEvent.Failure -> {
|
||||||
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
||||||
// 清零 / 调大限额 / 改成无限制。所以单独记一个标记,
|
// 清零 / 调大限额 / 改成无限制。所以单独记一个标记,
|
||||||
@@ -1394,7 +1424,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun useAgent(id: String) {
|
fun useAgent(id: String) {
|
||||||
|
val changed = id != state.settings.activeAgentId
|
||||||
saveSettings(mapOf("activeAgentId" to id))
|
saveSettings(mapOf("activeAgentId" to id))
|
||||||
|
// ★★ 换人就**换会话**(用户报的"串味")。
|
||||||
|
//
|
||||||
|
// 会话是属于某个智能体的:里面的历史消息是**上一个角色**说的。
|
||||||
|
// 只换 system prompt 不换会话的话,新角色会看到一堆"自己说过的话",
|
||||||
|
// 把它们当成自己的经历接着聊 —— 表现就是"智能体串味了"。
|
||||||
|
//
|
||||||
|
// 会话还是空的时候不用换(那是"刚点进来还没聊")。
|
||||||
|
if (changed && messages.isNotEmpty()) newTopic()
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------ 附件 ------------------------------ */
|
/* ------------------------------ 附件 ------------------------------ */
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package com.doubao.lynxclone.ui
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
@@ -30,6 +31,7 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.doubao.lynxclone.data.MemoryItem
|
import com.doubao.lynxclone.data.MemoryItem
|
||||||
@@ -82,6 +84,8 @@ fun MemoryScreen(
|
|||||||
onTogglePin: (String, Boolean) -> Unit,
|
onTogglePin: (String, Boolean) -> Unit,
|
||||||
onSummarize: () -> Unit,
|
onSummarize: () -> Unit,
|
||||||
onExport: () -> Unit,
|
onExport: () -> Unit,
|
||||||
|
/** 调注入窗口(条数,0 = 不限) */
|
||||||
|
onSetWindow: (Int) -> Unit,
|
||||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||||
onImportClick: () -> Unit,
|
onImportClick: () -> Unit,
|
||||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||||
@@ -95,6 +99,9 @@ fun MemoryScreen(
|
|||||||
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
||||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||||
var confirmSummarize by remember { mutableStateOf(false) }
|
var confirmSummarize by remember { mutableStateOf(false) }
|
||||||
|
/** 调注入窗口(输入条数,0 = 不限) */
|
||||||
|
var editWindow by remember { mutableStateOf(false) }
|
||||||
|
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||||
val readingOwn = space?.own == true
|
val readingOwn = space?.own == true
|
||||||
|
|
||||||
FullScreen(
|
FullScreen(
|
||||||
@@ -164,6 +171,49 @@ fun MemoryScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||||
|
if (!readingOwn && !worldMode && space != null) {
|
||||||
|
val total = space.memories.size
|
||||||
|
val win = space.window
|
||||||
|
val injected = space.injected
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||||
|
.clip(RoundedCornerShape(10.dp))
|
||||||
|
.background(doubaoSurface())
|
||||||
|
.clickable { windowDraft = win.toString(); editWindow = true }
|
||||||
|
.padding(10.dp),
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
// ★ "列表里有 300 条"和"带进去 50 条"是完全不同的两件事。
|
||||||
|
// 不写清楚的话,用户会以为记忆全都在提示词里。
|
||||||
|
"这一轮会带进去 $injected / $total 条",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = doubaoText(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(3.dp))
|
||||||
|
Text(
|
||||||
|
buildString {
|
||||||
|
append("窗口:")
|
||||||
|
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||||
|
if (space.pinnedCount > 0) {
|
||||||
|
append(";其中 ${space.pinnedCount} 条置顶的永远带,不受窗口限制")
|
||||||
|
}
|
||||||
|
if (injected < total) {
|
||||||
|
append("。没带进去的没丢,AI 用 memory_search 还能搜到。")
|
||||||
|
}
|
||||||
|
append(" 点这里调 ›")
|
||||||
|
},
|
||||||
|
fontSize = 10.sp,
|
||||||
|
lineHeight = 15.sp,
|
||||||
|
color = doubaoTextSecondary(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
||||||
if (worldMode) {
|
if (worldMode) {
|
||||||
Box(
|
Box(
|
||||||
@@ -327,6 +377,44 @@ fun MemoryScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 注入窗口的调整(A 方案)----
|
||||||
|
if (editWindow) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { editWindow = false },
|
||||||
|
title = { Text("注入窗口", fontSize = 16.sp) },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||||
|
"置顶的永远带,不受这个数限制;其余按时间取最近的。\n" +
|
||||||
|
"没带进去的不会丢 —— AI 用 memory_search 还能搜到。\n\n" +
|
||||||
|
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||||
|
"而且早期的会挤掉最近的对话上下文。",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
lineHeight = 18.sp,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = windowDraft,
|
||||||
|
onValueChange = { s -> windowDraft = s.filter { it.isDigit() }.take(5) },
|
||||||
|
label = { Text("条数(0 = 不限)", fontSize = 12.sp) },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
editWindow = false
|
||||||
|
onSetWindow(windowDraft.toIntOrNull() ?: 0)
|
||||||
|
}) { Text("保存") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { editWindow = false }) { Text("取消") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// ---- AI 整理的确认(复查报告 4.2.1)----
|
// ---- AI 整理的确认(复查报告 4.2.1)----
|
||||||
if (confirmSummarize) {
|
if (confirmSummarize) {
|
||||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||||
@@ -413,7 +501,7 @@ private fun MemoryRow(
|
|||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
if (item.pinned) {
|
if (item.pinned) {
|
||||||
Text(
|
Text(
|
||||||
"必须保留",
|
"置顶",
|
||||||
fontSize = 9.sp,
|
fontSize = 9.sp,
|
||||||
color = Color(0xFF8A6100),
|
color = Color(0xFF8A6100),
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -470,7 +558,7 @@ private fun MemoryRow(
|
|||||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||||
RowAction(if (item.pinned) "取消保留" else "必须保留", onClick = onTogglePin)
|
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||||
RowAction("编辑", onClick = onEdit)
|
RowAction("编辑", onClick = onEdit)
|
||||||
RowAction("删除", danger = true, onClick = onDelete)
|
RowAction("删除", danger = true, onClick = onDelete)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -272,6 +272,15 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
|||||||
'suggestion': '',
|
'suggestion': '',
|
||||||
}
|
}
|
||||||
items = agentdb.memory_list(scope)
|
items = agentdb.memory_list(scope)
|
||||||
|
# 注入窗口(条数):界面要显示"这一轮实际会带多少条进去",
|
||||||
|
# 而"列表里有 300 条"和"带进去 50 条"是完全不同的两件事 ——
|
||||||
|
# 不显示的话用户会以为全都在提示词里。
|
||||||
|
try:
|
||||||
|
window = int((store.read_settings() or {}).get('memoryWindow') or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
window = 0
|
||||||
|
pinned_count = sum(1 for m in items if m.get('pinned'))
|
||||||
|
injected = len(items) if window <= 0 or len(items) <= window else max(window, pinned_count)
|
||||||
return {
|
return {
|
||||||
'ok': True,
|
'ok': True,
|
||||||
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
||||||
@@ -282,6 +291,9 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
|||||||
# ★ 绑定世界观之后,私有空间里可能还留着以前攒的记忆 ——
|
# ★ 绑定世界观之后,私有空间里可能还留着以前攒的记忆 ——
|
||||||
# 条数一并告诉界面,它才知道要不要显示"以前那些在这"这个入口
|
# 条数一并告诉界面,它才知道要不要显示"以前那些在这"这个入口
|
||||||
'ownCount': 0 if scope == own else len(agentdb.memory_list(own)),
|
'ownCount': 0 if scope == own else len(agentdb.memory_list(own)),
|
||||||
|
'window': window,
|
||||||
|
'pinnedCount': pinned_count,
|
||||||
|
'injected': injected,
|
||||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,22 +103,65 @@ def build_emotion(agent: dict) -> str:
|
|||||||
|
|
||||||
def build_memory(agent: dict) -> str:
|
def build_memory(agent: dict) -> str:
|
||||||
"""
|
"""
|
||||||
`<memory>` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。
|
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||||
|
|
||||||
★★ 共享空间里的条目**带作者署名**(复查报告第 5 条)。
|
## 注入窗口 + 置顶保护
|
||||||
|
|
||||||
为什么必须带:共享记忆是几个人往同一个本子上写。没有署名的时候,
|
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||||
别人写的"我小时候住在海边"在模型眼里就是**它自己的经历** ——
|
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||||
它会当成自己的过去来讲,甚至在用户问起时说"我不记得有这事"。
|
早期记忆反而挤掉了最近的对话上下文**。
|
||||||
署名之后它才知道"这条是仙辰写的,不是我的"(需求 3.6 的
|
|
||||||
"交模型调和矛盾记忆"也才有前提:得先分得清谁写的)。
|
|
||||||
|
|
||||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
所以这里按**窗口**裁:
|
||||||
|
|
||||||
|
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||||
|
· 其余按时间取**最近**的,凑够窗口
|
||||||
|
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||||
|
不是用来否决用户明确置顶的东西)
|
||||||
|
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||||
|
也就是"降级为仅可检索"
|
||||||
|
|
||||||
|
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||||
|
|
||||||
|
## 共享记忆带作者署名
|
||||||
|
|
||||||
|
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||||
|
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||||
|
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||||
|
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||||
|
得先分得清谁写的)。
|
||||||
|
|
||||||
|
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||||
"""
|
"""
|
||||||
scope = memory_scope(agent)
|
scope = memory_scope(agent)
|
||||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||||
if not items:
|
if not items:
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
# ---- 窗口裁剪 ----
|
||||||
|
settings = _safe(store.read_settings, {}) or {}
|
||||||
|
try:
|
||||||
|
window = int(settings.get('memoryWindow') or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
window = 0
|
||||||
|
total = len(items)
|
||||||
|
trimmed = 0
|
||||||
|
if window > 0 and total > window:
|
||||||
|
pinned = [m for m in items if m.get('pinned')]
|
||||||
|
rest = [m for m in items if not m.get('pinned')]
|
||||||
|
room = max(0, window - len(pinned))
|
||||||
|
keep = pinned + (rest[-room:] if room else [])
|
||||||
|
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
|
||||||
|
items = keep
|
||||||
|
trimmed = total - len(keep)
|
||||||
|
parts = []
|
||||||
|
if pinned:
|
||||||
|
parts.append(f'置顶 {len(pinned)} 条')
|
||||||
|
if trimmed:
|
||||||
|
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
|
||||||
|
note = '(' + ';'.join(parts) + ')' if parts else ''
|
||||||
|
else:
|
||||||
|
note = ''
|
||||||
|
|
||||||
tmpl = _safe(
|
tmpl = _safe(
|
||||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||||
DEFAULT_MEMORY_LINE,
|
DEFAULT_MEMORY_LINE,
|
||||||
@@ -133,15 +176,20 @@ def build_memory(agent: dict) -> str:
|
|||||||
title = (it.get('title') or '').strip()
|
title = (it.get('title') or '').strip()
|
||||||
content = (it.get('content') or '').strip()
|
content = (it.get('content') or '').strip()
|
||||||
author = (it.get('author_agent') or '').strip()
|
author = (it.get('author_agent') or '').strip()
|
||||||
|
tags = []
|
||||||
|
if it.get('pinned'):
|
||||||
|
tags.append('置顶')
|
||||||
if shared and author:
|
if shared and author:
|
||||||
# 自己写的也标出来("(你记的)")—— 一眼能分清哪些是自己的立场
|
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||||
who = '你记的' if author == me else f'{names.get(author) or "某人"}记的'
|
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||||
title = f'{title}({who})'
|
if tags:
|
||||||
|
title = f'{title}({",".join(tags)})'
|
||||||
try:
|
try:
|
||||||
lines.append(tmpl.format(title=title, content=content))
|
lines.append(tmpl.format(title=title, content=content))
|
||||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||||
return '\n'.join(lines)
|
body = '\n'.join(lines)
|
||||||
|
return f'{body}\n{note}' if note else body
|
||||||
|
|
||||||
|
|
||||||
def build_peer_emotions(agent: dict) -> str:
|
def build_peer_emotions(agent: dict) -> str:
|
||||||
|
|||||||
@@ -207,10 +207,16 @@ def memory_get(memory_id: str) -> dict | None:
|
|||||||
|
|
||||||
|
|
||||||
def memory_list(scope: str) -> list:
|
def memory_list(scope: str) -> list:
|
||||||
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
|
"""
|
||||||
|
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
|
||||||
|
|
||||||
|
★ 顺序是**置顶的排最前**,其余按时间。
|
||||||
|
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
|
||||||
|
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
|
||||||
|
"""
|
||||||
init()
|
init()
|
||||||
rows = _connect().execute(
|
rows = _connect().execute(
|
||||||
'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,),
|
'SELECT * FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|||||||
@@ -928,7 +928,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
body = self.read_json_body()
|
body = self.read_json_body()
|
||||||
except ValueError:
|
except ValueError:
|
||||||
body = {}
|
body = {}
|
||||||
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
|
self.send_json(200, {'conversation': store.create_conversation(
|
||||||
|
body.get('title') or '新对话',
|
||||||
|
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||||||
|
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||||||
|
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||||||
|
agent_id=(body.get('agentId') or '').strip(),
|
||||||
|
)})
|
||||||
return True
|
return True
|
||||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||||
if conv_id is not None:
|
if conv_id is not None:
|
||||||
@@ -1661,6 +1667,27 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||||
agent_id = (agent or {}).get('id') or ''
|
agent_id = (agent or {}).get('id') or ''
|
||||||
|
|
||||||
|
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||||
|
#
|
||||||
|
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||||
|
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
|
||||||
|
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
|
||||||
|
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
|
||||||
|
#
|
||||||
|
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
|
||||||
|
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||||
|
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||||
|
owner = (existing.get('agentId') or '').strip()
|
||||||
|
if existing and agent_id:
|
||||||
|
if not owner:
|
||||||
|
store.set_conversation_agent(conversation_id, agent_id)
|
||||||
|
elif owner != agent_id:
|
||||||
|
conversation_id = store.create_conversation(agent_id=agent_id)['id']
|
||||||
|
existing = store.get_conversation(conversation_id) or {}
|
||||||
|
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
|
||||||
|
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||||
|
'reason': 'agent_changed'})
|
||||||
|
|
||||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||||
#
|
#
|
||||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||||
|
|||||||
@@ -166,6 +166,15 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
|||||||
|
|
||||||
|
|
||||||
DEFAULT_SETTINGS = {
|
DEFAULT_SETTINGS = {
|
||||||
|
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
|
||||||
|
#
|
||||||
|
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
|
||||||
|
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
|
||||||
|
# 记忆越贵、反而把最近的对话上下文挤掉**。
|
||||||
|
# 所以给一个窗口:置顶的永远注入,其余取最近的。
|
||||||
|
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||||
|
# 0 = 不限(退回全量注入)。
|
||||||
|
'memoryWindow': 50,
|
||||||
'provider': 'ark',
|
'provider': 'ark',
|
||||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||||
|
|||||||
@@ -932,6 +932,26 @@ def delete_conversation(conv_id: str) -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def set_conversation_agent(conv_id: str, agent_id: str) -> None:
|
||||||
|
"""
|
||||||
|
把会话**认领**给一个智能体(只用于没有主人的老会话)。
|
||||||
|
|
||||||
|
★ 只认领、不"改嫁":已经在别人名下的会话不由这里动 ——
|
||||||
|
那会让历史消息和提示词对不上(用户报的"串味"就是这么来的)。
|
||||||
|
★ 走 `_load_conversations` / `_persist_conversations` 这一对,
|
||||||
|
不要自己 `_read_json`+`_write_json`:会话有一份**内存缓存**,
|
||||||
|
绕过它写文件的话,紧接着的 `get_conversation` 读到的还是旧的缓存
|
||||||
|
(这个错误在探针里被抓到过)。
|
||||||
|
"""
|
||||||
|
with _lock:
|
||||||
|
data = _load_conversations()
|
||||||
|
for c in data.get('conversations') or []:
|
||||||
|
if c.get('id') == conv_id and not (c.get('agentId') or '').strip():
|
||||||
|
c['agentId'] = agent_id
|
||||||
|
_persist_conversations()
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
def append_messages(conv_id: str, messages: list):
|
def append_messages(conv_id: str, messages: list):
|
||||||
item = get_conversation(conv_id)
|
item = get_conversation(conv_id)
|
||||||
if not item:
|
if not item:
|
||||||
|
|||||||
@@ -373,6 +373,57 @@ def main():
|
|||||||
str(again and again.get("agents")))
|
str(again and again.get("agents")))
|
||||||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
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")))
|
||||||
|
store.write_settings({"memoryWindow": 50})
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 汇总
|
# ---------------------------------------------------------------- 汇总
|
||||||
print()
|
print()
|
||||||
if fails:
|
if fails:
|
||||||
|
|||||||
Reference in New Issue
Block a user