Vector Memory

DeskBot's vector memory extends the base Memory system with embedding-based semantic search. When an embedding function is available (e.g. sentence-transformers), entries are embedded at add-time and can be retrieved by cosine similarity - so the LLM can recall semantically relevant past interactions even when exact keywords don't match.


Mode How it works When available
Keyword search Substring match on entry content Always
Semantic search Cosine similarity between query and entry embeddings When an EmbeddingFn is configured

Keyword search (search()) works independently of embeddings and is always available. Semantic search (search_similar()) requires an embedding function and falls back to reverse-chronological order when using NoOpEmbedding.


Configuration

Vector memory is opt-in and disabled by default:

DESKBOT_VECTOR_MEMORY__ENABLED=true

When disabled, the base Memory keyword search is used instead.

To use sentence-transformers embeddings:

pip install sentence-transformers

Core classes

VectorMemory

VectorMemory stores entries with their pre-computed embedding vectors. It maintains a bounded deque of entries (default capacity 1024) and supports both keyword and semantic search:

from robot.ai.vector_memory import VectorMemory, SentenceTransformerEmbedding

# With sentence-transformers
embedding_fn = SentenceTransformerEmbedding(model_name="all-MiniLM-L6-v2")
memory = VectorMemory(embedding_fn=embedding_fn)

# Add entries
memory.add("User asked about the weather", importance=0.3, tags=["weather"])
memory.add("Robot explained the forecast", importance=0.5, tags=["weather", "explanation"])

# Keyword search
results = memory.search("weather")

# Semantic search - returns (entry, similarity) tuples sorted by relevance
similar = memory.search_similar("What's the temperature outside?", limit=5)
for entry, score in similar:
    print(f"[{score:.2f}] {entry.content}")

VectorMemoryEntry

Each entry is a VectorMemoryEntry with:

Field Type Description
timestamp datetime When the entry was created
content str The memory text
importance float Importance score (0.0–1.0)
tags tuple[str, ...] Optional tags for categorisation
embedding tuple[float, ...] Pre-computed embedding vector

Methods

Method Description
add(content, importance, tags) Add an entry, computing its embedding
recall(limit) Return the N most recent entries
search(query) Keyword substring search
search_similar(query, limit, min_similarity) Semantic cosine-similarity search
clear() Remove all entries

Embedding functions

NoOpEmbedding

NoOpEmbedding is the default fallback. It returns a zero vector of configurable dimension (default 128), meaning all entries have identical embeddings. search_similar() returns entries in reverse-chronological order.

SentenceTransformerEmbedding

SentenceTransformerEmbedding wraps the sentence-transformers library and produces normalised embeddings suitable for cosine similarity:

from robot.ai.vector_memory import VectorMemory, SentenceTransformerEmbedding

fn = SentenceTransformerEmbedding(model_name="all-MiniLM-L6-v2")
memory = VectorMemory(embedding_fn=fn)

memory.add("The robot likes discussing philosophy")
memory.add("User prefers casual conversation style")

# Semantic search - finds entries by meaning, not just keywords
results = memory.search_similar("intellectual topics", limit=5)

Requires: pip install sentence-transformers

Custom EmbeddingFn

You can implement the EmbeddingFn protocol to use any embedding backend (OpenAI embeddings, local models, etc.):

from robot.ai.vector_memory import EmbeddingFn

class MyEmbedding(EmbeddingFn):
    def embed(self, text: str) -> list[float]:
        # Call your embedding API or model here
        return my_model.encode(text)

Cosine similarity

search_similar() computes cosine similarity between the query embedding and each stored entry's embedding:

similarity(q, e) = (q · e) / (|q| × |e|)

Entries are returned sorted by descending similarity. The min_similarity parameter (default 0.0) filters out entries below a threshold, allowing you to exclude weakly related results.


API reference

robot.ai.vector_memory.VectorMemory dataclass

Memory store with vector-based semantic search.

Entries are embedded at add-time using the configured :class:EmbeddingFn. If no embedding function is provided, a :class:NoOpEmbedding is used and :meth:search_similar returns entries in reverse-chronological order (same as :class:Memory).

Keyword search (:meth:search) works independently of embeddings and is always available.

Source code in src/robot/ai/vector_memory.py
@dataclass(slots=True)
class VectorMemory:
    """Memory store with vector-based semantic search.

    Entries are embedded at add-time using the configured
    :class:`EmbeddingFn`. If no embedding function is provided,
    a :class:`NoOpEmbedding` is used and :meth:`search_similar`
    returns entries in reverse-chronological order (same as
    :class:`Memory`).

    Keyword search (:meth:`search`) works independently of
    embeddings and is always available.
    """

    entries: deque[VectorMemoryEntry] = field(default_factory=deque)
    capacity: int = 1024
    embedding_fn: EmbeddingFn = field(default_factory=NoOpEmbedding)

    def _fallback_dim(self) -> int:
        """Return the embedding dimension for fallback zero vectors.

        When the embedding function has a _dim attribute set to a
        positive integer, use it.  Otherwise default to 128.
        """
        dim = getattr(self.embedding_fn, "_dim", None)
        return dim if dim is not None and dim > 0 else 128

    def add(self, content: str, importance: float = 0.5, tags: Iterable[str] = ()) -> None:
        """Add an entry, computing and storing its embedding."""
        try:
            vec = self.embedding_fn.embed(content)
        except Exception:
            _log.warning("vector_memory.embed_failed", content=content[:80])
            vec = [0.0] * self._fallback_dim()
        entry = VectorMemoryEntry(
            timestamp=datetime.now(tz=UTC),
            content=content,
            importance=max(0.0, min(1.0, importance)),
            tags=tuple(tags),
            embedding=tuple(vec),
        )
        self.entries.append(entry)
        while len(self.entries) > self.capacity:
            self.entries.popleft()

    def recall(self, limit: int = 10) -> list[VectorMemoryEntry]:
        """Return the most recent ``limit`` entries."""
        return list(self.entries)[-limit:]

    def search(self, query: str) -> list[VectorMemoryEntry]:
        """Keyword search (substring match on content)."""
        q = query.lower()
        return [e for e in self.entries if q in e.content.lower()]

    def search_similar(
        self, query: str, limit: int = 10, min_similarity: float = 0.0
    ) -> list[tuple[VectorMemoryEntry, float]]:
        """Return entries ranked by cosine similarity to ``query``.

        Returns a list of ``(entry, similarity)`` tuples sorted by
        descending similarity. Entries below ``min_similarity`` are
        excluded.

        When using :class:`NoOpEmbedding` (no real embedding backend),
        cosine similarity is meaningless.  In that case, the method
        returns recent entries in reverse chronological order with a
        placeholder similarity of 0.0, making it explicit that no
        semantic search was performed.
        """
        if not self.entries:
            return []

        # Detect NoOpEmbedding fallback: all vectors are zero, so
        # cosine similarity is meaningless. Return recent entries in
        # reverse chronological order instead.
        if isinstance(self.embedding_fn, NoOpEmbedding):
            entries = list(reversed(self.entries))[:limit]
            _log.debug(
                "vector_memory.noop_fallback",
                message="NoOpEmbedding: returning recent entries in reverse chronological order",
                count=len(entries),
            )
            return [(e, 0.0) for e in entries]

        try:
            query_vec = self.embedding_fn.embed(query)
        except Exception:
            _log.warning("vector_memory.query_embed_failed", query=query[:80])
            # Embedding failed; fall back to chronological order.
            entries = list(reversed(self.entries))[:limit]
            return [(e, 0.0) for e in entries]

        results: list[tuple[VectorMemoryEntry, float]] = []
        for entry in self.entries:
            sim = _cosine_similarity(query_vec, list(entry.embedding))
            if sim >= min_similarity:
                results.append((entry, sim))

        results.sort(key=lambda pair: pair[1], reverse=True)
        return results[:limit]

    def clear(self) -> None:
        self.entries.clear()

add(content, importance=0.5, tags=())

Add an entry, computing and storing its embedding.

Source code in src/robot/ai/vector_memory.py
def add(self, content: str, importance: float = 0.5, tags: Iterable[str] = ()) -> None:
    """Add an entry, computing and storing its embedding."""
    try:
        vec = self.embedding_fn.embed(content)
    except Exception:
        _log.warning("vector_memory.embed_failed", content=content[:80])
        vec = [0.0] * self._fallback_dim()
    entry = VectorMemoryEntry(
        timestamp=datetime.now(tz=UTC),
        content=content,
        importance=max(0.0, min(1.0, importance)),
        tags=tuple(tags),
        embedding=tuple(vec),
    )
    self.entries.append(entry)
    while len(self.entries) > self.capacity:
        self.entries.popleft()

recall(limit=10)

Return the most recent limit entries.

Source code in src/robot/ai/vector_memory.py
def recall(self, limit: int = 10) -> list[VectorMemoryEntry]:
    """Return the most recent ``limit`` entries."""
    return list(self.entries)[-limit:]

search(query)

Keyword search (substring match on content).

Source code in src/robot/ai/vector_memory.py
def search(self, query: str) -> list[VectorMemoryEntry]:
    """Keyword search (substring match on content)."""
    q = query.lower()
    return [e for e in self.entries if q in e.content.lower()]

search_similar(query, limit=10, min_similarity=0.0)

Return entries ranked by cosine similarity to query.

Returns a list of (entry, similarity) tuples sorted by descending similarity. Entries below min_similarity are excluded.

When using :class:NoOpEmbedding (no real embedding backend), cosine similarity is meaningless. In that case, the method returns recent entries in reverse chronological order with a placeholder similarity of 0.0, making it explicit that no semantic search was performed.

Source code in src/robot/ai/vector_memory.py
def search_similar(
    self, query: str, limit: int = 10, min_similarity: float = 0.0
) -> list[tuple[VectorMemoryEntry, float]]:
    """Return entries ranked by cosine similarity to ``query``.

    Returns a list of ``(entry, similarity)`` tuples sorted by
    descending similarity. Entries below ``min_similarity`` are
    excluded.

    When using :class:`NoOpEmbedding` (no real embedding backend),
    cosine similarity is meaningless.  In that case, the method
    returns recent entries in reverse chronological order with a
    placeholder similarity of 0.0, making it explicit that no
    semantic search was performed.
    """
    if not self.entries:
        return []

    # Detect NoOpEmbedding fallback: all vectors are zero, so
    # cosine similarity is meaningless. Return recent entries in
    # reverse chronological order instead.
    if isinstance(self.embedding_fn, NoOpEmbedding):
        entries = list(reversed(self.entries))[:limit]
        _log.debug(
            "vector_memory.noop_fallback",
            message="NoOpEmbedding: returning recent entries in reverse chronological order",
            count=len(entries),
        )
        return [(e, 0.0) for e in entries]

    try:
        query_vec = self.embedding_fn.embed(query)
    except Exception:
        _log.warning("vector_memory.query_embed_failed", query=query[:80])
        # Embedding failed; fall back to chronological order.
        entries = list(reversed(self.entries))[:limit]
        return [(e, 0.0) for e in entries]

    results: list[tuple[VectorMemoryEntry, float]] = []
    for entry in self.entries:
        sim = _cosine_similarity(query_vec, list(entry.embedding))
        if sim >= min_similarity:
            results.append((entry, sim))

    results.sort(key=lambda pair: pair[1], reverse=True)
    return results[:limit]

robot.ai.vector_memory.VectorMemoryEntry dataclass

A memory entry with its pre-computed embedding vector.

Source code in src/robot/ai/vector_memory.py
@dataclass(slots=True, frozen=True)
class VectorMemoryEntry:
    """A memory entry with its pre-computed embedding vector."""

    timestamp: datetime
    content: str
    importance: float = 0.5
    tags: tuple[str, ...] = ()
    embedding: tuple[float, ...] = ()

    @property
    def vector(self) -> list[float]:
        return list(self.embedding)

robot.ai.vector_memory.EmbeddingFn

Bases: Protocol

A function that computes an embedding vector from text.

Implementations may call a local model (sentence-transformers), an API (OpenAI embeddings), or any other backend. The vector dimension must be consistent across calls.

Source code in src/robot/ai/vector_memory.py
@runtime_checkable
class EmbeddingFn(Protocol):
    """A function that computes an embedding vector from text.

    Implementations may call a local model (sentence-transformers),
    an API (OpenAI embeddings), or any other backend. The vector
    dimension must be consistent across calls.
    """

    def embed(self, text: str) -> list[float]:
        """Return a normalised embedding vector for ``text``."""
        ...

embed(text)

Return a normalised embedding vector for text.

Source code in src/robot/ai/vector_memory.py
def embed(self, text: str) -> list[float]:
    """Return a normalised embedding vector for ``text``."""
    ...

robot.ai.vector_memory.NoOpEmbedding

Fallback embedding that returns a zero vector.

Used when no embedding backend is configured - all entries get the same (zero) embedding and :meth:search_similar falls back to chronological order.

Source code in src/robot/ai/vector_memory.py
class NoOpEmbedding:
    """Fallback embedding that returns a zero vector.

    Used when no embedding backend is configured - all entries get
    the same (zero) embedding and :meth:`search_similar` falls back
    to chronological order.
    """

    def __init__(self, dim: int = 128) -> None:
        self._dim = dim

    def embed(self, text: str) -> list[float]:
        return [0.0] * self._dim

robot.ai.vector_memory.SentenceTransformerEmbedding

Embedding function backed by sentence-transformers.

Requires the sentence-transformers package. Install with::

pip install sentence-transformers

Usage::

from robot.ai.vector_memory import SentenceTransformerEmbedding

fn = SentenceTransformerEmbedding(model_name="all-MiniLM-L6-v2")
memory = VectorMemory(embedding_fn=fn)
Source code in src/robot/ai/vector_memory.py
class SentenceTransformerEmbedding:
    """Embedding function backed by ``sentence-transformers``.

    Requires the ``sentence-transformers`` package. Install with::

        pip install sentence-transformers

    Usage::

        from robot.ai.vector_memory import SentenceTransformerEmbedding

        fn = SentenceTransformerEmbedding(model_name="all-MiniLM-L6-v2")
        memory = VectorMemory(embedding_fn=fn)
    """

    def __init__(self, model_name: str = "all-MiniLM-L6-v2") -> None:
        try:
            from sentence_transformers import SentenceTransformer
        except ImportError as exc:
            raise ImportError(
                "sentence-transformers is required for SentenceTransformerEmbedding. "
                "Install with: pip install sentence-transformers"
            ) from exc
        # Force CPU to avoid CUDA kernel compatibility issues on GPUs
        # with older compute capabilities (e.g. Quadro P520, CC 6.1).
        # The all-MiniLM-L6-v2 model is small enough that CPU inference
        # is fast and avoids the 'no kernel image' error from torch.
        self._model = SentenceTransformer(model_name, device="cpu")
        self._model_name = model_name
        self._dim: int | None = None
        _log.info("vector_memory.model_loaded", model=model_name)

    def embed(self, text: str) -> list[float]:
        embedding = self._model.encode(text, normalize_embeddings=True)
        vec = [float(x) for x in embedding.tolist()]
        if self._dim is None:
            self._dim = len(vec)
        return vec