按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。 ## 内核 - 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。 **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由): 记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删", 那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、 且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。 - 新增 agent_context.py:按需求附录 C 拼 system prompt (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。 - 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、 memory_suggest_summary、emotion_set、get_token_usage)。 走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。 共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。 - 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、 Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。 app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。 - store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、 三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、 delete_agent 清理绑定关系但**不删记忆**。 - Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头, 以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高) + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住, 附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。 - 会议节点的 system prompt 也改用 agent_context(以前是自己拼的, 同一个智能体在会议里没有记忆/情绪/世界观)。 - doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。 ## 安卓 - AgentSelectScreen:智能体选择界面(需求第二章)—— 左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框), 1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序, 连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。 - AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)—— PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧), SVG 走 WebView(原生解不了)。 - TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、 限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、 pinned 开关、共享记忆提示)。 - Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。 - 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面 (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。 - 需求文档给的两张默认资源图进 res/drawable(2.3MB)。 ## 验证 - 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路 (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、 pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、 20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、 记忆导入的合并去重、资源 CRUD。全绿。 - 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。 ## 还没做(下一阶段) 世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展 (介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、 幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
441 lines
16 KiB
Python
441 lines
16 KiB
Python
"""智能体系统的数据层:**记忆 / 情绪 / Token 统计 / 绑定关系**。
|
||
|
||
## 为什么这次用 SQLite,而别处(设置/会话/智能体)还是 JSON
|
||
|
||
`store.py` 顶上写着"为什么用 JSON 而不是 SQLite",理由很实在:
|
||
**数据量极小**(几条会话、几个智能体),而且用户/开发者要能直接看到、改那些文件。
|
||
|
||
那个理由对**智能体本身**依然成立(就几个),所以它们还在 `agents.json` 里。
|
||
但记忆不一样,三条都指向 SQLite:
|
||
|
||
· 需求明确"记忆条目**无上限**",而**每轮对话都要全量注入** smartMemory ——
|
||
几千条记忆塞进一个 JSON、每轮读盘再反序列化一遍,代价是实打实的
|
||
· 要按关键词检索(`memory_search` 是 LIKE 查询)
|
||
· 要"只改一条""只删自己写的"这种**行级**操作 —— 在 JSON 里就是
|
||
读全量 → 改 → 写全量,多线程下一次并发写就可能把别人的改动盖掉
|
||
|
||
所以分界线是:**会持续增长、要按行操作或检索的数据 → SQLite;
|
||
少量、要人肉可读的配置 → JSON。**
|
||
|
||
(另:这几张表**只属于智能体系统**,不和会话/设置混在一起 ——
|
||
`agent.db` 单独一个文件,删了就是"重置智能体系统",不会碰到聊天记录。)
|
||
|
||
## 关联一律用 UUID
|
||
|
||
见需求附录 A。`memories.author_agent`、`agent_skills.agent_id`、
|
||
`token_usage.agent_id` 存的都是 UUID,`name` 只是显示名(可重复、可随便改)。
|
||
"""
|
||
|
||
import os
|
||
import sqlite3
|
||
import threading
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
|
||
import paths
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 连接
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# ★ 每线程一个连接:sqlite3 的连接默认不能跨线程用,而内核是多线程的
|
||
# (HTTP 每请求一线程 + 工具跑在又一个线程里)。
|
||
# 用 threading.local() 而不是"一个全局连接 + 一把大锁":记忆检索可能在
|
||
# 对话生成的过程中被调用,一把大锁会把整条链路串起来。
|
||
_local = threading.local()
|
||
_init_done = False
|
||
_init_lock = threading.Lock()
|
||
|
||
|
||
def db_path() -> str:
|
||
"""数据库文件的位置(跟着数据目录走,和 settings.json 同一层)"""
|
||
return os.path.join(os.path.dirname(paths.get().settings_file), 'agent.db')
|
||
|
||
|
||
def _connect() -> sqlite3.Connection:
|
||
conn = getattr(_local, 'conn', None)
|
||
if conn is not None:
|
||
return conn
|
||
os.makedirs(os.path.dirname(db_path()), exist_ok=True)
|
||
# check_same_thread=False 是安全的:这个连接只会被**创建它的那个线程**用到
|
||
conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=10)
|
||
conn.row_factory = sqlite3.Row
|
||
# WAL:读不挡写。安卓上内核同时有"对话在写记忆"和"界面在读列表"。
|
||
try:
|
||
conn.execute('PRAGMA journal_mode=WAL')
|
||
conn.execute('PRAGMA synchronous=NORMAL')
|
||
except sqlite3.Error:
|
||
pass # 只读文件系统之类:不致命,退化成默认模式
|
||
_local.conn = conn
|
||
return conn
|
||
|
||
|
||
SCHEMA = """
|
||
CREATE TABLE IF NOT EXISTS memories (
|
||
id TEXT PRIMARY KEY,
|
||
scope TEXT NOT NULL,
|
||
title TEXT NOT NULL DEFAULT '',
|
||
content TEXT NOT NULL DEFAULT '',
|
||
pinned INTEGER NOT NULL DEFAULT 0,
|
||
author_agent TEXT NOT NULL DEFAULT '',
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||
|
||
CREATE TABLE IF NOT EXISTS emotions (
|
||
agent_id TEXT PRIMARY KEY,
|
||
emotion TEXT NOT NULL DEFAULT '',
|
||
updated_at TEXT NOT NULL
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS token_usage (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
agent_id TEXT NOT NULL,
|
||
model TEXT NOT NULL DEFAULT '',
|
||
input INTEGER NOT NULL DEFAULT 0,
|
||
output INTEGER NOT NULL DEFAULT 0,
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
|
||
|
||
CREATE TABLE IF NOT EXISTS agent_skills (
|
||
agent_id TEXT NOT NULL,
|
||
skill_id TEXT NOT NULL,
|
||
ord INTEGER NOT NULL DEFAULT 0,
|
||
PRIMARY KEY (agent_id, skill_id)
|
||
);
|
||
"""
|
||
|
||
|
||
def init() -> None:
|
||
"""建表(幂等)。内核启动时调一次,各处也会惰性调。"""
|
||
global _init_done
|
||
if _init_done:
|
||
return
|
||
with _init_lock:
|
||
if _init_done:
|
||
return
|
||
conn = _connect()
|
||
conn.executescript(SCHEMA)
|
||
conn.commit()
|
||
_init_done = True
|
||
|
||
|
||
def reset_init() -> None:
|
||
"""测试用:换过数据目录之后强制重新建表"""
|
||
global _init_done
|
||
_init_done = False
|
||
_local.__dict__.pop('conn', None)
|
||
|
||
|
||
def new_id() -> str:
|
||
"""新实体的主键。**一律 UUID**(需求附录 A)"""
|
||
return str(uuid.uuid4())
|
||
|
||
|
||
def now_iso() -> str:
|
||
"""和 store.now_iso() 一样的格式(前端直接拿来排序/展示)"""
|
||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# scope:记忆是"智能体私有"还是"世界观共享"
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# ★ 用带前缀的字符串而不是两列(agent_id / worldview_id):
|
||
# 读的时候永远只关心"这一条属于哪个记忆空间",不需要分情况查两列;
|
||
# 而且以后加第三种空间(比如"全局公共记忆")不用改表结构。
|
||
|
||
def agent_scope(agent_id: str) -> str:
|
||
return f'agent:{agent_id or ""}'
|
||
|
||
|
||
def world_scope(worldview_id: str) -> str:
|
||
return f'world:{worldview_id or ""}'
|
||
|
||
|
||
def scope_of(agent_id: str, worldview_id: str = '') -> str:
|
||
"""
|
||
这个智能体当前该读写哪个记忆空间。
|
||
|
||
绑定世界观 → 共享空间;没绑定 → 自己的私有空间(需求 3.6)。
|
||
"""
|
||
if worldview_id:
|
||
return world_scope(worldview_id)
|
||
return agent_scope(agent_id)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 记忆
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def memory_add(scope: str, title: str, content: str, author_agent: str = '') -> dict:
|
||
"""新增一条。返回整条(带新生成的 UUID)"""
|
||
init()
|
||
item = {
|
||
'id': new_id(),
|
||
'scope': scope,
|
||
'title': (title or '').strip(),
|
||
'content': (content or '').strip(),
|
||
'pinned': 0,
|
||
'author_agent': author_agent or '',
|
||
'created_at': now_iso(),
|
||
}
|
||
conn = _connect()
|
||
conn.execute(
|
||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||
'VALUES (:id, :scope, :title, :content, :pinned, :author_agent, :created_at)',
|
||
item,
|
||
)
|
||
conn.commit()
|
||
return item
|
||
|
||
|
||
def memory_get(memory_id: str) -> dict | None:
|
||
init()
|
||
row = _connect().execute('SELECT * FROM memories WHERE id = ?', (memory_id,)).fetchone()
|
||
return dict(row) if row else None
|
||
|
||
|
||
def memory_list(scope: str) -> list:
|
||
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
|
||
init()
|
||
rows = _connect().execute(
|
||
'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
|
||
def memory_search(scope: str, keyword: str, limit: int = 20) -> list:
|
||
"""
|
||
关键词检索(`memory_search` 工具)。
|
||
|
||
★ 用 LIKE 而不是 FTS5:FTS5 对中文要额外的分词器,而这里的关键词
|
||
就是用户/模型给的整词,LIKE '%关键词%' 反而更符合直觉
|
||
(搜"咖啡"能命中"喜欢喝咖啡")。条目量级(几千)下 LIKE 也够快。
|
||
"""
|
||
init()
|
||
kw = (keyword or '').strip()
|
||
if not kw:
|
||
return []
|
||
like = f'%{kw}%'
|
||
rows = _connect().execute(
|
||
'SELECT * FROM memories WHERE scope = ? AND (title LIKE ? OR content LIKE ?) '
|
||
'ORDER BY pinned DESC, created_at DESC LIMIT ?',
|
||
(scope, like, like, max(1, min(200, int(limit)))),
|
||
).fetchall()
|
||
return [dict(r) for r in rows]
|
||
|
||
|
||
def memory_update(memory_id: str, title: str = None, content: str = None) -> dict | None:
|
||
"""改标题/正文(只改传进来的字段)"""
|
||
init()
|
||
cur = memory_get(memory_id)
|
||
if not cur:
|
||
return None
|
||
new_title = cur['title'] if title is None else (title or '').strip()
|
||
new_content = cur['content'] if content is None else (content or '').strip()
|
||
conn = _connect()
|
||
conn.execute(
|
||
'UPDATE memories SET title = ?, content = ? WHERE id = ?',
|
||
(new_title, new_content, memory_id),
|
||
)
|
||
conn.commit()
|
||
return memory_get(memory_id)
|
||
|
||
|
||
def memory_forget(memory_id: str) -> bool:
|
||
init()
|
||
conn = _connect()
|
||
cur = conn.execute('DELETE FROM memories WHERE id = ?', (memory_id,))
|
||
conn.commit()
|
||
return cur.rowcount > 0
|
||
|
||
|
||
def memory_set_pinned(memory_id: str, pinned: bool) -> bool:
|
||
"""用户手动标记「必须保留」(AI 改不了这个,见需求 3.2)"""
|
||
init()
|
||
conn = _connect()
|
||
cur = conn.execute('UPDATE memories SET pinned = ? WHERE id = ?', (1 if pinned else 0, memory_id))
|
||
conn.commit()
|
||
return cur.rowcount > 0
|
||
|
||
|
||
def memory_replace_all(scope: str, items: list, keep_pinned: bool = True) -> int:
|
||
"""
|
||
**AI 总结**的写回:整个空间换成压缩后的那份。
|
||
|
||
★ `keep_pinned=True` 时 pinned 条目**原样保留**、不参与替换 ——
|
||
这是需求 3.2 里"pinned 保护"的落地:用户标了"必须保留"的东西,
|
||
不能被一次总结合并掉。
|
||
|
||
返回写回了多少条。
|
||
"""
|
||
init()
|
||
conn = _connect()
|
||
kept = []
|
||
if keep_pinned:
|
||
kept = [dict(r) for r in conn.execute(
|
||
'SELECT * FROM memories WHERE scope = ? AND pinned = 1', (scope,),
|
||
).fetchall()]
|
||
conn.execute('DELETE FROM memories WHERE scope = ?' + (' AND pinned = 0' if keep_pinned else ''),
|
||
(scope,))
|
||
n = 0
|
||
for it in items or []:
|
||
title = str((it or {}).get('title') or '').strip()
|
||
content = str((it or {}).get('content') or '').strip()
|
||
if not title and not content:
|
||
continue
|
||
conn.execute(
|
||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||
'VALUES (?, ?, ?, ?, 0, ?, ?)',
|
||
(new_id(), scope, title, content, str(it.get('author_agent') or ''), now_iso()),
|
||
)
|
||
n += 1
|
||
conn.commit()
|
||
return n + len(kept)
|
||
|
||
|
||
def memory_titles(scope: str) -> list:
|
||
"""只要标题清单(注入时先拼标题,正文按需检索 —— 见注入模板)"""
|
||
init()
|
||
rows = _connect().execute(
|
||
'SELECT title FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||
).fetchall()
|
||
return [r['title'] for r in rows if r['title']]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def emotion_get(agent_id: str) -> str:
|
||
init()
|
||
row = _connect().execute(
|
||
'SELECT emotion FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||
).fetchone()
|
||
return row['emotion'] if row else ''
|
||
|
||
|
||
def emotion_set(agent_id: str, emotion: str) -> str:
|
||
init()
|
||
conn = _connect()
|
||
conn.execute(
|
||
'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) '
|
||
'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at',
|
||
(agent_id or '', emotion or '', now_iso()),
|
||
)
|
||
conn.commit()
|
||
return emotion or ''
|
||
|
||
|
||
def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list:
|
||
"""
|
||
同世界观、**其他**智能体的「名字 + 情绪」(情绪感知开关打开时才注入)。
|
||
|
||
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。
|
||
"""
|
||
init()
|
||
out = []
|
||
for aid in agent_ids or []:
|
||
if not aid or aid == exclude_agent:
|
||
continue
|
||
out.append((aid, emotion_get(aid)))
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Token 统计
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int) -> None:
|
||
"""
|
||
记一次消耗。
|
||
|
||
★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
|
||
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
|
||
不是提前建好的。这样换模型不会有"桶没建好"的问题。
|
||
"""
|
||
init()
|
||
conn = _connect()
|
||
conn.execute(
|
||
'INSERT INTO token_usage (agent_id, model, input, output, created_at) '
|
||
'VALUES (?, ?, ?, ?, ?)',
|
||
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()),
|
||
)
|
||
conn.commit()
|
||
|
||
|
||
def token_usage(agent_id: str) -> dict:
|
||
"""
|
||
这个智能体的累计用量。
|
||
|
||
返回 `{'total': {'input':..,'output':..}, 'byModel': [{'model':..,'input':..,'output':..}]}`
|
||
"""
|
||
init()
|
||
conn = _connect()
|
||
rows = conn.execute(
|
||
'SELECT model, SUM(input) AS i, SUM(output) AS o FROM token_usage '
|
||
'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
|
||
(agent_id or '',),
|
||
).fetchall()
|
||
by_model = [
|
||
{'model': r['model'] or '(未知)', 'input': int(r['i'] or 0), 'output': int(r['o'] or 0)}
|
||
for r in rows
|
||
]
|
||
return {
|
||
'total': {
|
||
'input': sum(m['input'] for m in by_model),
|
||
'output': sum(m['output'] for m in by_model),
|
||
},
|
||
'byModel': by_model,
|
||
}
|
||
|
||
|
||
def token_reset(agent_id: str) -> int:
|
||
"""按智能体清零(需求 3.1 的"管理操作")。返回清掉了几行"""
|
||
init()
|
||
conn = _connect()
|
||
cur = conn.execute('DELETE FROM token_usage WHERE agent_id = ?', (agent_id or '',))
|
||
conn.commit()
|
||
return cur.rowcount
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Skill 绑定
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def skills_of(agent_id: str) -> list:
|
||
"""这个智能体绑定的自定义 Skill id(**按绑定顺序** —— 注入要按顺序拼)"""
|
||
init()
|
||
rows = _connect().execute(
|
||
'SELECT skill_id FROM agent_skills WHERE agent_id = ? ORDER BY ord ASC, skill_id ASC',
|
||
(agent_id or '',),
|
||
).fetchall()
|
||
return [r['skill_id'] for r in rows]
|
||
|
||
|
||
def bind_skills(agent_id: str, skill_ids: list) -> None:
|
||
"""整体替换绑定关系(界面上的"勾选"就是一次整体替换,不用做增删接口)"""
|
||
init()
|
||
conn = _connect()
|
||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||
for i, sid in enumerate(skill_ids or []):
|
||
if not sid:
|
||
continue
|
||
conn.execute(
|
||
'INSERT OR REPLACE INTO agent_skills (agent_id, skill_id, ord) VALUES (?, ?, ?)',
|
||
(agent_id or '', sid, i),
|
||
)
|
||
conn.commit()
|
||
|
||
|
||
def unbind_agent(agent_id: str) -> None:
|
||
"""智能体被删掉时的清理(记忆**不删** —— 那是用户的数据,删了他会心疼)"""
|
||
init()
|
||
conn = _connect()
|
||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||
conn.execute('DELETE FROM emotions WHERE agent_id = ?', (agent_id or '',))
|
||
conn.commit()
|