Skip to content

BaseMemoryStore

Base memory store class.

BaseMemoryStore

Bases: ABC

Base class for episodic memory stores.

Subclasses are responsible for two things:

  1. Durable persistence — write episodes to the substrate, including any preprocessing required by that substrate (embedding, indexing, tokenization).
  2. Retrieval primitives — implement _read_recent and _search so that the concrete search() method can dispatch based on recall_mode without knowing the underlying storage details.

The public retrieval interface is search(). Subclasses must not override it; they implement _read_recent and _search instead.

Attributes:

Name Type Description
max_results int

Default number of results returned by search() when no explicit count is supplied by the caller.

recall_mode RecallMode

Controls how search() retrieves episodes. RecallMode.RECENT delegates to _read_recent; RecallMode.SEARCH delegates to _search.

Source code in src/llm_agents_from_scratch/base/memory_store.py
class BaseMemoryStore(ABC):
    """Base class for episodic memory stores.

    Subclasses are responsible for two things:

    1. **Durable persistence** — write episodes to the substrate, including
       any preprocessing required by that substrate (embedding, indexing,
       tokenization).
    2. **Retrieval primitives** — implement ``_read_recent`` and ``_search``
       so that the concrete ``search()`` method can dispatch based on
       ``recall_mode`` without knowing the underlying storage details.

    The public retrieval interface is ``search()``. Subclasses must not
    override it; they implement ``_read_recent`` and ``_search`` instead.

    Attributes:
        max_results (int): Default number of results returned by
            ``search()`` when no explicit count is supplied by the caller.
        recall_mode (RecallMode): Controls how ``search()`` retrieves
            episodes. ``RecallMode.RECENT`` delegates to ``_read_recent``;
            ``RecallMode.SEARCH`` delegates to ``_search``.
    """

    def __init__(
        self,
        max_results: int = 5,
        recall_mode: RecallMode = RecallMode.SEARCH,
    ) -> None:
        """Initialise shared store state.

        Args:
            max_results (int): Default maximum number of episodes
                returned by retrieval operations. Defaults to 5.
            recall_mode (RecallMode): Retrieval strategy used by
                ``search()``. Defaults to ``RecallMode.SEARCH``.
        """
        self.max_results = max_results
        self.recall_mode = recall_mode

    @abstractmethod
    async def write(self, episode: Episode) -> None:
        """Persist an episode to the store.

        Subclasses must implement this method.

        Args:
            episode (Episode): The completed episode to store.
        """

    @abstractmethod
    async def _read_recent(self, n: int) -> list[Episode]:
        """Return the N most recently recorded episodes.

        Subclasses must implement this method. It is called by the
        concrete ``search()`` when ``recall_mode`` is
        ``RecallMode.RECENT``.

        Args:
            n (int): Maximum number of episodes to return.

        Returns:
            list[Episode]: Episodes ordered from most recent to oldest.
        """

    @abstractmethod
    async def _search(
        self,
        query: str,
        **kwargs: Any,
    ) -> list[Episode]:
        """Return the most relevant episodes for a query.

        Subclasses must implement this method. It is called by the
        concrete ``search()`` when ``recall_mode`` is
        ``RecallMode.SEARCH``. The number of results is controlled by
        ``self.max_results``.

        Args:
            query (str): The search query (e.g. the task instruction).
            **kwargs: Optional substrate-specific search parameters
                (e.g. filters, score thresholds).

        Returns:
            list[Episode]: Episodes ordered by relevance to the query.
        """

    async def recall(
        self,
        query: str,
        **kwargs: Any,
    ) -> list[Episode]:
        """Return episodes according to ``recall_mode``.

        Dispatches to ``_read_recent`` when ``recall_mode`` is
        ``RecallMode.RECENT``, or to ``_search`` when it is
        ``RecallMode.SEARCH``. Subclasses must not override this method;
        implement ``_read_recent`` and ``_search`` instead.

        Args:
            query (str): The search query (e.g. the task instruction).
                Ignored when ``recall_mode`` is ``RecallMode.RECENT``.
            **kwargs: Optional substrate-specific search parameters
                forwarded to ``_search``.

        Returns:
            list[Episode]: Episodes ordered by recency or relevance
                depending on ``recall_mode``.
        """
        if self.recall_mode == RecallMode.RECENT:
            results = await self._read_recent(self.max_results)
        else:
            results = await self._search(query, **kwargs)
        if len(results) > self.max_results:
            warnings.warn(
                f"{type(self).__name__}._search returned {len(results)} results"
                f" but max_results={self.max_results}.",
                MaxResultsExceededWarning,
                stacklevel=2,
            )
        return results

    @abstractmethod
    async def delete(self, id_: str) -> None:
        """Delete an episode by its unique identifier.

        Subclasses must implement this method. Raises
        ``EpisodeNotFoundError`` if no episode with ``id_`` exists.

        Args:
            id_ (str): The ``Episode.id_`` of the episode to remove.
        """

    @abstractmethod
    async def update(self, episode: Episode) -> None:
        """Replace an existing episode with an updated version.

        Subclasses must implement this method. Matches the stored episode
        by ``episode.id_`` and replaces it in-place. Raises
        ``EpisodeNotFoundError`` if no matching episode exists.

        Args:
            episode (Episode): The updated episode. Matched by ``id_``.
        """

    @abstractmethod
    async def count(self) -> int:
        """Return the total number of episodes in the store.

        Subclasses must implement this method.

        Returns:
            int: Episode count.
        """

    @abstractmethod
    async def summary(self) -> str:
        """Return a human-readable summary of the store contents.

        Subclasses must implement this method. Should describe the
        substrate, episode count, and the oldest and newest episodes.
        Intended for inspection and debugging.

        Returns:
            str: Multi-line summary of the store.
        """

__init__

__init__(max_results=5, recall_mode=RecallMode.SEARCH)

Initialise shared store state.

Parameters:

Name Type Description Default
max_results int

Default maximum number of episodes returned by retrieval operations. Defaults to 5.

5
recall_mode RecallMode

Retrieval strategy used by search(). Defaults to RecallMode.SEARCH.

SEARCH
Source code in src/llm_agents_from_scratch/base/memory_store.py
def __init__(
    self,
    max_results: int = 5,
    recall_mode: RecallMode = RecallMode.SEARCH,
) -> None:
    """Initialise shared store state.

    Args:
        max_results (int): Default maximum number of episodes
            returned by retrieval operations. Defaults to 5.
        recall_mode (RecallMode): Retrieval strategy used by
            ``search()``. Defaults to ``RecallMode.SEARCH``.
    """
    self.max_results = max_results
    self.recall_mode = recall_mode

write abstractmethod async

write(episode)

Persist an episode to the store.

Subclasses must implement this method.

Parameters:

Name Type Description Default
episode Episode

The completed episode to store.

required
Source code in src/llm_agents_from_scratch/base/memory_store.py
@abstractmethod
async def write(self, episode: Episode) -> None:
    """Persist an episode to the store.

    Subclasses must implement this method.

    Args:
        episode (Episode): The completed episode to store.
    """

recall async

recall(query, **kwargs)

Return episodes according to recall_mode.

Dispatches to _read_recent when recall_mode is RecallMode.RECENT, or to _search when it is RecallMode.SEARCH. Subclasses must not override this method; implement _read_recent and _search instead.

Parameters:

Name Type Description Default
query str

The search query (e.g. the task instruction). Ignored when recall_mode is RecallMode.RECENT.

required
**kwargs Any

Optional substrate-specific search parameters forwarded to _search.

{}

Returns:

Type Description
list[Episode]

list[Episode]: Episodes ordered by recency or relevance depending on recall_mode.

Source code in src/llm_agents_from_scratch/base/memory_store.py
async def recall(
    self,
    query: str,
    **kwargs: Any,
) -> list[Episode]:
    """Return episodes according to ``recall_mode``.

    Dispatches to ``_read_recent`` when ``recall_mode`` is
    ``RecallMode.RECENT``, or to ``_search`` when it is
    ``RecallMode.SEARCH``. Subclasses must not override this method;
    implement ``_read_recent`` and ``_search`` instead.

    Args:
        query (str): The search query (e.g. the task instruction).
            Ignored when ``recall_mode`` is ``RecallMode.RECENT``.
        **kwargs: Optional substrate-specific search parameters
            forwarded to ``_search``.

    Returns:
        list[Episode]: Episodes ordered by recency or relevance
            depending on ``recall_mode``.
    """
    if self.recall_mode == RecallMode.RECENT:
        results = await self._read_recent(self.max_results)
    else:
        results = await self._search(query, **kwargs)
    if len(results) > self.max_results:
        warnings.warn(
            f"{type(self).__name__}._search returned {len(results)} results"
            f" but max_results={self.max_results}.",
            MaxResultsExceededWarning,
            stacklevel=2,
        )
    return results

delete abstractmethod async

delete(id_)

Delete an episode by its unique identifier.

Subclasses must implement this method. Raises EpisodeNotFoundError if no episode with id_ exists.

Parameters:

Name Type Description Default
id_ str

The Episode.id_ of the episode to remove.

required
Source code in src/llm_agents_from_scratch/base/memory_store.py
@abstractmethod
async def delete(self, id_: str) -> None:
    """Delete an episode by its unique identifier.

    Subclasses must implement this method. Raises
    ``EpisodeNotFoundError`` if no episode with ``id_`` exists.

    Args:
        id_ (str): The ``Episode.id_`` of the episode to remove.
    """

update abstractmethod async

update(episode)

Replace an existing episode with an updated version.

Subclasses must implement this method. Matches the stored episode by episode.id_ and replaces it in-place. Raises EpisodeNotFoundError if no matching episode exists.

Parameters:

Name Type Description Default
episode Episode

The updated episode. Matched by id_.

required
Source code in src/llm_agents_from_scratch/base/memory_store.py
@abstractmethod
async def update(self, episode: Episode) -> None:
    """Replace an existing episode with an updated version.

    Subclasses must implement this method. Matches the stored episode
    by ``episode.id_`` and replaces it in-place. Raises
    ``EpisodeNotFoundError`` if no matching episode exists.

    Args:
        episode (Episode): The updated episode. Matched by ``id_``.
    """

count abstractmethod async

count()

Return the total number of episodes in the store.

Subclasses must implement this method.

Returns:

Name Type Description
int int

Episode count.

Source code in src/llm_agents_from_scratch/base/memory_store.py
@abstractmethod
async def count(self) -> int:
    """Return the total number of episodes in the store.

    Subclasses must implement this method.

    Returns:
        int: Episode count.
    """

summary abstractmethod async

summary()

Return a human-readable summary of the store contents.

Subclasses must implement this method. Should describe the substrate, episode count, and the oldest and newest episodes. Intended for inspection and debugging.

Returns:

Name Type Description
str str

Multi-line summary of the store.

Source code in src/llm_agents_from_scratch/base/memory_store.py
@abstractmethod
async def summary(self) -> str:
    """Return a human-readable summary of the store contents.

    Subclasses must implement this method. Should describe the
    substrate, episode count, and the oldest and newest episodes.
    Intended for inspection and debugging.

    Returns:
        str: Multi-line summary of the store.
    """