## 串味:会话没做隔离 会话本来就有 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 整数
296 lines
12 KiB
Python
296 lines
12 KiB
Python
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||
|
||
## 这个模块只做一件事
|
||
|
||
把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序**
|
||
拼成一段 system prompt。
|
||
|
||
## 为什么单独一个模块,而不是写在 agent_loop 里
|
||
|
||
因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把
|
||
整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。
|
||
|
||
## 几条硬约定
|
||
|
||
**① 空段整段删掉。**
|
||
绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。
|
||
不删的话每次对话都带着一堆空的 `<worldview></worldview>`,
|
||
模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。
|
||
|
||
**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。**
|
||
见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦"
|
||
再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。
|
||
|
||
**③ 每轮重新拼。**
|
||
记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话,
|
||
用户会看到"我明明让它记住了,下一句它又忘了"。
|
||
|
||
**④ 查库失败一律当成"这段没有"。**
|
||
数据库被锁、文件损坏都不该让用户发不出消息。
|
||
"""
|
||
|
||
import re
|
||
|
||
import agentdb
|
||
import store
|
||
from defaults import (
|
||
BUILTIN_SKILL,
|
||
DEFAULT_MEMORY_LINE,
|
||
DEFAULT_PROMPT_TEMPLATE,
|
||
)
|
||
|
||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||
SECTIONS = ('skills', 'worldview', 'emotion', 'memory', 'peer_emotions')
|
||
|
||
|
||
def _safe(fn, fallback):
|
||
"""
|
||
跑一个小查询,出错就当"没有"。
|
||
|
||
★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该
|
||
让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。
|
||
"""
|
||
try:
|
||
return fn()
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr)
|
||
return fallback
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 各段
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def build_skills(agent: dict) -> str:
|
||
"""
|
||
`<skills>` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。
|
||
|
||
内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用,
|
||
自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。
|
||
"""
|
||
parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else []
|
||
agent_id = (agent or {}).get('id') or ''
|
||
if agent_id:
|
||
for sid in _safe(lambda: agentdb.skills_of(agent_id), []):
|
||
sk = _safe(lambda: store.get_resource('skills', sid), None)
|
||
if sk and (sk.get('content') or '').strip():
|
||
parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}')
|
||
return '\n\n'.join(parts)
|
||
|
||
|
||
def build_worldview(agent: dict) -> str:
|
||
"""`<worldview>` 段:绑定的世界观设定文本(没绑就是空)"""
|
||
wid = (agent or {}).get('worldviewId') or ''
|
||
if not wid:
|
||
return ''
|
||
wv = _safe(lambda: store.get_resource('worldviews', wid), None)
|
||
return (wv or {}).get('setting', '').strip()
|
||
|
||
|
||
def memory_scope(agent: dict) -> str:
|
||
"""这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)"""
|
||
agent = agent or {}
|
||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||
|
||
|
||
def build_emotion(agent: dict) -> str:
|
||
"""`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)"""
|
||
agent_id = (agent or {}).get('id') or ''
|
||
if not agent_id:
|
||
return ''
|
||
return (_safe(lambda: agentdb.emotion_get(agent_id), '') or '').strip()
|
||
|
||
|
||
def build_memory(agent: dict) -> str:
|
||
"""
|
||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||
|
||
## 注入窗口 + 置顶保护
|
||
|
||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||
记忆撑爆(每条几十字,一千条就是几万 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,
|
||
)
|
||
shared = scope.startswith('world:')
|
||
names = {}
|
||
if shared:
|
||
names = {a.get('id'): (a.get('name') or '某人') for a in _safe(store.list_agents, [])}
|
||
me = (agent or {}).get('id') or ''
|
||
lines = []
|
||
for it in items:
|
||
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:
|
||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||
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))
|
||
body = '\n'.join(lines)
|
||
return f'{body}\n{note}' if note else body
|
||
|
||
|
||
def build_peer_emotions(agent: dict) -> str:
|
||
"""
|
||
`<peer_emotions>` 段:**同世界观其他智能体**的名字(+ 情绪)(需求 3.5)。
|
||
|
||
★★ 分两档,不是"开关一关就什么都没有":
|
||
|
||
· 绑了世界观但**没开**情绪感知 → 只给**成员名单**(谁在,但看不到情绪)
|
||
· 绑了世界观且**开了**开关 → 名单 + 各自当前的情绪
|
||
|
||
为什么关着也要给名单(复查报告第 5 条):
|
||
共享记忆是**共用**的,AI 一定会看到"别人写的条目"。如果它连
|
||
"这个空间里还有别人"都不知道,那些第三人称的条目在它眼里就是
|
||
**自己的记忆**——它会以为"我什么时候去过九霄山?",
|
||
于是把别人的经历当成自己的,或者在正文里跟用户说"我没记过这个"。
|
||
名单不含情绪,所以"角色内的隐私"这条边界仍然守住了。
|
||
|
||
★ 情绪感知开关默认关(需求原话"默认关闭")—— 别人的**情绪**属于
|
||
角色内的隐私,默认让 AI 看到会让它们的表现互相串味。
|
||
"""
|
||
agent = agent or {}
|
||
if not agent.get('worldviewId'):
|
||
return ''
|
||
my_id = agent.get('id') or ''
|
||
wid = agent.get('worldviewId') or ''
|
||
others = [
|
||
a for a in _safe(store.list_agents, [])
|
||
if a.get('worldviewId') == wid and a.get('id') != my_id
|
||
]
|
||
if not others:
|
||
return ''
|
||
|
||
by_id = {a.get('id'): a for a in others}
|
||
names = [(by_id.get(aid) or {}).get('name') or '某人' for aid in by_id]
|
||
|
||
if not agent.get('emotionEnabled'):
|
||
return ';'.join(f'{n}(不知道他此刻的情绪)' for n in names)
|
||
|
||
rows = _safe(
|
||
lambda: agentdb.peer_emotions(wid, my_id, list(by_id)),
|
||
[],
|
||
)
|
||
emo_by_id = {aid: (emo or '').strip() for aid, emo in rows}
|
||
parts = []
|
||
for aid, one in by_id.items():
|
||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||
name = one.get('name') or '某人'
|
||
emo = emo_by_id.get(aid) or ''
|
||
parts.append(f'{name}-{emo}' if emo else f'{name}(没说自己在想什么)')
|
||
return ';'.join(parts)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 拼装
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
_RE_BLOCK = {name: re.compile(rf'<{name}>.*?</{name}>', re.S) for name in SECTIONS}
|
||
|
||
|
||
def render(template: str, values: dict) -> str:
|
||
"""
|
||
按模板渲染,**空的段整段删掉**。
|
||
|
||
★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `<memory>` 这样的字
|
||
(用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配
|
||
只在**模板**上做,不在渲染结果上做。
|
||
"""
|
||
out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip())
|
||
for name in SECTIONS:
|
||
block = _RE_BLOCK[name].search(out)
|
||
if not block:
|
||
continue
|
||
value = (values.get(name) or '').strip()
|
||
if value:
|
||
out = out[:block.start()] + f'<{name}>\n{value}\n</{name}>' + out[block.end():]
|
||
else:
|
||
out = out[:block.start()] + out[block.end():]
|
||
# 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白
|
||
out = re.sub(r'\n{3,}', '\n\n', out)
|
||
return out.strip()
|
||
|
||
|
||
def build_system_prompt(settings: dict, agent: dict) -> str:
|
||
"""
|
||
这一轮要用的 system prompt。
|
||
|
||
[settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。
|
||
"""
|
||
agent = agent or {}
|
||
settings = settings or {}
|
||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||
values = {
|
||
'prompt': prompt,
|
||
'skills': build_skills(agent),
|
||
'worldview': build_worldview(agent),
|
||
'emotion': build_emotion(agent),
|
||
'memory': build_memory(agent),
|
||
'peer_emotions': build_peer_emotions(agent),
|
||
}
|
||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||
return render(template, values)
|