"""智能体系统的数据层:**记忆 / 情绪 / 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 是安全的:这个连接只会被**创建它的那个线程**用到 # # ★ 这个 timeout 是**锁等待**(不是查询超时):另一个线程正在写时, # 等多久才放弃并抛 "database is locked"。 # 它以前写死 10 秒 —— 对拍脚本抓到的硬编码。现在复用「本地接口请求」 # 那一项:语义最接近(都是"本机内部等一等"),而且用户调它是有意义的 # (老设备上几千条记忆的整理会长时间占着写锁)。 import timeouts as _timeouts wait = float(_timeouts.get('kernelLocal') or 10) conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=max(1.0, wait)) 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 pinned DESC, 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()