mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-08-14 08:49:00 +00:00
* feat(memory): pluggable + self-contained memory system (MemoryManager plan phases 1 & 2) Phase 1 — Pluggable (steps 0-10): - ABC MemoryManager (9 methods) + singleton factory + drop-in backend discovery - DeerMem default backend with core/ (storage/queue/updater/prompt/message_processing) - NoopMemoryManager backend (proves pluggability) - All call sites (middleware/hook/prompt/gateway/client/app) routed through manager - hasattr capability probing for DeerMem-internal methods (no hard imports) - MemoryConfig gains manager_class field; shared vs DeerMem-private annotated Phase 2 — Self-contained DeerMem (steps 11-18): - backend_config passthrough + DeerMemConfig (all DeerMem-private fields moved off MemoryConfig) - DI: DeerMem owns storage/queue/updater/llm as instance attributes (no global singletons) - Storage independence: core/paths.py with own root (~/.deermem or ), factory auto-injects deer-flow's runtime_home() as absolute base_dir (zero-config) - LLM independence: core/llm.py via langchain init_chat_model (no create_chat_model) - Trace independence: optional tracing_callback replaces inject_langfuse_metadata/request_trace_context - Message processing independence: hide_from_ui default-skip + optional should_keep_hidden_message hook - Internal imports → relative (only deer_mem.py ABC import is host-relative) - Carrier (deer_mem.py adapter) / portable (deermem/ config+core) split - New tests: test_deermem_self_contained + test_memory_manager_pluggable; all memory tests migrated - Other-agent demo: samples/other_agent_demo/ + automated portability test - config.example.yaml memory section updated to phase-2 schema * feat(memory): port consolidation + staleness fix into self-contained DeerMem; phase-2 host hooks Port upstream #3996 (memory consolidation) and #3993 (staleness KeyError fix) from origin/MemoryManager into the pluggable, self-contained DeerMem structure (backends/deermem/deermem/), adapted to the DI MemoryUpdater (config injected, not get_memory_config globals): - DeerMemConfig: add consolidation_enabled (opt-in, default false) / consolidation_min_facts / consolidation_max_groups_per_cycle / consolidation_max_sources - prompt.py: factsToConsolidate JSON field + {consolidation_section} placeholder + CONSOLIDATION_PROMPT constant - updater.py: _coerce_source_confidence / _select_consolidation_candidates / _build_consolidation_section module helpers (matching the existing _select_stale_candidates style); consolidation normalization in _normalize_memory_update_data; consolidation apply in _apply_updates (after max_facts trim, with apply-time guardrails mirroring staleness); staleness KeyError fix (f["id"] -> f.get("id") is not None) applied to both the staleness guardrail and the consolidation allowed_source_ids comprehension - config.example.yaml: consolidation section under memory.backend_config - tests/test_memory_consolidation.py: 40 DI-adapted tests (running, not skipped) incl. the staleness KeyError regression Also includes in-flight phase-2 host-integration work: storage_path semantics (any absolute/relative value = root dir) and host-default tracing_callback / should_keep_hidden_message hooks injected into backend_config by the factory. Co-Authored-By: Claude <noreply@anthropic.com> * feat(memory): add noop backend template and backends guide - backends/noop/: complete drop-in template (config.py with zero deer-flow imports, noop_manager.py with a 6-step new-backend walkthrough in its docstring, commented optional fact-CRUD capabilities). - backends/README.md: which files to touch when adding/swapping a backend, the 5-item backend contract, and common pitfalls. - manager.py: generalize backend examples in comments (drop mem0-specific references). Co-Authored-By: Claude <noreply@anthropic.com> * fix(frontend): guard formatTimeAgo against invalid timestamps Return a neutral placeholder when the input date is invalid (e.g. an empty lastUpdated from a backend with no memories) instead of throwing 'Invalid time value' from date-fns. Co-Authored-By: Claude <noreply@anthropic.com> * feat(memory): wire tool-driven memory mode through the MemoryManager ABC tools.py (memory_search/add/update/delete) now calls get_memory_manager() instead of the removed host memory module, so tool mode (memory.mode: tool) works for any backend. DeerMem.search is implemented (case-insensitive substring match, ranked by confidence) as a stand-in for the planned semantic retrieval; noop.search returns [] (unchanged). Fact-CRUD tools use getattr+callable probing -- backends lacking those ops (noop) get a clear JSON error instead of crashing. Tests: test_memory_tools rewired to mock the manager (handler tests) + TestModeGating retained; test_memory_search now covers DeerMem.search; pluggable stubs test updated (search no longer a stub). Co-Authored-By: Claude <noreply@anthropic.com> * fix: resolve lint errors (import sorting, type annotation quotes, E402 in skipped tests) * docs: restore explanatory comments in config.example.yaml memory section * fix(security): port html-escape memory facts fix (#4097) to vendored DeerMem prompt.py * fix(memory): address review + port dropped upstream memory fixes Review blockers (vendored DeerMem): - #4044 restore _escape_memory_for_prompt (current_memory blob in MEMORY_UPDATE_PROMPT) - prevents </current_memory> breakout - #4028 html.escape staleness-section cat/content in _build_staleness_section - #4119 add _escape_summary for injection-path summaries (Work/Personal/ Current Focus/Recent/Earlier/Background) - default-model silent no-op: factory injects host default chat model via a new host_llm slot (create_chat_model(name=None)); DeerMem prefers host_llm over build_llm(model). Zero-config extraction works out of the box again - MemoryConfigResponse: fix stale docstring (backend-agnostic shape; DeerMem knobs live under backend_config, not top-level - restoring flat would re-couple the API to DeerMem). Frontend audited: does not read /memory/config - _host_default_tracing_callback: restore langfuse assistant_id/environment - search: push category onto the ABC signature; DeerMem filters BEFORE the top_k slice (was filtered client-side after slicing -> starved results) - _do_update_memory_sync: split into wrapper+impl; bind trace_id into the request-trace ContextVar on the Timer/executor worker via a new trace_context_manager host hook (None trace_id left unbound - no fabrication) - client.py fact-CRUD now passes user_id (was writing to the global bucket while get_memory reads per-user) - _resolve_manager_class: fail-fast (raise ValueError) on an unresolved explicit manager_class instead of silently falling back to DeerMem (memory is persistent state - a wrong store is a silent data-integrity footgun) Upstream memory fixes dropped by the host->vendored rename conflict, re-ported to backends/deermem/deermem/core/ (+ deer_mem.py): - #4073 queue busy-timer-spin -> _reprocess_pending flag (core/queue.py) - #4074 null source.confidence in staleness -> _coerce_source_confidence (core/updater.py: _build_staleness_section + _apply_updates stale sort) - #4075 factsToRemove is optional (drop from _REQUIRED_MEMORY_UPDATE_TOP_LEVEL_KEYS) - #4076 null confidence in search ranking -> _coerce_source_confidence (deer_mem.py DeerMem.search) host_llm + trace_context_manager are host-injected via backend_config (factory in manager.py), keeping backends/deermem/ at exactly one `from deerflow` line (the ABC contract) - portability test preserved. Co-Authored-By: Claude <noreply@anthropic.com> * fix: resolve lint errors (F541 f-string without placeholders, E501 line too long) * fix(memory): restore hide_from_ui clarification preservation, expose mode Two memory-system fixes (F541/E501 lint was already fixed on this branch): - filter_messages_for_memory: restore default preservation of well-formed human_input_response clarification answers (v2 regression). The self-containment refactor made the bare function skip ALL hide_from_ui when no hook was passed, but upstream preserves well-formed clarification responses by default (test_hide_from_ui_human_input_response_is_preserved). Inline a host-agnostic _is_human_clarification_response mirror of read_human_input_response as the default keep-decision; the host-injected should_keep_hidden_message hook still overrides (production path unchanged). Portable package stays zero `from deerflow`. - /memory/config: expose `mode` (middleware|tool) in MemoryConfigResponse + the config/status endpoints + client.get_memory_config. mode is a host- shared, behavior-determining field missing from the response projection. Sync tests (mock .mode; e2e assert mode present). - Align manager_class field docstring with fail-fast behavior. Tests: filter/self-contained/portability (35) + memory-config (4) pass; ruff clean. Co-Authored-By: Claude <noreply@anthropic.com> * fix(memory): resolve ruff format failures in memory module + tests `make lint` runs `ruff format --check` in addition to `ruff check`; 8 memory files had pending format changes -- 7 pre-existing (deer_mem, updater, tools, test_memory_queue/router/search/tools) + message_processing from the hide_from_ui fix. Apply `ruff format`: whitespace/wrapping only, no logic change. 109 memory tests pass; ruff check + format --check both clean. Co-Authored-By: Claude <noreply@anthropic.com> * fix(memory): address PR review - legacy field migration, fact_id contract, path/docs Address willem-bd's review on PR head bc8bf0d4 (risk:high, persistent state): - config: auto-migrate pre-abstraction top-level memory.* DeerMem fields (storage_path, max_facts, debounce_seconds, model_name, token_counting, staleness_*, consolidation_*) into backend_config on load + warn, so an upgrade does NOT silently revert customized settings (was: silent extra='ignore' drop). model_name -> backend_config.model.model. Unknown top-level keys warned. - factory: resolve a relative backend_config.storage_path against runtime_home() (base_dir-relative, CWD-independent) to preserve pre-abstraction semantics; paths.py stays portable (no runtime_home import). - tools: memory_add uses the fact_id returned directly by create_fact instead of re-deriving it via content-key matching (coupled the tool to the backend's content normalization; could misreport a storage cap). create_fact now returns (memory_data, fact_id); gateway/client/tool updated. Fix terse {"error":"content"} -> {"error":"empty content"}. - app.py: update stale token_counting=="char" warm-up comment to point at manager.warm (DeerMem.warm re-checks char and returns early). - router: comment explaining reload_memory silent fallback vs fact 501 asymmetry (read-only degrade vs write fail-loud). - CHANGELOG: document breaking changes (/memory/config + client.get_memory_config shape flat->backend_config; custom storage_class path moved + __init__ must accept config) and the legacy-field auto-migration. - tests: add regression test pinning the per-user memory path ({storage_path}/users/{safe_user_id}/memory.json == host make_safe_user_id) across the abstraction; update create_fact mocks for (memory_data, fact_id). Tests: 273 passed (memory suite); ruff check + format clean. Co-Authored-By: Claude <noreply@anthropic.com> * fix(memory): address PR review - storage_path, max_facts, tracing, parsing Six review findings (willem-bd), each verified against upstream: - storage_path semantics (file -> root dir): migration drops file-style (.json) legacy values with a warning; factory raises if storage_path resolves to an existing file (avoid silent NotADirectoryError write failure). CHANGELOG + config.example.yaml comment updated. - create_memory_fact enforces max_facts again (via _trim_facts_to_max) and returns (memory, None) when the cap evicts the new fact; memory_add tool reports "not stored", client raises ValueError, POST /memory/facts -> 409. - max_facts trim uses _coerce_source_confidence (was raw f.get("confidence", 0) -> TypeError on non-float imported/legacy confidence, swallowed as silent update failure). - memory-tracing assistant_id restored to "memory_agent" (was "lead-agent" copy-paste; matches upstream + DeerMem run_name). - _is_human_clarification_response cross-checked against read_human_input_response (drift guard test). - empty-string legacy values skipped silently in migration (narrow fix, not broad "if not value" which would skip explicit bool False). 8 new regression tests. make lint + 406 memory tests pass. Co-Authored-By: Claude <noreply@anthropic.com> * fix(memory): address internal review - storage fail-fast, build_llm degrade, config warn, noop template Addresses 4 findings from the PR #4122 internal supplemental review (parallel to willem-bd's review, no overlap): - create_storage fail-fast: a misspelled/unimportable storage_class now raises ValueError instead of silently falling back to FileMemoryStorage. Memory is persistent state, so a wrong store is a data-integrity footgun; mirrors the existing manager_class resolution policy. (storage.py) - noop template create_fact signature: the commented template used keyword-only `content` and returned a bare dict, while DeerMem's actual create_fact takes positional `content` and returns tuple[dict, str|None] (the memory_add tool passes content positionally; gateway/client/tools all tuple-unpack). A backend copied from the template would 500 on fact-CRUD. Template fixed; delete_fact/update_fact templates left (callers compatible). (noop_manager.py) - build_llm graceful degrade: wrap init_chat_model in try/except, degrade to None + WARNING on failure (mirroring _host_default_llm) so a misconfigured explicit model does not crash app startup -- non-LLM memory ops still work and an update raises at runtime with the error logged. (llm.py) - from_backend_config unknown-key warning: log a WARNING for unknown backend_config keys (mirrors the host layer's load_memory_config_from_dict) so a typo like `storage_pat` does not silently fall back to the default and write memory to an unintended location. (config.py) Tests: rewrote 3 create_storage fallback tests to expect ValueError; added 4 tests (build_llm zero-config/degrade, from_backend_config warn/silent). make lint green; full memory suite passes. Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: lllyfff <2281215061@qq.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: lllyfff <122260771+lllyfff@users.noreply.github.com>
457 lines
20 KiB
Python
457 lines
20 KiB
Python
"""Memory manager contract + pluggable backend factory.
|
|
|
|
This module is the shared, backend-agnostic core of the memory package. It
|
|
defines the :class:`MemoryManager` interface (9 methods) that every backend
|
|
implements, plus a singleton :func:`get_memory_manager` factory that resolves
|
|
the active backend from ``MemoryConfig.manager_class``.
|
|
|
|
Swap backend = drop a ``backends/<name>/`` folder exposing ``MANAGER_CLASS``
|
|
and set ``manager_class: <name>``. Nothing else in deer-flow changes.
|
|
|
|
Scope note: this phase is *pluggable only*, not black-box. Agent-side
|
|
conventions (``enabled`` gating at call sites, ``<memory>`` wrapping in
|
|
``_get_memory_context``) stay where they are; they are backend-agnostic and
|
|
do not impede pluggability.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import logging
|
|
import os
|
|
import threading
|
|
from abc import ABC, abstractmethod
|
|
from pathlib import Path
|
|
from types import ModuleType
|
|
from typing import Any
|
|
|
|
from deerflow.config.memory_config import get_memory_config
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Backend packages live in <this dir>/backends/<name>/.
|
|
_BACKENDS_DIR = Path(__file__).parent / "backends"
|
|
# Sentinel attribute each backend's __init__ exposes (a MemoryManager subclass).
|
|
_MANAGER_CLASS_ATTR = "MANAGER_CLASS"
|
|
|
|
# Singleton instance + backend-registry cache (reset together by reset_memory_manager).
|
|
# _manager_lock guards get_memory_manager()'s double-checked init (multi-threaded).
|
|
_memory_manager: MemoryManager | None = None
|
|
_backends_cache: dict[str, type[MemoryManager]] | None = None
|
|
_manager_lock = threading.Lock()
|
|
|
|
|
|
class MemoryManager(ABC):
|
|
"""Backend-neutral memory manager contract (9 methods).
|
|
|
|
Memories are bucketed per ``(agent_name, user_id)``; ``thread_id`` aligns
|
|
with the deer-flow conversation thread. The contract is deliberately
|
|
neutral so a third-party memory system can be adapted without deer-flow
|
|
code changes:
|
|
|
|
- :meth:`get_context` returns plain injection text; the *format* is the
|
|
implementation's own choice and is NOT part of the contract (DeerMem
|
|
does load + ``format_memory_for_injection``; another backend may do
|
|
its own search + formatting).
|
|
- :meth:`add` / :meth:`add_nowait` take raw conversation messages; any
|
|
filtering / correction-/reinforcement-detection is the implementation's
|
|
private concern (not on the contract).
|
|
- No facts-model assumption: a backend need not store "facts" at all.
|
|
|
|
Methods marked *stub* are part of the contract but have no caller yet in
|
|
this phase; DeerMem raises ``NotImplementedError`` for them, a future
|
|
backend (or a later DeerMem ``core/`` module) may implement them for real.
|
|
"""
|
|
|
|
def __init__(self, backend_config: dict[str, Any] | None = None) -> None:
|
|
"""Receive backend-private config (the factory passes ``backend_config``).
|
|
|
|
Default stores the raw dict; backends that need to parse it (e.g. DeerMem
|
|
into a ``DeerMemConfig``) override ``__init__``. Backends that ignore
|
|
private config (e.g. noop) inherit this unchanged.
|
|
"""
|
|
self._backend_config = backend_config
|
|
|
|
# ── Write ────────────────────────────────────────────────────────────
|
|
@abstractmethod
|
|
def add(
|
|
self,
|
|
thread_id: str,
|
|
messages: list[Any],
|
|
*,
|
|
agent_name: str | None = None,
|
|
user_id: str | None = None,
|
|
trace_id: str | None = None,
|
|
) -> None:
|
|
"""Queue a conversation for memory update (debounced, asynchronous).
|
|
|
|
Args:
|
|
thread_id: Conversation thread id.
|
|
messages: Raw conversation messages; the implementation filters
|
|
to user inputs + final assistant responses itself.
|
|
agent_name: Per-agent bucket; ``None`` = global memory.
|
|
user_id: Per-user bucket.
|
|
trace_id: Request trace id captured for memory-LLM tracing.
|
|
"""
|
|
|
|
@abstractmethod
|
|
def add_nowait(
|
|
self,
|
|
thread_id: str,
|
|
messages: list[Any],
|
|
*,
|
|
agent_name: str | None = None,
|
|
user_id: str | None = None,
|
|
) -> None:
|
|
"""Queue a conversation for *immediate* memory update (emergency flush).
|
|
|
|
Used right before summarization removes messages from state, so the
|
|
content is captured instead of lost.
|
|
"""
|
|
|
|
# ── Read ─────────────────────────────────────────────────────────────
|
|
@abstractmethod
|
|
def get_context(
|
|
self,
|
|
user_id: str | None,
|
|
*,
|
|
agent_name: str | None = None,
|
|
thread_id: str | None = None,
|
|
) -> str:
|
|
"""Return injection-ready memory text for the given bucket.
|
|
|
|
Implementations load their memory and format it however they choose;
|
|
the returned string is injected verbatim by call sites. Format
|
|
parameters are the backend's own private config (received via
|
|
``backend_config`` at construction), NOT a host config on this method.
|
|
"""
|
|
|
|
@abstractmethod
|
|
def search(
|
|
self,
|
|
query: str,
|
|
top_k: int = 5,
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
category: str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""Search the bucket's memory for facts matching ``query``; return up to
|
|
``top_k`` ranked by relevance. ``category`` (optional) filters BEFORE the
|
|
``top_k`` slice so a category-scoped search is not starved by other
|
|
categories' higher-ranked facts."""
|
|
|
|
# ── Manage ───────────────────────────────────────────────────────────
|
|
@abstractmethod
|
|
def get_memory(
|
|
self,
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Return the full memory document for the bucket."""
|
|
|
|
@abstractmethod
|
|
def delete_memory(
|
|
self,
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
) -> None:
|
|
"""Delete the entire memory document for the bucket. *stub* this phase."""
|
|
|
|
@abstractmethod
|
|
def clear_memory(
|
|
self,
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Clear the bucket's memory; return the cleared (now-empty) document."""
|
|
|
|
@abstractmethod
|
|
def import_memory(
|
|
self,
|
|
memory_data: dict[str, Any],
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Import a memory document into the bucket; return the merged result."""
|
|
|
|
@abstractmethod
|
|
def export_memory(
|
|
self,
|
|
*,
|
|
user_id: str | None = None,
|
|
agent_name: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Export the memory document for the bucket. *stub* this phase (no caller yet)."""
|
|
|
|
|
|
# ── Backend discovery (drop-in) ───────────────────────────────────────────
|
|
def _scan_backends() -> dict[str, type[MemoryManager]]:
|
|
"""Discover pluggable backends under ``backends/<name>/``.
|
|
|
|
Each subpackage that exposes a ``MANAGER_CLASS`` attribute (a
|
|
:class:`MemoryManager` subclass) is registered under its folder name.
|
|
Results are cached for the process. Folder name == backend name ==
|
|
``manager_class`` config value (drop-in contract). A backend that fails
|
|
to import is logged and skipped so a broken optional backend never breaks
|
|
the factory.
|
|
"""
|
|
global _backends_cache
|
|
if _backends_cache is not None:
|
|
return _backends_cache
|
|
|
|
registry: dict[str, type[MemoryManager]] = {}
|
|
if not _BACKENDS_DIR.is_dir():
|
|
_backends_cache = registry
|
|
return registry
|
|
|
|
for entry in sorted(_BACKENDS_DIR.iterdir()):
|
|
if not entry.is_dir() or entry.name.startswith(("_", ".")):
|
|
continue
|
|
if not (entry / "__init__.py").is_file():
|
|
continue
|
|
dotted = f"deerflow.agents.memory.backends.{entry.name}"
|
|
try:
|
|
module: ModuleType = importlib.import_module(dotted)
|
|
except Exception: # noqa: BLE001 - a broken backend must not break the factory
|
|
logger.exception("Failed to import memory backend %r; skipping", entry.name)
|
|
continue
|
|
cls = getattr(module, _MANAGER_CLASS_ATTR, None)
|
|
if cls is None:
|
|
continue
|
|
if not (isinstance(cls, type) and issubclass(cls, MemoryManager)):
|
|
logger.warning(
|
|
"Memory backend %r exposes MANAGER_CLASS=%r which is not a MemoryManager subclass; skipping",
|
|
entry.name,
|
|
cls,
|
|
)
|
|
continue
|
|
registry[entry.name] = cls
|
|
|
|
_backends_cache = registry
|
|
return registry
|
|
|
|
|
|
def _resolve_manager_class(manager_class: str) -> type[MemoryManager]:
|
|
"""Resolve a ``manager_class`` config value to a concrete class.
|
|
|
|
Resolution order:
|
|
1. Registered short name (from :func:`_scan_backends`).
|
|
2. Dotted import path (``pkg.mod:Cls`` or ``pkg.mod.Cls``).
|
|
|
|
A value that resolves to neither is a config error: raise rather than
|
|
silently fall back to a different storage backend. Memory is persistent
|
|
state, so silently substituting DeerMem when an explicit ``manager_class``
|
|
fails to resolve (typo / import error / missing attr) would route writes to
|
|
the wrong store -- a silent data-integrity footgun. Fail loud (the manager
|
|
is resolved eagerly at startup so it can be warmed) so the operator fixes
|
|
``memory.manager_class`` instead of discovering the mismatch later.
|
|
"""
|
|
registry = _scan_backends()
|
|
if manager_class in registry:
|
|
return registry[manager_class]
|
|
|
|
# Treat as a dotted path: support both "pkg.mod:Cls" and "pkg.mod.Cls".
|
|
dotted_error: str | None = None
|
|
if ":" in manager_class:
|
|
module_path, _, attr = manager_class.partition(":")
|
|
else:
|
|
module_path, _, attr = manager_class.rpartition(".")
|
|
if module_path and attr:
|
|
try:
|
|
module = importlib.import_module(module_path)
|
|
except ImportError as e:
|
|
dotted_error = f"cannot import module {module_path!r}: {e}"
|
|
else:
|
|
cls = getattr(module, attr, None)
|
|
if cls is None:
|
|
dotted_error = f"attribute {attr!r} not found in {module_path!r}"
|
|
elif not (isinstance(cls, type) and issubclass(cls, MemoryManager)):
|
|
dotted_error = f"{manager_class!r} resolved to non-MemoryManager {cls!r}"
|
|
else:
|
|
return cls
|
|
|
|
raise ValueError(
|
|
f"memory.manager_class={manager_class!r} is not a registered backend name "
|
|
f"(known: {sorted(registry)}) nor a resolvable 'pkg.mod:Cls' path" + (f": {dotted_error}" if dotted_error else "") + ". Fix memory.manager_class in config; refusing to silently fall back to a "
|
|
"different storage backend (memory is persistent state -- a wrong store is a "
|
|
"silent data-integrity footgun)."
|
|
)
|
|
|
|
|
|
# ── Host-default hooks (injected into backend_config by the factory) ──────
|
|
#
|
|
# DeerMemConfig declares ``tracing_callback`` and ``should_keep_hidden_message``
|
|
# as optional, host-agnostic slots (default ``None``). The portable package
|
|
# never names a deer-flow concept, so the host fills these slots HERE -- in the
|
|
# factory, which is host code outside ``backends/deermem/``. Backends whose
|
|
# config schema declares these slots (DeerMem) consume them via
|
|
# ``from_backend_config``'s known-field filter; others (e.g. noop) ignore
|
|
# them. An explicit value in ``backend_config`` (set programmatically) takes
|
|
# precedence and is left untouched.
|
|
#
|
|
# Imports are lazy (matching the ``runtime_home`` precedent) so this module
|
|
# stays cheap to import and so another agent vendoring the contract only has
|
|
# to edit these two helpers, not the top-level imports.
|
|
def _host_default_tracing_callback(
|
|
invoke_config: dict[str, Any],
|
|
*,
|
|
thread_id: str | None,
|
|
user_id: str | None,
|
|
trace_id: str | None,
|
|
model_name: str | None,
|
|
) -> None:
|
|
"""deer-flow default for DeerMem's ``tracing_callback`` slot.
|
|
|
|
Merges Langfuse trace metadata into ``invoke_config`` (no-op when
|
|
Langfuse is not an enabled tracing provider). Maps DeerMem's ``trace_id``
|
|
onto ``inject_langfuse_metadata``'s ``deerflow_trace_id`` kwarg -- the
|
|
name mismatch that previously made memory LLM tracing silently TypeError
|
|
is bridged here, at the host seam, so the portable package is untouched.
|
|
"""
|
|
from deerflow.tracing import inject_langfuse_metadata
|
|
|
|
inject_langfuse_metadata(
|
|
invoke_config,
|
|
thread_id=thread_id,
|
|
user_id=user_id,
|
|
assistant_id="memory_agent",
|
|
model_name=model_name,
|
|
environment=os.environ.get("DEER_FLOW_ENV") or os.environ.get("ENVIRONMENT"),
|
|
deerflow_trace_id=trace_id,
|
|
)
|
|
|
|
|
|
def _host_default_should_keep_hidden_message(additional_kwargs: Any) -> bool:
|
|
"""deer-flow default for DeerMem's ``should_keep_hidden_message`` slot.
|
|
|
|
Keep a ``hide_from_ui`` message only when it carries a human-input
|
|
clarification response, so the user's clarification is captured into
|
|
memory; drop all other hidden messages (framework-internal reminders,
|
|
view-image payloads, etc.). Restores the pre-abstraction behaviour where
|
|
``message_processing`` imported ``read_human_input_response`` directly.
|
|
"""
|
|
from deerflow.agents.human_input import read_human_input_response
|
|
|
|
return read_human_input_response(additional_kwargs) is not None
|
|
|
|
|
|
def _host_default_llm() -> Any:
|
|
"""deer-flow default for DeerMem's ``host_llm`` slot (zero-config extraction).
|
|
|
|
Builds the host's default chat model (``create_chat_model(name=None)`` ->
|
|
app default, ``attach_tracing=True`` so memory LLM calls surface in langfuse
|
|
via the metadata ``tracing_callback`` merges), mirroring pre-abstraction
|
|
``model_name: null``. Returns ``None`` if no model is available (no models
|
|
configured) so DeerMem no-ops extraction with a clear error rather than
|
|
crashing startup.
|
|
"""
|
|
try:
|
|
from deerflow.models import create_chat_model
|
|
|
|
return create_chat_model(name=None)
|
|
except Exception: # noqa: BLE001 - no default model is a config state, not a crash
|
|
logger.warning("Could not build host default model for DeerMem memory extraction; memory extraction will be disabled", exc_info=True)
|
|
return None
|
|
|
|
|
|
# ── Singleton factory ─────────────────────────────────────────────────────
|
|
def get_memory_manager() -> MemoryManager:
|
|
"""Return the singleton :class:`MemoryManager` for the active config.
|
|
|
|
Reads ``MemoryConfig.manager_class`` and resolves it via
|
|
:func:`_resolve_manager_class`. The instance is cached; call
|
|
:func:`reset_memory_manager` to force re-resolution (tests / runtime
|
|
backend switching).
|
|
"""
|
|
global _memory_manager
|
|
if _memory_manager is not None:
|
|
return _memory_manager
|
|
|
|
# deer-flow is multi-threaded: memory injection runs via asyncio.to_thread,
|
|
# the update queue fires on a Timer thread, and gateway/agent threads all
|
|
# reach here. Double-checked locking ensures only one instance is built even
|
|
# on first-call contention -- essential since backends now own stateful
|
|
# dependencies (DeerMem owns its storage/queue/updater; others may open
|
|
# connections) constructed here in __init__.
|
|
with _manager_lock:
|
|
if _memory_manager is not None:
|
|
return _memory_manager
|
|
|
|
cfg = get_memory_config()
|
|
manager_class = cfg.manager_class
|
|
cls = _resolve_manager_class(manager_class)
|
|
backend_config = dict(cfg.backend_config or {})
|
|
# Zero-config UX: default DeerMem storage to deer-flow's state dir
|
|
# (absolute, CWD-independent) so memory lands at
|
|
# {runtime_home}/users/{user_id}/memory.json (deer-flow's base_dir,
|
|
# same as pre-abstraction) unless the host explicitly sets storage_path.
|
|
if not backend_config.get("storage_path"):
|
|
from deerflow.config.runtime_paths import runtime_home
|
|
|
|
backend_config["storage_path"] = str(runtime_home())
|
|
elif not Path(backend_config.get("storage_path", "")).is_absolute():
|
|
# A relative storage_path is resolved against runtime_home() (base_dir-
|
|
# relative, CWD-independent) to preserve pre-abstraction semantics; left
|
|
# as-is it would be CWD-relative and fragile. (Resolved here in host code
|
|
# so the portable paths.py stays free of any runtime_home dependency.)
|
|
from deerflow.config.runtime_paths import runtime_home
|
|
|
|
backend_config["storage_path"] = str((Path(runtime_home()) / backend_config["storage_path"]).resolve())
|
|
# Guard: DeerMem treats storage_path as a root DIRECTORY (per-user memory
|
|
# under {storage_path}/users/{uid}/memory.json). A file-style value (e.g. a
|
|
# leftover .json file from the pre-abstraction file-path semantics) would
|
|
# make FileMemoryStorage.save's mkdir(parents=True) raise NotADirectoryError,
|
|
# caught as OSError -> silent write failure. Fail loud at startup instead
|
|
# (memory is persistent state -- a wrong root is a data-integrity footgun).
|
|
_resolved_storage_path = Path(backend_config["storage_path"])
|
|
if _resolved_storage_path.is_file():
|
|
raise ValueError(
|
|
f"memory.backend_config.storage_path={backend_config['storage_path']!r} "
|
|
f"resolves to an existing file {_resolved_storage_path}; DeerMem treats "
|
|
f"storage_path as a root DIRECTORY (per-user memory under "
|
|
f"{{storage_path}}/users/{{uid}}/memory.json). Point it at a directory."
|
|
)
|
|
# Host-default hooks: callables cannot come from YAML, so the host
|
|
# injects them here. DeerMem consumes them (known config fields);
|
|
# noop ignores them (unknown-field filter in from_backend_config).
|
|
# An explicit value (incl. ``null`` in YAML) takes precedence -> the
|
|
# host default is only filled when the key is absent.
|
|
if "tracing_callback" not in backend_config:
|
|
backend_config["tracing_callback"] = _host_default_tracing_callback
|
|
if "should_keep_hidden_message" not in backend_config:
|
|
backend_config["should_keep_hidden_message"] = _host_default_should_keep_hidden_message
|
|
# Zero-config LLM: when no memory model is configured, inject the host's
|
|
# default chat model so memory extraction works out of the box (mirrors
|
|
# pre-abstraction `model_name: null` -> app default). DeerMem prefers
|
|
# host_llm over build_llm(model); other backends ignore the slot.
|
|
model_cfg = backend_config.get("model")
|
|
if not (isinstance(model_cfg, dict) and model_cfg.get("model")) and "host_llm" not in backend_config:
|
|
backend_config["host_llm"] = _host_default_llm()
|
|
# Restore structured-log trace correlation on the memory-update worker
|
|
# thread (Timer / executor): bind trace_id into the request-trace
|
|
# ContextVar. A None trace_id is left unbound by the updater's guard.
|
|
if "trace_context_manager" not in backend_config:
|
|
from deerflow.trace_context import request_trace_context
|
|
|
|
backend_config["trace_context_manager"] = request_trace_context
|
|
_memory_manager = cls(backend_config=backend_config)
|
|
logger.info("Memory manager resolved: %s (manager_class=%r)", cls.__name__, manager_class)
|
|
return _memory_manager
|
|
|
|
|
|
def reset_memory_manager() -> None:
|
|
"""Clear the cached singleton manager and the backend registry.
|
|
|
|
The next :func:`get_memory_manager` call re-reads the config and re-scans
|
|
backends. Use this in tests or when switching backends at runtime.
|
|
"""
|
|
global _memory_manager, _backends_cache
|
|
with _manager_lock:
|
|
_memory_manager = None
|
|
_backends_cache = None
|