Skip to content

Base

Base memory-store interface and common data structures.

A memory store holds what an agent has learned and wants to carry into later conversations: short text notes addressed by path. It is deliberately not a FileStore. That interface carries list_files_bytes, extracted-text caching, content types and BytesIO — all of which exist for agent file plumbing memory does not take part in, and each of which caused a bug when memory was built on top of it.

MemoryChangedError

Bases: MemoryStoreError

Raised when a memory changed or was deleted since it was read, so a write would lose that change.

Source code in dynamiq/storages/memory/base.py
40
41
class MemoryChangedError(MemoryStoreError):
    """Raised when a memory changed or was deleted since it was read, so a write would lose that change."""

MemoryEntry

Bases: BaseModel

One memory, without its content.

description is what the store reports the memory holds: its description property, else its first line of prose. content_hash identifies the content, for write_if_unchanged. A store that reports neither leaves them empty.

Source code in dynamiq/storages/memory/base.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class MemoryEntry(BaseModel):
    """One memory, without its content.

    ``description`` is what the store reports the memory holds: its ``description`` property, else its
    first line of prose. ``content_hash`` identifies the content, for ``write_if_unchanged``. A store that
    reports neither leaves them empty.
    """

    path: str
    size: int = 0
    updated_at: datetime | None = None
    description: str = ""
    content_hash: str = ""

    @field_validator("description", "content_hash", mode="before")
    @classmethod
    def _absent_is_empty(cls, value: Any) -> Any:
        return "" if value is None else value

MemoryHit

Bases: MemoryEntry

A memory that matches a search, with the passage that matched.

Source code in dynamiq/storages/memory/base.py
69
70
71
72
73
class MemoryHit(MemoryEntry):
    """A memory that matches a search, with the passage that matched."""

    snippet: str = ""
    score: float = 0.0

Bases: BaseModel

A link one memory makes. path is None when no memory of that name exists yet.

Source code in dynamiq/storages/memory/base.py
76
77
78
79
80
class MemoryLink(BaseModel):
    """A link one memory makes. ``path`` is None when no memory of that name exists yet."""

    target: str
    path: str | None = None

MemoryNotFoundError

Bases: MemoryStoreError

Raised when a memory does not exist.

Source code in dynamiq/storages/memory/base.py
32
33
class MemoryNotFoundError(MemoryStoreError):
    """Raised when a memory does not exist."""

MemoryNote

Bases: MemoryEntry

One memory with its content, the memories it links to and the memories that link to it.

Source code in dynamiq/storages/memory/base.py
83
84
85
86
87
88
class MemoryNote(MemoryEntry):
    """One memory with its content, the memories it links to and the memories that link to it."""

    content: str
    links: list[MemoryLink] = Field(default_factory=list)
    backlinks: list[str] = Field(default_factory=list)

MemoryPermissionError

Bases: MemoryStoreError

Raised when a memory operation is not permitted.

Source code in dynamiq/storages/memory/base.py
36
37
class MemoryPermissionError(MemoryStoreError):
    """Raised when a memory operation is not permitted."""

MemoryStore

Bases: ABC, BaseModel

Abstract base class for memory backends.

Four operations over text addressed by path. There is no exists: read raises when a path is absent and delete reports whether it removed anything, which covers every caller and keeps one endpoint out of the API.

_clone_shared tells Node.clone() to share this instance by reference rather than deep-copying it, so parallel cloned tools reach the same store.

Source code in dynamiq/storages/memory/base.py
 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
119
120
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
class MemoryStore(abc.ABC, BaseModel):
    """Abstract base class for memory backends.

    Four operations over text addressed by path. There is no ``exists``: ``read`` raises when a path
    is absent and ``delete`` reports whether it removed anything, which covers every caller and
    keeps one endpoint out of the API.

    ``_clone_shared`` tells ``Node.clone()`` to share this instance by reference rather than
    deep-copying it, so parallel cloned tools reach the same store.
    """

    description: str | None = Field(
        default=None,
        description="What this memory holds. Shown to the model so it can tell memories apart.",
    )

    _clone_shared: ClassVar[bool] = True

    model_config = ConfigDict(arbitrary_types_allowed=True)

    @computed_field
    @property
    def type(self) -> str:
        """Dotted path used to rebuild this store from a serialized workflow."""
        return f"{self.__module__.rsplit('.', 1)[0]}.{self.__class__.__name__}"

    @property
    def to_dict_exclude_params(self) -> dict[str, bool]:
        """Parameters to drop when serializing."""
        return {}

    def to_dict(self, **kwargs) -> dict[str, Any]:
        """Convert the store to a dictionary."""
        kwargs.pop("for_tracing", None)
        kwargs.pop("include_secure_params", None)
        exclude = kwargs.pop("exclude", self.to_dict_exclude_params)
        data = self.model_dump(exclude=exclude, **kwargs)
        data["type"] = self.type
        return data

    def scope_of(self, path: str) -> str:
        """The prefix of the memory that holds ``path``; links between memories resolve inside it."""
        return ""

    def describe_namespaces(self) -> dict[str, str]:
        """Path prefix -> what lives there.

        The empty key means everything this store holds. A composite overrides this to compose its
        routes' descriptions, so the caller never assembles a parallel structure by hand.
        """
        return {"": self.description} if self.description else {}

    def identity(self) -> Hashable:
        """What underlying store this addresses; two stores with the same identity hold the same data.

        A composite strips its route prefix before calling a store, so two routes pointing at one
        store would map different agent paths onto the same key and silently overwrite each other.
        This is how the composite tells them apart and refuses. Subclasses that address something
        remote should key on what identifies it there, not on the Python object.
        """
        return id(self)

    def content_limit(self) -> int | None:
        """The most characters one memory may hold, or None when the store sets no limit."""
        return None

    @abc.abstractmethod
    def list(self, prefix: str = "", user_id: str | None = None) -> builtins.list[MemoryEntry]:
        """List memories under ``prefix``. An empty prefix lists everything.

        Returns metadata only — read a path to get its content. ``user_id`` is the end user this
        call is for; it overrides whatever default the store was configured with.
        """

    @abc.abstractmethod
    def read(self, path: str, user_id: str | None = None) -> str:
        """Return the content of one memory.

        Raises:
            MemoryNotFoundError: If the path does not exist.
        """

    @abc.abstractmethod
    def write(self, path: str, content: str, user_id: str | None = None) -> MemoryEntry:
        """Create or replace one memory, returning its entry."""

    @abc.abstractmethod
    def delete(self, path: str, user_id: str | None = None) -> bool:
        """Delete one memory. Returns False when it was not there."""

    def read_note(self, path: str, user_id: str | None = None) -> MemoryNote:
        """Read one memory with the memories it links to and that link to it.

        The default knows nothing beyond the content; a store that tracks links overrides it.

        Raises:
            MemoryNotFoundError: If the path does not exist.
        """
        content = self.read(path, user_id)
        return MemoryNote(path=path, content=content, content_hash=content_hash(content))

    def write_if_unchanged(
        self, path: str, content: str, expected_hash: str | None, user_id: str | None = None
    ) -> MemoryEntry:
        """Replace a memory only while it still holds the content ``expected_hash`` identifies; with no
        hash, create it only while no memory exists at the path.

        The default checks, then writes, so a write landing in between goes unnoticed; a store that can
        check both at once overrides it.

        Raises:
            MemoryChangedError: If the memory changed or was deleted since it was read, or, with no hash,
                already exists.
        """
        try:
            current = self.read(path, user_id)
        except MemoryNotFoundError:
            if expected_hash is None:
                return self.write(path, content, user_id)
            raise MemoryChangedError(f"'{path}' was deleted since it was read", operation="write", path=path) from None
        if expected_hash is None:
            raise MemoryChangedError(f"'{path}' already exists", operation="write", path=path)
        if content_hash(current) != expected_hash:
            raise MemoryChangedError(f"'{path}' changed since it was read", operation="write", path=path)
        return self.write(path, content, user_id)

    def delete_if_unchanged(self, path: str, expected_hash: str, user_id: str | None = None) -> bool:
        """Delete a memory only while it still holds the content ``expected_hash`` identifies. Returns False
        when it was not there.

        The default checks, then deletes, so a write landing in between goes unnoticed; a store that can
        check both at once overrides it.

        Raises:
            MemoryChangedError: If the memory changed since it was read.
        """
        try:
            current = self.read(path, user_id)
        except MemoryNotFoundError:
            return False
        if content_hash(current) != expected_hash:
            raise MemoryChangedError(f"'{path}' changed since it was read", operation="delete", path=path)
        return self.delete(path, user_id)

    def search(
        self, query: str, prefix: str = "", limit: int = 10, user_id: str | None = None
    ) -> builtins.list[MemoryHit]:
        """Memories under ``prefix`` that hold the words of ``query``, best first.

        The default reads every memory and counts the query's words in each, which is fine for the few
        hundred short notes a memory holds; a store with an index of its own overrides it.
        """
        words = {word for word in _WORD.findall(query.lower()) if len(word) > 2}
        if not words:
            return []
        hits: builtins.list[MemoryHit] = []
        for entry in self.list(prefix, user_id):
            try:
                text = f"{entry.path} {self.read(entry.path, user_id)}".lower()
            except MemoryNotFoundError:
                continue
            score = sum(1 for word in words if word in text) / len(words)
            if score:
                hits.append(MemoryHit(**entry.model_dump(), score=score))
        hits.sort(key=lambda hit: (-hit.score, hit.path))
        return hits[:limit]

to_dict_exclude_params: dict[str, bool] property

Parameters to drop when serializing.

type: str property

Dotted path used to rebuild this store from a serialized workflow.

content_limit()

The most characters one memory may hold, or None when the store sets no limit.

Source code in dynamiq/storages/memory/base.py
153
154
155
def content_limit(self) -> int | None:
    """The most characters one memory may hold, or None when the store sets no limit."""
    return None

delete(path, user_id=None) abstractmethod

Delete one memory. Returns False when it was not there.

Source code in dynamiq/storages/memory/base.py
177
178
179
@abc.abstractmethod
def delete(self, path: str, user_id: str | None = None) -> bool:
    """Delete one memory. Returns False when it was not there."""

delete_if_unchanged(path, expected_hash, user_id=None)

Delete a memory only while it still holds the content expected_hash identifies. Returns False when it was not there.

The default checks, then deletes, so a write landing in between goes unnoticed; a store that can check both at once overrides it.

Raises:

Type Description
MemoryChangedError

If the memory changed since it was read.

Source code in dynamiq/storages/memory/base.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def delete_if_unchanged(self, path: str, expected_hash: str, user_id: str | None = None) -> bool:
    """Delete a memory only while it still holds the content ``expected_hash`` identifies. Returns False
    when it was not there.

    The default checks, then deletes, so a write landing in between goes unnoticed; a store that can
    check both at once overrides it.

    Raises:
        MemoryChangedError: If the memory changed since it was read.
    """
    try:
        current = self.read(path, user_id)
    except MemoryNotFoundError:
        return False
    if content_hash(current) != expected_hash:
        raise MemoryChangedError(f"'{path}' changed since it was read", operation="delete", path=path)
    return self.delete(path, user_id)

describe_namespaces()

Path prefix -> what lives there.

The empty key means everything this store holds. A composite overrides this to compose its routes' descriptions, so the caller never assembles a parallel structure by hand.

Source code in dynamiq/storages/memory/base.py
135
136
137
138
139
140
141
def describe_namespaces(self) -> dict[str, str]:
    """Path prefix -> what lives there.

    The empty key means everything this store holds. A composite overrides this to compose its
    routes' descriptions, so the caller never assembles a parallel structure by hand.
    """
    return {"": self.description} if self.description else {}

identity()

What underlying store this addresses; two stores with the same identity hold the same data.

A composite strips its route prefix before calling a store, so two routes pointing at one store would map different agent paths onto the same key and silently overwrite each other. This is how the composite tells them apart and refuses. Subclasses that address something remote should key on what identifies it there, not on the Python object.

Source code in dynamiq/storages/memory/base.py
143
144
145
146
147
148
149
150
151
def identity(self) -> Hashable:
    """What underlying store this addresses; two stores with the same identity hold the same data.

    A composite strips its route prefix before calling a store, so two routes pointing at one
    store would map different agent paths onto the same key and silently overwrite each other.
    This is how the composite tells them apart and refuses. Subclasses that address something
    remote should key on what identifies it there, not on the Python object.
    """
    return id(self)

list(prefix='', user_id=None) abstractmethod

List memories under prefix. An empty prefix lists everything.

Returns metadata only — read a path to get its content. user_id is the end user this call is for; it overrides whatever default the store was configured with.

Source code in dynamiq/storages/memory/base.py
157
158
159
160
161
162
163
@abc.abstractmethod
def list(self, prefix: str = "", user_id: str | None = None) -> builtins.list[MemoryEntry]:
    """List memories under ``prefix``. An empty prefix lists everything.

    Returns metadata only — read a path to get its content. ``user_id`` is the end user this
    call is for; it overrides whatever default the store was configured with.
    """

read(path, user_id=None) abstractmethod

Return the content of one memory.

Raises:

Type Description
MemoryNotFoundError

If the path does not exist.

Source code in dynamiq/storages/memory/base.py
165
166
167
168
169
170
171
@abc.abstractmethod
def read(self, path: str, user_id: str | None = None) -> str:
    """Return the content of one memory.

    Raises:
        MemoryNotFoundError: If the path does not exist.
    """

read_note(path, user_id=None)

Read one memory with the memories it links to and that link to it.

The default knows nothing beyond the content; a store that tracks links overrides it.

Raises:

Type Description
MemoryNotFoundError

If the path does not exist.

Source code in dynamiq/storages/memory/base.py
181
182
183
184
185
186
187
188
189
190
def read_note(self, path: str, user_id: str | None = None) -> MemoryNote:
    """Read one memory with the memories it links to and that link to it.

    The default knows nothing beyond the content; a store that tracks links overrides it.

    Raises:
        MemoryNotFoundError: If the path does not exist.
    """
    content = self.read(path, user_id)
    return MemoryNote(path=path, content=content, content_hash=content_hash(content))

scope_of(path)

The prefix of the memory that holds path; links between memories resolve inside it.

Source code in dynamiq/storages/memory/base.py
131
132
133
def scope_of(self, path: str) -> str:
    """The prefix of the memory that holds ``path``; links between memories resolve inside it."""
    return ""

search(query, prefix='', limit=10, user_id=None)

Memories under prefix that hold the words of query, best first.

The default reads every memory and counts the query's words in each, which is fine for the few hundred short notes a memory holds; a store with an index of its own overrides it.

Source code in dynamiq/storages/memory/base.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def search(
    self, query: str, prefix: str = "", limit: int = 10, user_id: str | None = None
) -> builtins.list[MemoryHit]:
    """Memories under ``prefix`` that hold the words of ``query``, best first.

    The default reads every memory and counts the query's words in each, which is fine for the few
    hundred short notes a memory holds; a store with an index of its own overrides it.
    """
    words = {word for word in _WORD.findall(query.lower()) if len(word) > 2}
    if not words:
        return []
    hits: builtins.list[MemoryHit] = []
    for entry in self.list(prefix, user_id):
        try:
            text = f"{entry.path} {self.read(entry.path, user_id)}".lower()
        except MemoryNotFoundError:
            continue
        score = sum(1 for word in words if word in text) / len(words)
        if score:
            hits.append(MemoryHit(**entry.model_dump(), score=score))
    hits.sort(key=lambda hit: (-hit.score, hit.path))
    return hits[:limit]

to_dict(**kwargs)

Convert the store to a dictionary.

Source code in dynamiq/storages/memory/base.py
122
123
124
125
126
127
128
129
def to_dict(self, **kwargs) -> dict[str, Any]:
    """Convert the store to a dictionary."""
    kwargs.pop("for_tracing", None)
    kwargs.pop("include_secure_params", None)
    exclude = kwargs.pop("exclude", self.to_dict_exclude_params)
    data = self.model_dump(exclude=exclude, **kwargs)
    data["type"] = self.type
    return data

write(path, content, user_id=None) abstractmethod

Create or replace one memory, returning its entry.

Source code in dynamiq/storages/memory/base.py
173
174
175
@abc.abstractmethod
def write(self, path: str, content: str, user_id: str | None = None) -> MemoryEntry:
    """Create or replace one memory, returning its entry."""

write_if_unchanged(path, content, expected_hash, user_id=None)

Replace a memory only while it still holds the content expected_hash identifies; with no hash, create it only while no memory exists at the path.

The default checks, then writes, so a write landing in between goes unnoticed; a store that can check both at once overrides it.

Raises:

Type Description
MemoryChangedError

If the memory changed or was deleted since it was read, or, with no hash, already exists.

Source code in dynamiq/storages/memory/base.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def write_if_unchanged(
    self, path: str, content: str, expected_hash: str | None, user_id: str | None = None
) -> MemoryEntry:
    """Replace a memory only while it still holds the content ``expected_hash`` identifies; with no
    hash, create it only while no memory exists at the path.

    The default checks, then writes, so a write landing in between goes unnoticed; a store that can
    check both at once overrides it.

    Raises:
        MemoryChangedError: If the memory changed or was deleted since it was read, or, with no hash,
            already exists.
    """
    try:
        current = self.read(path, user_id)
    except MemoryNotFoundError:
        if expected_hash is None:
            return self.write(path, content, user_id)
        raise MemoryChangedError(f"'{path}' was deleted since it was read", operation="write", path=path) from None
    if expected_hash is None:
        raise MemoryChangedError(f"'{path}' already exists", operation="write", path=path)
    if content_hash(current) != expected_hash:
        raise MemoryChangedError(f"'{path}' changed since it was read", operation="write", path=path)
    return self.write(path, content, user_id)

MemoryStoreConfig

Bases: BaseModel

Configuration for an agent's memory store.

Attributes:

Name Type Description
enabled bool

Whether the agent gets a memory tool at all.

backend MemoryStore

The store holding memories. A CompositeMemoryStore when there are several.

write_enabled bool

Whether the agent may create, edit and delete memories.

Source code in dynamiq/storages/memory/base.py
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
class MemoryStoreConfig(BaseModel):
    """Configuration for an agent's memory store.

    Attributes:
        enabled: Whether the agent gets a memory tool at all.
        backend: The store holding memories. A ``CompositeMemoryStore`` when there are several.
        write_enabled: Whether the agent may create, edit and delete memories.
    """

    enabled: bool = False
    backend: MemoryStore = Field(..., description="Store holding the agent's memories.")
    write_enabled: bool = Field(
        default=True,
        description="Whether the agent is permitted to write memories.",
    )

    model_config = ConfigDict(arbitrary_types_allowed=True)

    @property
    def to_dict_exclude_params(self) -> dict[str, bool]:
        """The backend serializes itself, so exclude it from the plain dump."""
        return {"backend": True}

    def to_dict(self, **kwargs) -> dict[str, Any]:
        """Convert the config to a dictionary, delegating the backend to its own ``to_dict``."""
        for_tracing = kwargs.pop("for_tracing", False)
        if for_tracing and not self.enabled:
            return {"enabled": False}
        include_secure_params = kwargs.pop("include_secure_params", False)
        exclude = kwargs.pop("exclude", self.to_dict_exclude_params)
        data = self.model_dump(exclude=exclude, **kwargs)
        data["backend"] = self.backend.to_dict(for_tracing=for_tracing, include_secure_params=include_secure_params)
        return data

to_dict_exclude_params: dict[str, bool] property

The backend serializes itself, so exclude it from the plain dump.

to_dict(**kwargs)

Convert the config to a dictionary, delegating the backend to its own to_dict.

Source code in dynamiq/storages/memory/base.py
282
283
284
285
286
287
288
289
290
291
def to_dict(self, **kwargs) -> dict[str, Any]:
    """Convert the config to a dictionary, delegating the backend to its own ``to_dict``."""
    for_tracing = kwargs.pop("for_tracing", False)
    if for_tracing and not self.enabled:
        return {"enabled": False}
    include_secure_params = kwargs.pop("include_secure_params", False)
    exclude = kwargs.pop("exclude", self.to_dict_exclude_params)
    data = self.model_dump(exclude=exclude, **kwargs)
    data["backend"] = self.backend.to_dict(for_tracing=for_tracing, include_secure_params=include_secure_params)
    return data

MemoryStoreError

Bases: Exception

Base exception for memory-store operations.

Source code in dynamiq/storages/memory/base.py
22
23
24
25
26
27
28
29
class MemoryStoreError(Exception):
    """Base exception for memory-store operations."""

    def __init__(self, message: str, operation: str | None = None, path: str | None = None):
        self.message = message
        self.operation = operation
        self.path = path
        super().__init__(self.message)

content_hash(content)

The hex SHA-256 of a memory's text, as the platform reports it in content_hash.

Source code in dynamiq/storages/memory/base.py
44
45
46
def content_hash(content: str) -> str:
    """The hex SHA-256 of a memory's text, as the platform reports it in ``content_hash``."""
    return hashlib.sha256(content.encode()).hexdigest()

render_namespaces(namespaces)

One line per memory, for the tool description and the prompt.

Empty when nothing is described, in which case the surrounding wording already covers a single unnamed memory.

Source code in dynamiq/storages/memory/base.py
294
295
296
297
298
299
300
301
302
def render_namespaces(namespaces: dict[str, str]) -> str:
    """One line per memory, for the tool description and the prompt.

    Empty when nothing is described, in which case the surrounding wording already covers a single
    unnamed memory.
    """
    if not namespaces:
        return ""
    return "\n".join(f"- {prefix} - {text}" if prefix else f"- {text}" for prefix, text in namespaces.items() if text)