Skip to content

Memory store tool

MemoryStoreAction

Bases: str, Enum

Action for the memory store tool.

Source code in dynamiq/nodes/tools/memory_store_tool.py
58
59
60
61
62
63
64
65
66
class MemoryStoreAction(str, Enum):
    """Action for the memory store tool."""

    LIST = "list"
    SEARCH = "search"
    READ = "read"
    WRITE = "write"
    EDIT = "edit"
    DELETE = "delete"

MemoryStoreTool

Bases: Node

The agent's memory: notes that outlive the conversation.

One tool with actions rather than several tools, following SkillsTool. Its backend is a MemoryStore — deliberately not a FileStore, so memory never shares a path namespace or a tool with the agent's working files.

Source code in dynamiq/nodes/tools/memory_store_tool.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
class MemoryStoreTool(Node):
    """The agent's memory: notes that outlive the conversation.

    One tool with actions rather than several tools, following ``SkillsTool``. Its backend is a
    ``MemoryStore`` — deliberately not a ``FileStore``, so memory never shares a path namespace or a
    tool with the agent's working files.
    """

    group: Literal[NodeGroup.TOOLS] = NodeGroup.TOOLS
    action_type: ActionType = ActionType.FILE_OPERATION
    # Agent machinery, not an outside-world integration: never swept in by MockPolicy.ALL.
    is_mockable: ClassVar[bool] = False
    name: str = "memory-store"
    description: str = DESCRIPTION
    backend: MemoryStore = Field(..., description="Store holding the agent's memories.")
    write_enabled: bool = Field(default=True, description="Whether the agent may change memories.")
    user_id: str | None = Field(
        default=None,
        description="End user whose memories these are, bound at construction. An agent rebuilds "
        "the tool per run from the run's user_id, so callers only pass it to `agent.run(...)`.",
    )

    model_config = ConfigDict(arbitrary_types_allowed=True)
    input_schema: ClassVar[type[MemoryStoreToolInputSchema]] = MemoryStoreToolInputSchema

    # The content hash of each memory as this run last read or wrote it, "" from a store that reports
    # none. A write over a memory changed since, or over one this run never saw, is refused instead of
    # erasing someone else's change.
    _seen: dict[str, str] = PrivateAttr(default_factory=dict)

    @model_validator(mode="after")
    def describe_memories(self):
        """Tell the model what each memory holds, straight from the stores themselves.

        The backend already knows — a composite composes its routes' descriptions — so there is no
        parallel structure to keep in sync and no need to know whether the backend is composite.
        """
        listing = render_namespaces(self.backend.describe_namespaces())
        if listing and "Your memories:" not in self.description:
            self.description = f"{self.description}\n\nYour memories:\n{listing}"
        if not self.write_enabled and READ_ONLY_NOTE not in self.description:
            self.description += READ_ONLY_NOTE
        limit = self.backend.content_limit()
        if self.write_enabled and limit and LIMIT_NOTE_START not in self.description:
            self.description += (
                f"{LIMIT_NOTE_START} {limit:,} characters: split one that would grow past that by topic."
            )
        return self

    @property
    def to_dict_exclude_params(self):
        return super().to_dict_exclude_params | {"backend": True}

    def reset_run_state(self):
        self._seen = {}

    def execute(
        self, input_data: MemoryStoreToolInputSchema, config: RunnableConfig | None = None, **kwargs
    ) -> dict[str, Any]:
        config = ensure_config(config)
        check_cancellation(config)
        self.run_on_node_execute_run(config.callbacks, **kwargs)

        action = input_data.action
        if action in MUTATING_ACTIONS and not self.write_enabled:
            raise ToolExecutionException(
                f"This memory is read-only; '{action.value}' is not available. You can list and read it.",
                recoverable=True,
            )

        try:
            user_id = self.user_id
            if action == MemoryStoreAction.LIST:
                return self._list(input_data.path or "", user_id)
            if action == MemoryStoreAction.SEARCH:
                return self._search(input_data.query, input_data.path or "", user_id)
            if action == MemoryStoreAction.READ:
                return self._read(input_data.path, user_id)
            if action == MemoryStoreAction.WRITE:
                return self._write(input_data.path, input_data.content, user_id)
            if action == MemoryStoreAction.EDIT:
                return self._edit(input_data, user_id)
            return self._delete(input_data.path, user_id)
        except ToolExecutionException:
            raise
        except MemoryStoreError as e:
            # Includes "not in any memory", which names the valid prefixes: worth relaying verbatim.
            raise ToolExecutionException(str(e), recoverable=True) from e
        except Exception as e:
            logger.error(f"Tool {self.name} - {self.id}: {action.value} failed. Error: {e}")
            raise ToolExecutionException(
                f"Memory {action.value} failed: {e}. Please analyze the error and take appropriate action.",
                recoverable=True,
            ) from e

    def _list(self, prefix: str, user_id: str | None = None) -> dict[str, Any]:
        """List memories, grouped under what each one holds.

        The grouping matters: a bare path like ``team/naming.md`` gives the model nothing to judge
        relevance by, so it lists and then reads nothing. Naming the memory the path belongs to puts
        that judgement where the decision is made, the same way the tool description does.
        """
        entries = self.backend.list(prefix, user_id)
        if not entries:
            where = f" under '{prefix}'" if prefix else ""
            return {"content": f"No memories{where} yet."}

        described = _recently_described(entries, LIST_DESCRIBED_CHARS)

        namespaces = self.backend.describe_namespaces()
        grouped: dict[str, list[str]] = {}
        for entry in entries:
            owner = max(
                (ns for ns in namespaces if ns and entry.path.startswith(ns)),
                key=len,
                default="",
            )
            line = _describe(entry) if entry.path in described else f"{entry.path} ({entry.size} chars)"
            grouped.setdefault(owner, []).append(f"  - {line}")

        sections = []
        for owner, lines in grouped.items():
            heading = f"{owner} — {namespaces[owner]}" if owner and namespaces.get(owner) else (owner or "Memories")
            sections.append(f"{heading}\n" + "\n".join(lines))
        if len(described) < len(entries):
            sections.append(
                f"{len(entries)} memories; the {len(described)} changed most recently are described. 'search' "
                "for a topic, or 'list' a folder to see what each of its memories holds."
            )
        return {"content": "\n".join(sections), "paths": [entry.path for entry in entries]}

    def _read(self, path: str, user_id: str | None = None) -> dict[str, Any]:
        """The memory, then the memories around it, so following a link costs one read, not a search.

        Paths only: the model has just listed what each one holds.
        """
        try:
            note = self.backend.read_note(path, user_id)
        except MemoryNotFoundError:
            self._seen.pop(path, None)
            raise ToolExecutionException(
                f"No memory at '{path}'. Use action 'list' to see what exists.", recoverable=True
            ) from None
        self._seen[path] = note.content_hash
        linked = [link.path for link in note.links if link.path]
        unresolved = [link.target for link in note.links if not link.path]
        around = []
        if linked:
            around.append(LINKS_TO + ", ".join(linked))
        if unresolved:
            around.append(UNRESOLVED_LINKS + ", ".join(unresolved))
        if note.backlinks:
            around.append(LINKED_FROM + ", ".join(note.backlinks))
        if not around:
            return {"content": note.content}
        # Marked apart, so a model rewriting the memory from this output does not copy them into it.
        return {"content": note.content + LINKS_MARKER + "\n".join(around)}

    def _search(self, query: str, prefix: str, user_id: str | None = None) -> dict[str, Any]:
        """Hits with what each memory holds and the passage that matched: enough to pick what to read."""
        hits = self.backend.search(query, prefix, SEARCH_LIMIT, user_id)
        if not hits:
            where = f" under '{prefix}'" if prefix else ""
            return {"content": f"No memories{where} mention '{query}'. Try other words, or 'list'."}
        lines = []
        for hit in hits:
            lines.append(f"- {_describe(hit)}")
            if hit.snippet:
                lines.append(f"  > {hit.snippet}")
        return {"content": "\n".join(lines), "paths": [hit.path for hit in hits]}

    def _write(self, path: str, content: str, user_id: str | None = None) -> dict[str, Any]:
        """Write, then name memories on the same topic, so the next step merges instead of duplicating.

        Best effort: a failed search must not turn a saved memory into a failed call.
        """
        entry = self._store(path, _without_links(content), user_id)
        message = f"Remembered in '{entry.path}'."
        # Within the memory that holds it: links resolve inside one memory, and a route's name is not a topic.
        scope = self.backend.scope_of(entry.path)
        try:
            # The file name, not its folders: every memory in a folder holds the folder's name in its path.
            topic = " ".join(filter(None, [entry.description, _path_words(entry.path.rsplit("/", 1)[-1])]))
            hits = self.backend.search(topic, scope, RELATED_LIMIT + 1, user_id)
        except MemoryStoreError as e:
            logger.warning(f"Tool {self.name} - {self.id}: related-memory search failed. Error: {e}")
            hits = []
        related = [hit.path for hit in hits if hit.path != entry.path and hit.score >= RELATED_MIN_SCORE]
        related = related[:RELATED_LIMIT]
        if related:
            message += (
                " Memories on nearby topics: " + ", ".join(related) + ". If one covers the same topic, merge into it; "
                f"if they relate, link them by name, like [[{related[0].rsplit('/', 1)[-1].removesuffix('.md')}]]."
            )
        return {"content": message}

    def _edit(self, input_data: MemoryStoreToolInputSchema, user_id: str | None = None) -> dict[str, Any]:
        path, find, replace = input_data.path, input_data.find, input_data.replace
        try:
            note = self.backend.read_note(path, user_id)
        except MemoryNotFoundError:
            raise ToolExecutionException(
                f"No memory at '{path}' to edit. Use action 'write' to create it.", recoverable=True
            ) from None
        current = note.content

        # Candidate positions, not str.count: overlapping matches ("---" in "-----") are what
        # make a find string ambiguous, and counting only non-overlapping ones would let an
        # ambiguous edit through and persist it.
        positions = find_positions(current, find)
        if not positions:
            raise ToolExecutionException(
                f"'{find}' does not appear in '{path}', so nothing was changed.", recoverable=True
            )
        if len(positions) > 1 and not input_data.replace_all:
            raise ToolExecutionException(
                f"'{find}' appears {len(positions)} times in '{path}'. Include more surrounding text to "
                f"make it unique, or set 'replace_all' to change every occurrence.",
                recoverable=True,
            )

        updated = current.replace(find, replace) if input_data.replace_all else current.replace(find, replace, 1)
        self._seen[path] = note.content_hash
        self._store(path, updated, user_id)
        # How many a replacement actually consumes is str.count's question, not the candidates'.
        changed = current.count(find) if input_data.replace_all else 1
        return {"content": f"Updated '{path}' ({changed} replacement{'s' if changed > 1 else ''})."}

    def _store(self, path: str, content: str, user_id: str | None) -> MemoryEntry:
        """Write over only what this run has seen: the content it read, or no memory at all."""
        seen = self._seen.get(path)
        try:
            if seen == "":
                entry = self.backend.write(path, content, user_id)
            else:
                entry = self.backend.write_if_unchanged(path, content, seen, user_id)
        except MemoryChangedError:
            if seen is None:
                raise ToolExecutionException(
                    f"'{path}' already exists and you haven't read it here, so nothing was saved. Read it, then "
                    "apply your change to what it says.",
                    recoverable=True,
                ) from None
            raise ToolExecutionException(
                f"'{path}' changed since you read it, so nothing was saved. Read it again and apply your change "
                "to what it says now.",
                recoverable=True,
            ) from None
        # A store that reports no hash on write still holds what was written, so the next write stays
        # conditional.
        self._seen[path] = entry.content_hash or content_hash(content)
        return entry

    def _delete(self, path: str, user_id: str | None = None) -> dict[str, Any]:
        """Delete over only what this run has seen, when it has read the memory; otherwise delete as asked."""
        seen = self._seen.get(path)
        try:
            if seen:
                deleted = self.backend.delete_if_unchanged(path, seen, user_id)
            else:
                deleted = self.backend.delete(path, user_id)
        except MemoryChangedError:
            raise ToolExecutionException(
                f"'{path}' changed since you read it, so it was not deleted. Read it again and decide whether it "
                "should still go.",
                recoverable=True,
            ) from None
        self._seen.pop(path, None)
        return {"content": f"Deleted '{path}'." if deleted else f"There was no memory at '{path}'."}

describe_memories()

Tell the model what each memory holds, straight from the stores themselves.

The backend already knows — a composite composes its routes' descriptions — so there is no parallel structure to keep in sync and no need to know whether the backend is composite.

Source code in dynamiq/nodes/tools/memory_store_tool.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@model_validator(mode="after")
def describe_memories(self):
    """Tell the model what each memory holds, straight from the stores themselves.

    The backend already knows — a composite composes its routes' descriptions — so there is no
    parallel structure to keep in sync and no need to know whether the backend is composite.
    """
    listing = render_namespaces(self.backend.describe_namespaces())
    if listing and "Your memories:" not in self.description:
        self.description = f"{self.description}\n\nYour memories:\n{listing}"
    if not self.write_enabled and READ_ONLY_NOTE not in self.description:
        self.description += READ_ONLY_NOTE
    limit = self.backend.content_limit()
    if self.write_enabled and limit and LIMIT_NOTE_START not in self.description:
        self.description += (
            f"{LIMIT_NOTE_START} {limit:,} characters: split one that would grow past that by topic."
        )
    return self

MemoryStoreToolInputSchema

Bases: BaseModel

Input schema for the memory store tool.

Source code in dynamiq/nodes/tools/memory_store_tool.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class MemoryStoreToolInputSchema(BaseModel):
    """Input schema for the memory store tool."""

    action: MemoryStoreAction = Field(..., description="What to do: list, search, read, write, edit or delete.")
    path: str | None = Field(
        default=None,
        description="Memory path, e.g. 'preferences.md'. Required for every action except list and "
        "search, where it optionally narrows to a prefix.",
    )
    query: str | None = Field(default=None, description="What to look for. Required for search.")
    content: str | None = Field(default=None, description="The memory's full text. Required for write.")
    find: str | None = Field(default=None, description="Exact text to replace. Required for edit.")
    replace: str | None = Field(default=None, description="Text to put in its place. Required for edit.")
    replace_all: bool = Field(
        default=False,
        description="Replace every occurrence of 'find' instead of requiring it to be unique.",
    )
    brief: str = Field(default="Using memory", description="Short description of what you are doing.")

    @model_validator(mode="after")
    def validate_action_fields(self):
        """Fail fast on the arguments each action needs, rather than part-way through execution."""
        if self.action not in (MemoryStoreAction.LIST, MemoryStoreAction.SEARCH) and not self.path:
            raise ValueError(f"'path' is required for action '{self.action.value}'")
        if self.action == MemoryStoreAction.SEARCH and not (self.query or "").strip():
            raise ValueError("'query' is required for action 'search'")
        if self.action == MemoryStoreAction.WRITE and self.content is None:
            raise ValueError("'content' is required for action 'write'")
        # An empty `find` matches between every character; `replace` may be empty.
        if self.action == MemoryStoreAction.EDIT and (not self.find or self.replace is None):
            raise ValueError("'find' (non-empty) and 'replace' are required for action 'edit'")
        return self

validate_action_fields()

Fail fast on the arguments each action needs, rather than part-way through execution.

Source code in dynamiq/nodes/tools/memory_store_tool.py
106
107
108
109
110
111
112
113
114
115
116
117
118
@model_validator(mode="after")
def validate_action_fields(self):
    """Fail fast on the arguments each action needs, rather than part-way through execution."""
    if self.action not in (MemoryStoreAction.LIST, MemoryStoreAction.SEARCH) and not self.path:
        raise ValueError(f"'path' is required for action '{self.action.value}'")
    if self.action == MemoryStoreAction.SEARCH and not (self.query or "").strip():
        raise ValueError("'query' is required for action 'search'")
    if self.action == MemoryStoreAction.WRITE and self.content is None:
        raise ValueError("'content' is required for action 'write'")
    # An empty `find` matches between every character; `replace` may be empty.
    if self.action == MemoryStoreAction.EDIT and (not self.find or self.replace is None):
        raise ValueError("'find' (non-empty) and 'replace' are required for action 'edit'")
    return self