Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Chat memory

Store chat turns in Telys, recall the most relevant history for the current message, and prune old turns with delete and compact to keep sessions bounded.

A long conversation overflows a model's context window. Instead of resending the whole transcript every turn, store each turn in Telys and recall only the turns relevant to the current message. Store, recall, and prune to keep a session bounded:

  1. Store every turn with add_texts, partitioned by session.

  2. Recall the most relevant prior turns with search_text before answering.

  3. Prune turns past a budget with delete, then reclaim space with compact.

Install with pipx install telys, sign in with telys login, then verify with telys runtime verify. The lexical embedder needs the native kernel from the verified runtime. See Install Telys.

Partition by session

Each conversation is one partition. Build the session scope with scope_key(...) and store it under a single scope column, so recall for one conversation never sees another. Telys has no temporal query API, so track recency client-side with a monotonic turn counter you assign as you go — that counter lets you prune the oldest turns deterministically.

Full example

chat_memory.py
from telys import Telys, Eq, scope_key
from telys.embedding import AlgentaMultigramEmbedder


class ChatMemory:
    """Per-session chat history with relevance recall and recency pruning."""

    def __init__(self, path: str = "./chat-memory", name: str = "turns", max_turns: int = 200):
        self.max_turns = max_turns
        self.embedder = AlgentaMultigramEmbedder()
        self.telys = Telys(path)
        try:
            self.col = self.telys.open_collection(name, embedder=self.embedder)
        except FileNotFoundError:
            self.col = self.telys.create_collection(
                name,
                dim=self.embedder.profile.dimension,
                partition_by="scope",
                embedder=self.embedder,
                filter_columns=("role", "turn", "text"),
            )
            self.col.save()
        self._counter: dict[str, int] = {}

    def _scope(self, session_id: str) -> str:
        return scope_key("session", session_id)

    def add_turn(self, session_id: str, role: str, text: str) -> str:
        """Append one chat turn (role = 'user' or 'assistant')."""
        scope = self._scope(session_id)
        n = self._counter.get(scope, 0)
        self._counter[scope] = n + 1
        turn_id = f"{scope}:{n:08d}"
        self.col.add_texts(
            texts=[text],
            ids=[turn_id],
            metadata=[{"scope": scope, "role": role, "turn": n, "text": text}],
        )
        return turn_id

    def recall(self, session_id: str, query: str, top_k: int = 6) -> list[dict]:
        res = self.col.search_text(
            query,
            top_k=top_k,
            where=Eq("scope", self._scope(session_id)),
            with_metadata=True,
        )
        hits = [
            {"turn": m["turn"], "role": m["role"], "text": m["text"], "score": s}
            for s, m in zip(res["scores"], res["metadata"])
        ]
        # Present recalled turns in conversational order.
        return sorted(hits, key=lambda h: h["turn"])

    def prune(self, session_id: str) -> int:
        """Delete turns older than the newest `max_turns`, then compact."""
        scope = self._scope(session_id)
        ids = self.col.ids(where=Eq("scope", scope))
        if len(ids) <= self.max_turns:
            return 0
        # ids sort lexicographically by the zero-padded turn number.
        stale = sorted(ids)[: len(ids) - self.max_turns]
        self.col.delete(stale)
        self.col.compact()
        return len(stale)

    def save(self) -> None:
        self.col.save()


if __name__ == "__main__":
    chat = ChatMemory(max_turns=200)
    sid = "conv-42"

    chat.add_turn(sid, "user", "I want to plan a trip to Lisbon in spring.")
    chat.add_turn(sid, "assistant", "Great — spring in Lisbon is mild. Any budget?")
    chat.add_turn(sid, "user", "Around 1500 euros, and I love seafood.")

    for h in chat.recall(sid, "what food does the user like?"):
        print(f"[{h['role']} #{h['turn']}] {h['text']}  ({h['score']:.3f})")

    removed = chat.prune(sid)
    print(f"pruned {removed} old turns")
    chat.save()

Recall then answer

Before calling your model, recall the relevant slice of history and prepend it. This is cheaper than resending the full transcript and keeps older-but-relevant turns available past the context window.

Expected result

The script recalls the seafood turn as the top hit for a food query, prints recalled turns in conversational order, and reports how many were pruned:

Below max_turns, prune deletes nothing. Once a session exceeds the budget, delete drops the oldest turns and compact reclaims their storage.

delete removes only ids that are present; compact physically reclaims deleted rows — run it after a batch of deletes, not per turn. See Delete & compact.

Next steps

Last updated

Was this helpful?