feat: V1记忆系统支持、管理员记忆编辑及对话记忆注入开关
- 新增 V1 记忆系统(memory.json)支持:提取结果强制中文、历史字段修复为增量累积日志 - 用户设置页面:V1 模式下新增 agent 选择器,可查看各 agent 的私有记忆 - 管理员记忆页面:区分 V1/V2 渲染,V1 支持完整 CRUD(用户画像/历史摘要/事实记录) - 后端新增 V1 记忆 CRUD API(sections/facts),前端同步添加对应 hooks 和 API 调用 - 新建专家页面:标记 bootstrap 线程类型,跳过记忆保存,侧边栏过滤该类线程 - 输入框工具栏新增「记忆」开关:关闭时 V1/V2 均不注入,开启时按 config.yaml 版本正常注入 - 修复 agent 目录不存在时的 FileNotFoundError,回退至默认配置 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
d59e0514b3
commit
b3a39cbdf7
27 files changed
+2725
-92
No files matched your search
+161
@@ -0,0 +1,161 @@
|
||||
"""Memory V1 — 原版 DeerFlow JSON-based MemoryProvider 实现。
|
||||
|
||||
存储格式:``{base_dir}/users/{user_id}/memory.json``(经 FileMemoryStorage 管理)
|
||||
JSON 结构使用嵌套 ``{summary, updatedAt}`` 对象,与原版 DeerFlow 完全一致。
|
||||
|
||||
LLM 在 V1 模式下不调用 memory 工具 —— 事实完全由异步 LLM 提取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from deerflow.agents.memory.provider import MemoryProvider
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _FakeMsg:
|
||||
"""轻量 message 对象,用于将文本传给原版 format_conversation_for_update。"""
|
||||
__slots__ = ("type", "content")
|
||||
|
||||
def __init__(self, type_: str, content: str) -> None:
|
||||
self.type = type_
|
||||
self.content = content
|
||||
|
||||
|
||||
class V1BuiltinProvider(MemoryProvider):
|
||||
"""原版 DeerFlow V1 记忆 provider。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
max_facts: int = 100,
|
||||
fact_confidence_threshold: float = 0.7,
|
||||
debounce_seconds: int = 30,
|
||||
model_name: str = "",
|
||||
token_budget: int = 2000,
|
||||
) -> None:
|
||||
self._max_facts = max_facts
|
||||
self._confidence_threshold = fact_confidence_threshold
|
||||
self._debounce_seconds = debounce_seconds
|
||||
self._model_name = model_name
|
||||
self._token_budget = token_budget
|
||||
|
||||
self._user_id: str = ""
|
||||
self._thread_id: str = ""
|
||||
self._agent_id: str | None = None
|
||||
self._frozen_block: str = ""
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "v1_builtin"
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def initialize(
|
||||
self,
|
||||
*,
|
||||
user_id: str,
|
||||
agent_id: str | None = None,
|
||||
thread_id: str | None = None,
|
||||
base_dir: str,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
_ = base_dir # FileMemoryStorage uses get_paths() internally
|
||||
self._user_id = user_id
|
||||
self._thread_id = thread_id or ""
|
||||
self._agent_id = agent_id
|
||||
self._frozen_block = self._build_frozen_block()
|
||||
|
||||
# ---- 系统提示词 -------------------------------------------------------
|
||||
|
||||
def _build_frozen_block(self) -> str:
|
||||
"""从 memory.json 读取数据,用 format_memory_for_injection 渲染注入块。
|
||||
|
||||
当 agent_id 已知时加载 per-agent 记忆;否则加载用户级记忆。
|
||||
"""
|
||||
try:
|
||||
from deerflow.agents.memory.v1.prompt import format_memory_for_injection
|
||||
from deerflow.agents.memory.v1.storage import get_memory_storage
|
||||
|
||||
data = get_memory_storage().load(
|
||||
agent_name=self._agent_id or None,
|
||||
user_id=self._user_id,
|
||||
)
|
||||
text = format_memory_for_injection(data, max_tokens=self._token_budget)
|
||||
if not text:
|
||||
return ""
|
||||
return f"<memory>\n{text}\n</memory>"
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("V1 provider 加载 memory.json 失败: %s", exc)
|
||||
return ""
|
||||
|
||||
def system_prompt_block(self) -> str:
|
||||
return self._frozen_block
|
||||
|
||||
# ---- 召回 / 写入 ------------------------------------------------------
|
||||
|
||||
def prefetch(self, query: str, *, thread_id: str = "") -> str:
|
||||
# V1 无动态召回,静态 snapshot 已在 system_prompt_block 里
|
||||
return ""
|
||||
|
||||
def sync_turn(
|
||||
self,
|
||||
user_content: str,
|
||||
assistant_content: str,
|
||||
*,
|
||||
thread_id: str = "",
|
||||
turn_index: int | None = None,
|
||||
) -> None:
|
||||
"""把本轮对话加入防抖队列,等待 LLM 异步提取事实。"""
|
||||
if not user_content.strip() and not assistant_content.strip():
|
||||
return
|
||||
try:
|
||||
from deerflow.agents.memory.v1.queue import get_memory_queue
|
||||
|
||||
msgs = [
|
||||
_FakeMsg("human", user_content),
|
||||
_FakeMsg("ai", assistant_content),
|
||||
]
|
||||
queue = get_memory_queue()
|
||||
queue.add(
|
||||
thread_id=thread_id or self._thread_id,
|
||||
messages=msgs,
|
||||
user_id=self._user_id,
|
||||
agent_name=self._agent_id or None,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("V1 provider sync_turn 入队失败: %s", exc)
|
||||
|
||||
# ---- 工具 (V1 不暴露工具给 LLM) -------------------------------------
|
||||
|
||||
def get_tool_schemas(self) -> list[dict[str, Any]]:
|
||||
return []
|
||||
|
||||
# ---- API 读取接口 (供 Gateway router 用) -----------------------------
|
||||
|
||||
def read_v1_data(self) -> dict[str, Any]:
|
||||
"""读取 memory.json 的当前内容(实时读磁盘,非 frozen snapshot)。
|
||||
|
||||
当 agent_id 已知时读取 per-agent 记忆;否则读用户级记忆。
|
||||
"""
|
||||
from deerflow.agents.memory.v1.storage import get_memory_storage
|
||||
return get_memory_storage().load(
|
||||
agent_name=self._agent_id or None,
|
||||
user_id=self._user_id,
|
||||
)
|
||||
|
||||
def fact_count(self) -> int:
|
||||
try:
|
||||
return len(self.read_v1_data().get("facts", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return 0
|
||||
|
||||
def usage_text(self) -> str:
|
||||
return f"{self.fact_count()}/{self._max_facts} 个事实"
|
||||
|
||||
|
||||
__all__ = ["V1BuiltinProvider"]
|
||||
Reference in new issue
Block a user