Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 249
|
||||
versionName = "2.0.49"
|
||||
versionCode = 252
|
||||
versionName = "2.0.52"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -229,8 +229,23 @@ fun AgentEditScreen(
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定,而且记忆会和同世界观的其他智能体共享。\n" +
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
@@ -124,6 +125,8 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -189,6 +192,8 @@ private fun AgentRow(
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -224,6 +229,19 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -271,6 +271,7 @@ fun AppRoot(
|
||||
onTogglePin = { _, _ -> },
|
||||
onSummarize = {},
|
||||
onExport = {},
|
||||
onSetWindow = {},
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
@@ -324,6 +325,7 @@ fun AppRoot(
|
||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||
onSummarize = { vm.summarizeMemories() },
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||
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() {
|
||||
val id = memoryAgentId
|
||||
if (id.isBlank()) return
|
||||
@@ -1027,7 +1047,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
fun newTopic() {
|
||||
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()
|
||||
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 -> {
|
||||
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
||||
// 清零 / 调大限额 / 改成无限制。所以单独记一个标记,
|
||||
@@ -1394,7 +1424,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
|
||||
fun useAgent(id: String) {
|
||||
val changed = id != state.settings.activeAgentId
|
||||
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.border
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -30,6 +31,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
@@ -82,6 +84,8 @@ fun MemoryScreen(
|
||||
onTogglePin: (String, Boolean) -> Unit,
|
||||
onSummarize: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
/** 调注入窗口(条数,0 = 不限) */
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||
@@ -95,6 +99,9 @@ fun MemoryScreen(
|
||||
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
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
|
||||
|
||||
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) {
|
||||
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)----
|
||||
if (confirmSummarize) {
|
||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||
@@ -413,7 +501,7 @@ private fun MemoryRow(
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (item.pinned) {
|
||||
Text(
|
||||
"必须保留",
|
||||
"置顶",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier
|
||||
@@ -470,7 +558,7 @@ private fun MemoryRow(
|
||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||
RowAction(if (item.pinned) "取消保留" else "必须保留", onClick = onTogglePin)
|
||||
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||
RowAction("编辑", onClick = onEdit)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
}
|
||||
|
||||
@@ -283,6 +283,21 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
// ★ 谁绑了它(用户要求)—— 反过来也得看得见:
|
||||
// 绑之前你要知道"这个世界观已经有谁在用了",
|
||||
// 空的则说明没人用它、共享记忆也没人在读写。
|
||||
if (kind.id == "worldviews") {
|
||||
val users = vm.state.worldviews.firstOrNull { it.id == id }?.agents ?: emptyList()
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
if (users.isEmpty()) "还没有智能体用它"
|
||||
else "${users.size} 个智能体在用:${users.joinToString("、") { it.name }}",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = if (users.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("记忆") {
|
||||
// ★ 世界观的**共享记忆**("大家共同记得什么")——
|
||||
|
||||
@@ -272,6 +272,15 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'suggestion': '',
|
||||
}
|
||||
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 {
|
||||
'ok': True,
|
||||
'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)),
|
||||
'window': window,
|
||||
'pinnedCount': pinned_count,
|
||||
'injected': injected,
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
}
|
||||
@@ -691,6 +703,34 @@ _RES_PATH = {
|
||||
}
|
||||
|
||||
|
||||
def _tag_world_agents(items: list) -> list:
|
||||
"""
|
||||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||||
|
||||
★ 为什么在**列表接口**里一起给,而不是开一个 `/worldviews/<id>/agents`:
|
||||
界面本来就要拉这个列表(进资源页就拉),多一个子路由只换来
|
||||
"多一次请求 + 一个可能和列表不同步的缓存"。这个数据量很小
|
||||
(智能体通常几个到几十个),一起算的成本可以忽略。
|
||||
|
||||
★ 顺便能看出**没绑的**(`agents` 为空)—— 那意味着这个世界观
|
||||
目前没人用,它的共享记忆也没有人在读写。
|
||||
"""
|
||||
by_world = {}
|
||||
for a in store.list_agents():
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
by_world.setdefault(wid, []).append({
|
||||
'id': a.get('id') or '',
|
||||
'name': a.get('name') or '未命名',
|
||||
})
|
||||
out = []
|
||||
for it in items or []:
|
||||
it = dict(it)
|
||||
it['agents'] = by_world.get((it.get('id') or '').strip(), [])
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
|
||||
def _resource_route(handler, seg: list, method: str, body, err):
|
||||
if seg[1] not in _RES_PATH:
|
||||
return None
|
||||
@@ -712,7 +752,15 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
|
||||
if len(seg) == 2:
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'items': store.list_resource(name)})
|
||||
items = store.list_resource(name)
|
||||
if name == 'worldviews':
|
||||
# ★ 给世界观补上"哪些智能体绑了它"(用户要求)。
|
||||
# 没有这个的话,你在绑之前想知道"这个世界观已经有谁在用了",
|
||||
# 只能回智能体列表一个个翻 —— 而那正是"互通"该解决的问题。
|
||||
# 在**列表接口里一起给**,而不是再开一个 `/agents` 子路由:
|
||||
# 界面本来就要拉列表,多一次请求只是多一次等待。
|
||||
items = _tag_world_agents(items)
|
||||
handler.send_json(200, {'ok': True, 'items': items})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||||
|
||||
@@ -103,22 +103,65 @@ def build_emotion(agent: dict) -> str:
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。
|
||||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||
|
||||
★★ 共享空间里的条目**带作者署名**(复查报告第 5 条)。
|
||||
## 注入窗口 + 置顶保护
|
||||
|
||||
为什么必须带:共享记忆是几个人往同一个本子上写。没有署名的时候,
|
||||
别人写的"我小时候住在海边"在模型眼里就是**它自己的经历** ——
|
||||
它会当成自己的过去来讲,甚至在用户问起时说"我不记得有这事"。
|
||||
署名之后它才知道"这条是仙辰写的,不是我的"(需求 3.6 的
|
||||
"交模型调和矛盾记忆"也才有前提:得先分得清谁写的)。
|
||||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||
早期记忆反而挤掉了最近的对话上下文**。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
所以这里按**窗口**裁:
|
||||
|
||||
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||
· 其余按时间取**最近**的,凑够窗口
|
||||
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||
不是用来否决用户明确置顶的东西)
|
||||
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||
也就是"降级为仅可检索"
|
||||
|
||||
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||
|
||||
## 共享记忆带作者署名
|
||||
|
||||
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||
得先分得清谁写的)。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
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(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
@@ -133,15 +176,20 @@ def build_memory(agent: dict) -> str:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
author = (it.get('author_agent') or '').strip()
|
||||
tags = []
|
||||
if it.get('pinned'):
|
||||
tags.append('置顶')
|
||||
if shared and author:
|
||||
# 自己写的也标出来("(你记的)")—— 一眼能分清哪些是自己的立场
|
||||
who = '你记的' if author == me else f'{names.get(author) or "某人"}记的'
|
||||
title = f'{title}({who})'
|
||||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||
if tags:
|
||||
title = f'{title}({",".join(tags)})'
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
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:
|
||||
|
||||
@@ -207,10 +207,16 @@ def memory_get(memory_id: str) -> dict | None:
|
||||
|
||||
|
||||
def memory_list(scope: str) -> list:
|
||||
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
|
||||
"""
|
||||
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
|
||||
|
||||
★ 顺序是**置顶的排最前**,其余按时间。
|
||||
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
|
||||
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
|
||||
"""
|
||||
init()
|
||||
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()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
@@ -928,7 +928,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
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
|
||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||
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_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)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
|
||||
@@ -166,6 +166,15 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
|
||||
#
|
||||
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
|
||||
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
|
||||
# 记忆越贵、反而把最近的对话上下文挤掉**。
|
||||
# 所以给一个窗口:置顶的永远注入,其余取最近的。
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
|
||||
@@ -932,6 +932,26 @@ def delete_conversation(conv_id: str) -> bool:
|
||||
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):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
|
||||
108
scripts/demo-peer-visibility.py
Normal file
108
scripts/demo-peer-visibility.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""演示:智能体在提示词里**实际能看到什么**(同世界观的伙伴)。
|
||||
|
||||
用户问"智能体能看哪些智能体绑了它吗" —— 这件事光说"能"没意义,
|
||||
跑一下把**真实注入的那段文字**打出来看。
|
||||
|
||||
python scripts/demo-peer-visibility.py
|
||||
|
||||
它造一个世界观 + 三个智能体(两个绑上、一个不绑),然后把三个智能体
|
||||
各自收到的 `<peer_emotions>` 段原样打印。
|
||||
"""
|
||||
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-demo-peer-")
|
||||
os.environ["DOUBAO_DATA"] = DATA
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
def seg(prompt: str, name: str) -> str:
|
||||
"""把某一段从拼好的提示词里抠出来(看不到就是空)"""
|
||||
a = prompt.find(f'<{name}>')
|
||||
if a < 0:
|
||||
return '(整段没有)'
|
||||
b = prompt.find(f'</{name}>', a)
|
||||
return prompt[a:b + len(name) + 3]
|
||||
|
||||
|
||||
def main():
|
||||
world = store.create_resource('worldviews', {
|
||||
'name': '九州', 'setting': '一个仙侠世界,灵气复苏。',
|
||||
})
|
||||
xc = store.create_agent({'name': '玄辰', 'systemPrompt': '你是玄辰,仙门大师兄。'})
|
||||
xc = store.update_agent(xc['id'], {'worldviewId': world['id']}) or xc
|
||||
xc2 = store.create_agent({'name': '仙辰', 'systemPrompt': '你是仙辰。'})
|
||||
xc2 = store.update_agent(xc2['id'], {'worldviewId': world['id']}) or xc2
|
||||
lone = store.create_agent({'name': '独行侠', 'systemPrompt': '你谁也不认识。'})
|
||||
|
||||
agentdb.emotion_set(xc['id'], '刚被师父训了一顿,有点闷')
|
||||
agentdb.emotion_set(xc2['id'], '刚赢了比试,得意')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('① 玄辰(绑了九州)· 情绪感知**关着**(默认)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 知道「有谁」,但看不到他们的情绪。')
|
||||
print(' 为什么关着也要给名单:共享记忆是共用的,它一定会看到别人写的条目。')
|
||||
print(' 不知道有别人,它就会把别人的经历当成自己的过去。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('② 玄辰 · 情绪感知**打开**(编辑界面 → 能力 → 情绪感知)')
|
||||
print('=' * 70)
|
||||
store.update_agent(xc['id'], {'emotionEnabled': True})
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 名单 + 各自当前的情绪。情绪仍然是**单向只读**的:')
|
||||
print(' 玄辰能看到仙辰的情绪,但改不了;仙辰那边看到的是玄辰的。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('③ 独行侠(没绑世界观)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(lone['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 没有这段。它没有世界观,也就没有"伙伴"这回事。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('④ 共享记忆里别人写的条目(署名)')
|
||||
print('=' * 70)
|
||||
scope = agentdb.world_scope(world['id'])
|
||||
agentdb.memory_add(scope, '师父的忌讳', '提到"剑冢"他会翻脸', author_agent=xc2['id'])
|
||||
agentdb.memory_add(scope, '我的佩剑', '叫"霜落",是师父给的', author_agent=xc['id'])
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'memory'))
|
||||
print()
|
||||
print(' → 玄辰看到的是:仙辰记的那条**标了「仙辰记的」**,')
|
||||
print(' 自己记的那条标「你记的」。不标的话,')
|
||||
print(' "我小时候住在海边"这种别人写的经历,在它眼里就是它自己的过去。')
|
||||
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
code = main()
|
||||
finally:
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
sys.exit(code)
|
||||
@@ -350,6 +350,80 @@ def main():
|
||||
r = h.call(f"/api/skills/{sid}", "DELETE")
|
||||
check("删 skill", r.get("deleted") is True)
|
||||
|
||||
# ---------------------------------------------------------------- 13
|
||||
section("13. 世界观的引用列表(谁绑了它)")
|
||||
lonely = store.create_resource("worldviews", {"name": "没人用的世界", "setting": "空"})
|
||||
r = h.call("/api/worldviews", "GET")
|
||||
items = r.get("items") or []
|
||||
check("列表每一项都带 agents 字段", items and all("agents" in it for it in items))
|
||||
mine = next((it for it in items if it.get("id") == wv["id"]), None)
|
||||
check("绑了它的两个智能体都在", mine is not None and len(mine.get("agents") or []) == 2,
|
||||
str(mine and mine.get("agents")))
|
||||
check("给的是名字而不是只有 id",
|
||||
bool(mine) and all(a.get("name") for a in mine.get("agents") or []),
|
||||
str(mine and mine.get("agents")))
|
||||
empty = next((it for it in items if it.get("id") == lonely["id"]), None)
|
||||
check("没人绑的世界观 agents 为空(能看出没人用)",
|
||||
empty is not None and empty.get("agents") == [], str(empty and empty.get("agents")))
|
||||
# 解绑之后要跟着变(缓存住了的话这里会露馅)
|
||||
store.update_agent(a2["id"], {"worldviewId": ""})
|
||||
again = next((it for it in (h.call("/api/worldviews", "GET").get("items") or [])
|
||||
if it.get("id") == wv["id"]), None)
|
||||
check("解绑之后列表跟着少一个", again is not None and len(again.get("agents") or []) == 1,
|
||||
str(again and again.get("agents")))
|
||||
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()
|
||||
if fails:
|
||||
|
||||
Reference in New Issue
Block a user