Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 42 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# amrita_plugin_memory

基于向量数据库的长期记忆插件 — **三层记忆模型**:
以 ChromaDB 为存储的长期记忆插件,关键词与向量可混用 — **三层记忆模型**:

| 层 | 名称 | 类比 | 载体 | 何时使用 |
| -- | ------------- | -------------------------- | -------------------------------- | -------------------- |
| L1 | 备忘录 | 恒常激活的持久记忆 | 插件自有 ORM 表(per-uni_id 单行) | 每轮常驻注入 |
| L2 | 向量记忆层 | 语义记忆(按线索提取) | ChromaDB 向量库 | LLM 按需检索 |
| L2 | 检索记忆层 | 长尾事实(按线索提取) | ChromaDB(documents + 可选向量) | LLM 按需检索 |
| L3 | 离线巩固循环 | 默认模式网络(DMN) | 后台 ReAct Agent | 空闲窗口到达时整理 |

- **L1** — 一段千字内的用户元信息(身份、稳定偏好、用户要求的工具调用模式),由 LLM 维护,每轮注入 system prompt。
- **L2** — 向量化的长尾事实库,LLM 通过工具按需读写,ChromaDB 语义检索。
- **L2** — 长尾事实库,LLM 通过工具按需读写;默认关键词与向量混合检索,没配嵌入模型时退为纯关键词。
- **L3** — 用户聊过之后,在作息里的冷门时段触发一轮后台整理:去重、压缩、画像精炼、知识沉淀。

## 安装
Expand All @@ -18,16 +18,18 @@
ambot plugin add amrita_plugin_memory
```

前置依赖:Python 3.11–3.13 / AmritaBot 实例 / **Ollama 或 OpenAI 嵌入服务** / ChromaDB。
前置依赖:Python 3.11–3.13 / AmritaBot 实例 / ChromaDB。

> 嵌入服务是**必需**前置 —— 本插件不自带嵌入模型。
嵌入服务是**可选**的:不配置也能用,L2 自动退到关键词检索;配了则按配置走
向量或关键词与向量的混合检索。插件本身不自带嵌入模型。

## 快速开始

### 1. 配置环境变量(`.env`)

```env
VECTOR_DB_TYPE=local
# 有嵌入服务时填这三行;没有就把 EMBEDDING_ENABLED 设为 false,L2 走纯关键词检索
EMBEDDING_MODEL_URL=http://127.0.0.1:11434
EMBEDDING_MODEL_NAME=auto
EMBEDDING_PROCTOL=ollama-embed
Expand Down Expand Up @@ -107,7 +109,7 @@ L1 临近上限时把细节下放到 L2,只留指针。

工具三个:`read_memo`、`append_memo`(末尾追加)、`update_memo`(整篇替换)。

## L2 向量记忆层
## L2 检索记忆层

`scope` 表达语义,与分区键是两个维度:

Expand All @@ -120,10 +122,24 @@ L1 临近上限时把细节下放到 L2,只留指针。
插件不硬编码,升级后自动跟随;存量 Key 由启动检查幂等迁移。

每条记忆带 `user_id` / `scope` / `tags` / `importance` / `created_at`,检索支持 `top_k`
与 `importance` 过滤,结果附带距离(ChromaDB 默认 l2,越小越相似)。
与 `importance` 过滤。

时间退化分两段:检索期按 `1/(1+d) × max(0.5^(age/half_life), floor)` 重排后截回 `top_k`
(只重排不删);清理期按 importance 的寿命阈值扫描,超龄先降级,降到 `low` 仍超龄才删除。
检索有三种模式,`read_memory` 的 `mode` 参数由 LLM 按需选择:

| `mode` | 行为 |
| --- | --- |
| `auto` | 有可用嵌入模型时用 `hybrid`,否则退到 `keyword`(默认) |
| `hybrid` | 关键词 BM25 与向量各自排序,按 `vector_weight`(默认 0.6)做加权 RRF 融合 |
| `keyword` | 只走关键词,不调用嵌入服务,最小部署可用 |
| `vector` | 只走向量;没有模型时直接报错,不静默换语义 |

关键词一路不依赖分词库:英文按词、中文按二元组切分后在本地算 BM25。没有嵌入模型时,
写入改用占位向量占住 Chroma 的行,检索完全不走向量路径 —— 这也是 `EMBEDDING_ENABLED=false`
时的最小部署形态。

时间退化分两段:检索期按「相关度 × `max(0.5^(age/half_life), floor)`」重排后截回 `top_k`,
相关度在向量模式下来自距离(`1/(1+d)`)、混合模式下来自融合分(只重排不删);
清理期按 importance 的寿命阈值扫描,超龄先降级,降到 `low` 仍超龄才删除。
两段都受 `[decay].enabled` 控制。

## L3 离线巩固循环(DMN)
Expand All @@ -143,11 +159,12 @@ L1 临近上限时把细节下放到 L2,只留指针。
一分钟内补跑);任务的 `misfire_grace_time` 置空,事件循环被卡住也不会把这次运行
静默丢弃;单轮失败按 30 分钟间隔最多重试 3 次,用户再发消息会重置重试计数。

## 嵌入模型与重映射
## 嵌入模型与重映射(可选)

向量只在同一模型下可比,换模型会让旧向量静默劣化且不报错。插件在集合 metadata 里记
`sha256(protocol|model|base_url)`,每次启动校验;不一致时按 `EMBED_MISMATCH_POLICY`
处理:`auto` 备份后删集合重建重嵌,`ask` 交互确认(非 TTY 拒绝加载插件),`never` 仅告警。
处理:`auto` 备份后删集合重建重嵌,`ask` 交互确认(非 TTY 只告警),`never` 仅告警。
嵌入服务不可用时跳过重映射,不会挡住启动。
指纹只看配置,同名模型被服务端换掉检测不到,用 `ambot memory reindex` 手动处理。

---
Expand Down Expand Up @@ -190,7 +207,7 @@ L1 临近上限时把细节下放到 L2,只留指针。

| 工具 | 用途 |
| -------------------------------- | -------------------------------------- |
| `subconscious_read_memory` | 语义检索 |
| `subconscious_read_memory` | 记忆检索(关键词/向量/混合) |
| `subconscious_write_memory` | 写入新记忆 |
| `subconscious_update_memory` | 更新指定 ID 记忆 |
| `subconscious_delete_memory` | 删除指定 ID 记忆 |
Expand Down Expand Up @@ -272,7 +289,7 @@ L1 临近上限时把细节下放到 L2,只留指针。
| L1 备忘录 | `UserMemo` 表(插件自有 ORM,主键 = uni_id) | LLM 维护的常驻用户元信息(≤ `memo_max_chars`) |
| 循环元状态 | `SubconsciousState` 表(插件自有 ORM,uid=`amrita_memory`) | `total_runs`、`last_abstracts`、`pending_messages`、`knowledge_suggestions`、`penalty`、`idle_planner`(热度图)|
| Session 摘要缓存 | `LRUCache[int, str]`(最大 128 条) | session DB id → LLM 生成的摘要文本,避免重复调用 `ContextCompactor` |
| L2 记忆 | ChromaDB `amrita_user_memory` | 向量 + documents + metadatas(含嵌入指纹与分区键版本) |
| L2 记忆 | ChromaDB `amrita_user_memory` | documents + 向量 + metadatas;纯关键词部署写占位向量(含嵌入指纹与分区键版本) |
| 用户画像 | `data/amrita_plugin_memory/user_profile.md` | Markdown 文件,`summary---body` 格式,行级增量更新 |
| 全局知识库 | `data/amrita_plugin_memory/knowledge/` + `knowledge_index.json` + ChromaDB | 三方同步管理 |
| Token 统计 | `InsightsModel`(复用 Bot ORM) | 全局 prompt/completion token 累加 |
Expand Down Expand Up @@ -303,7 +320,7 @@ L1 临近上限时把细节下放到 L2,只留指针。

## 技术栈

Python 3.11–3.13 / NoneBot2 / AmritaCore,向量库 ChromaDB,嵌入走 OpenAI 或 Ollama,
Python 3.11–3.13 / NoneBot2 / AmritaCore,存储 ChromaDB,嵌入(可选)走 OpenAI 或 Ollama,
调度 nonebot_plugin_apscheduler,持久化 nonebot_plugin_orm,配置 Pydantic + uniconf。


Expand Down Expand Up @@ -331,6 +348,12 @@ sweep_enabled = true
sweep_interval_hours = 24
sweep_batch_limit = 5000

# L2 检索策略(关键词 / 向量 / 混合)
[retrieval]
default_mode = "auto"
vector_weight = 0.6
keyword_candidate_limit = 2000

# L3 离线巩固循环
[subconscious]
enabled = false
Expand Down Expand Up @@ -374,6 +397,9 @@ enable_knowledge = true
| `decay.sweep_enabled` | `true` | 是否启用分层清理 |
| `decay.sweep_interval_hours` | `24` | 分层清理周期(小时) |
| `decay.sweep_batch_limit` | `5000` | 单次清理最多扫描的记忆条数 |
| `retrieval.default_mode` | `auto` | 默认检索模式,可被 `read_memory` 的 `mode` 覆盖 |
| `retrieval.vector_weight` | `0.6` | hybrid 下向量权重,可被工具参数覆盖 |
| `retrieval.keyword_candidate_limit` | `2000` | 关键词检索单次扫描上限 |
| `per_session_memory_limit` | `100` | 单个分区(uni_id)的记忆条数上限 |
| `memo_max_chars` | `1000` | L1 备忘录字数硬上限 |
| `enabled` | `false` | 是否启用离线巩固循环(以下除 `decay.*` / `per_session_memory_limit` / `memo_max_chars` 外均在 `[subconscious]` 节) |
Expand Down Expand Up @@ -425,6 +451,7 @@ enable_knowledge = true
| `VECTOR_DB_REMOTE_HEADERS` | dict | `{}` | 远程请求头 |
| `VECTOR_DB_TENANT` | string | `default` | 租户 |
| `VECTOR_DB_DATABASE` | string | `default` | 数据库 |
| `EMBEDDING_ENABLED` | bool/(空) | (空=自动尝试) | 关闭后完全不调用嵌入服务 |
| `EMBEDDING_MODEL_URL` | string | `http://127.0.0.1:11434` | 嵌入模型地址 |
| `EMBEDDING_MODEL_NAME` | string | `auto` | 模型名 |
| `EMBEDDING_PROCTOL` | openai/ollama-embed | `ollama-embed` | 协议 |
Expand All @@ -451,6 +478,7 @@ amrita_plugin_memory/
├── permissions.py # 会话侧知识库读取授权(LP 节点 / 超级用户)
├── profile_store.py # 画像路径与 Markdown 解析(纯函数,不依赖运行时)
├── decay.py # 时间记忆退化:软衰减重排 + 分层清理判定
├── retrieval.py # 关键词 BM25 与加权 RRF 融合(纯逻辑)
├── tasks.py # 分层清理的 APScheduler 周期任务
├── vector.py # ChromaDB 封装(AsyncUserMemory / 锁池)
├── embed.py # 嵌入适配器(Ollama)
Expand Down
4 changes: 4 additions & 0 deletions amrita_plugin_memory/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from chromadb.api.models.Collection import Collection
from chromadb.api.types import Metadata

from .config import env_config
from .embedding import (
backup_collection,
compute_fingerprint,
Expand Down Expand Up @@ -117,6 +118,9 @@ def _print_scope_counts(collection: Collection) -> None:

def cmd_reindex(*, assume_yes: bool = False) -> None:
"""用当前嵌入模型全量重映射。"""
if env_config.embedding_enabled is False:
click.echo("嵌入模型已禁用(EMBEDDING_ENABLED=false),无法重映射")
raise click.Abort()
collection = _get_collection()
count = collection.count() if collection is not None else 0
if count == 0:
Expand Down
34 changes: 34 additions & 0 deletions amrita_plugin_memory/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,30 @@ class DecayConfig(BaseModel):
)


class RetrievalConfig(BaseModel):
"""L2 检索策略:关键词与向量的取舍。"""

default_mode: Literal["auto", "hybrid", "keyword", "vector"] = Field(
default="auto",
description=(
"默认检索模式:auto 在有嵌入模型时用 hybrid,否则退到 keyword;"
"hybrid 关键词与向量融合;keyword 仅关键词;vector 仅语义"
),
)
vector_weight: float = Field(
default=0.6,
ge=0.0,
le=1.0,
description="hybrid 模式下向量的权重,其余权重归关键词,默认 0.6",
)
keyword_candidate_limit: int = Field(
default=2000,
ge=100,
le=20000,
description="关键词检索单次最多扫描的记忆条数,防止大库拖慢查询",
)


class ConfigFile(BaseModel):
"""配置文件"""

Expand All @@ -196,6 +220,9 @@ class ConfigFile(BaseModel):
subconscious: SubconsciousConfig = Field(
default_factory=SubconsciousConfig, description="常驻推理循环配置"
)
retrieval: RetrievalConfig = Field(
default_factory=RetrievalConfig, description="L2 检索策略配置"
)


class EnvConfig(BaseModel):
Expand Down Expand Up @@ -226,6 +253,13 @@ class EnvConfig(BaseModel):
default="default",
description="ChromaDB向量数据库数据库名称(当且仅当vector_db_type为remote时生效)",
)
embedding_enabled: bool | None = Field(
default=None,
description=(
"是否启用嵌入模型:None 为自动尝试,请求失败后降级为仅关键词检索;"
"false 则完全不调用嵌入服务,可用最小部署"
),
)
embedding_model_url: str = Field(
default="http://127.0.0.1:11434", description="Embedding模型地址"
)
Expand Down
34 changes: 28 additions & 6 deletions amrita_plugin_memory/decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
from __future__ import annotations

import math
from collections.abc import Mapping
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from typing import Any, Literal

Importance = Literal["low", "medium", "high"]

#: importance 的序,越大寿命越长
# importance 的序,越大寿命越长
IMPORTANCE_RANK: dict[str, int] = {"low": 0, "medium": 1, "high": 2}
#: 降级链,走到尽头即清理
# 降级链,走到尽头即清理
DEMOTE_CHAIN: dict[str, str] = {"high": "medium", "medium": "low"}

_SECONDS_PER_DAY = 86400.0
Expand Down Expand Up @@ -138,24 +138,46 @@ def rerank_query_result(
now: datetime | None = None,
) -> dict[str, Any]:
"""按衰减得分重排 QueryResult,并截断到 top_k;meta 里回填 decay_score。"""
ids_nested = result.get("ids")
if not ids_nested or not ids_nested[0]:
return dict(result)
size = len(ids_nested[0])
dists = _inner_list(result.get("distances"), size)
relevance = [similarity_from_distance(d) for d in dists]
return rerank_by_scores(result, relevance, top_k, base_half_life, boost, floor, now)


def rerank_by_scores(
result: Mapping[str, Any],
relevance: Sequence[float],
top_k: int,
base_half_life: float,
boost: float,
floor: float,
now: datetime | None = None,
) -> dict[str, Any]:
"""按调用方给的相关系数重排,并乘上时间衰减。

混合检索的分数是融合出来的名次分,不再是距离,所以由调用方直接给
relevance;``rerank_query_result`` 只是把它从距离推一遍。
"""
now = now or datetime.now(timezone.utc)
ids_nested = result.get("ids")
if not ids_nested or not ids_nested[0]:
return dict(result)
ids = list(ids_nested[0])
size = len(ids)
metas = _inner_list(result.get("metadatas"), size)
dists = _inner_list(result.get("distances"), size)

scores: list[float] = []
for i in range(size):
meta = metas[i] if isinstance(metas[i], dict) else {}
created = parse_created_at(meta.get("created_at"))
age = age_days(created, now) if created else 0.0
similarity = similarity_from_distance(dists[i])
sim = float(relevance[i]) if i < len(relevance) else 0.0
scores.append(
decay_score(
similarity,
sim,
age,
str(meta.get("importance", "medium")),
base_half_life,
Expand Down
12 changes: 11 additions & 1 deletion amrita_plugin_memory/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@

from .config import DATA_PATH, build_preset, env_config
from .keys import migrate_collection_keys
from .vector import MEMORY_COLLECTION_NAME, get_db_conn
from .vector import (
MEMORY_COLLECTION_NAME,
embedding_available,
get_db_conn,
mark_embedding_failed,
)

FINGERPRINT_META = "embed_fingerprint"
EMBED_PROTOCOL_META = "embed_protocol"
Expand Down Expand Up @@ -383,6 +388,10 @@ async def run_deferred_check() -> None:
global _pending_mismatch
if not _pending_mismatch:
return
if not embedding_available():
# 没有模型就无从重映射,等配置好再走启动检查
logger.warning("[Memory] 嵌入模型不可用,跳过指纹重映射,保持现有数据。")
return
reason, _pending_mismatch = _pending_mismatch, None

policy = env_config.embed_mismatch_policy
Expand All @@ -397,6 +406,7 @@ async def run_deferred_check() -> None:
try:
done = await reindex_all()
except Exception as e:
mark_embedding_failed(e)
logger.error(f"[Memory] 重映射失败,现有数据未被修改:{e}")
return
logger.info(f"[Memory] 重映射完成,共 {done} 条。")
4 changes: 2 additions & 2 deletions amrita_plugin_memory/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
if TYPE_CHECKING:
from nonebot.adapters.onebot.v11 import Event

#: 读取知识库所需的权限节点
# 读取知识库所需的权限节点
KNOWLEDGE_NODE = "memory.knowledge"
#: 管理员节点,始终持有 KNOWLEDGE_NODE
# 管理员节点,始终持有 KNOWLEDGE_NODE
ADMIN_NODE = "lp.admin"

_ENV_ADMINS = get_driver().config.superusers
Expand Down
2 changes: 1 addition & 1 deletion amrita_plugin_memory/profile_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class ProfileResult(TypedDict):
range_end: int


#: 画像文件路径
# 画像文件路径
PROFILE_PATH: Path = DATA_PATH / "user_profile.md"


Expand Down
4 changes: 2 additions & 2 deletions amrita_plugin_memory/rethinking/heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

from .schedule import DAYS, SLOT_MINUTES, SLOTS_PER_DAY, IdlePlanner, Plan

#: 超采样倍率:1x 下 12px 中文基本看不清,整体放大后出图
# 超采样倍率:1x 下 12px 中文基本看不清,整体放大后出图
SCALE = 2
_LOGICAL_W = 760
_LOGICAL_H = 814
Expand All @@ -51,7 +51,7 @@
HOT_MARK = (242, 209, 139)
NOW_MARK = (224, 122, 95)

#: 冷 -> 热的取色节点,最后一档偏暖,让热点一眼可见
# 冷 -> 热的取色节点,最后一档偏暖,让热点一眼可见
_RAMP = (
(0.0, (26, 34, 44)),
(0.3, (32, 62, 90)),
Expand Down
4 changes: 2 additions & 2 deletions amrita_plugin_memory/rethinking/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@
from .types import SessionSummary

_STATE_UID = "amrita_memory"
#: 重排节流窗口(秒)
# 重排节流窗口(秒)
_REPLAN_THROTTLE_SECONDS = 60.0
#: 单轮失败后的重试间隔(分钟)与连续重试上限,超限就等用户下一条消息
# 单轮失败后的重试间隔(分钟)与连续重试上限,超限就等用户下一条消息
_RETRY_DELAY_MINUTES = 30
_MAX_RUN_RETRIES = 3
_LEGACY_REPO_UID = (
Expand Down
Loading
Loading