Personal Assistant Memory

Save what each user tells your assistant (preferences, ongoing projects, useful facts) and recall the relevant pieces in later sessions, instead of growing the system prompt.

How it fits together

  • Each user gets one container, for example container:memory-42, and is its editor.
  • Reads and writes go through a client that acts as that user, so one user's memories can never show up in another user's results.
  • Each memory is one record: its vector, plus its text and a few fields such as kind and saved_at in metadata.
  • Your app decides what is worth remembering. SwarmV stores and searches; it doesn't pick facts out of conversations by itself.

Remember, recall and forget

The embedding providers ship with the SDK from version 1.4. Any other embedding function works too, as long as you use the same model and dimensions for saving and searching.

TypeScript
// Your backend. Runs with your API key; each user's memories go in their own container.
import { SwarmV, OpenAIEmbeddings } from "@swarmv/sdk";

const swarmv = new SwarmV();                                   // SWARMV_API_KEY from the environment
const embedder = new OpenAIEmbeddings({ dimensions: 768 });    // OPENAI_API_KEY from the environment
const containerOf = (userId: string) => `container:memory-${userId}`;

// Once per user, e.g. at sign-up: make them the editor of their own memory container.
export async function createMemory(userId: string) {
  await swarmv.graph.createRelation(`user:${userId}`, "editor", containerOf(userId));
}

// A client that acts as one user, so it can only read and write that user's memories.
// It mints a new token by itself whenever the old one expires.
const clients = new Map<string, SwarmV>();
function memoryOf(userId: string) {
  let client = clients.get(userId);
  if (!client) {
    client = new SwarmV({ getToken: () => swarmv.generateUserToken(`user:${userId}`) });
    clients.set(userId, client);
  }
  return client;
}

const newId = () => String(crypto.getRandomValues(new Uint32Array(1))[0]);  // IDs are 32-bit integers

export async function remember(userId: string, text: string, kind = "fact") {
  const id = newId();
  const [vector] = await embedder.embedDocuments([text]);
  // insertMany sends right away and throws if the write is refused (insert() batches for 50 ms).
  await memoryOf(userId).insertMany([{
    id,
    vector,
    metadata: { container_id: containerOf(userId), kind, text, saved_at: Date.now() },
  }]);
  return id;
}

export async function recall(userId: string, question: string, topK = 5) {
  const hits = await memoryOf(userId).search(await embedder.embedQuery(question), { topK, fresh: true });
  return hits.map((h) => ({ id: h.id, text: String(h.metadata?.text ?? "") }));
}

export async function forget(userId: string, id: string) {
  await memoryOf(userId).delete(id, { containerId: containerOf(userId) });
}
Python
import secrets, time
from swarmv import SwarmV, OpenAIEmbeddings

swarmv = SwarmV()                                   # SWARMV_API_KEY from the environment
embedder = OpenAIEmbeddings(dimensions=768)         # OPENAI_API_KEY from the environment
container_of = lambda user_id: f"container:memory-{user_id}"

def create_memory(user_id: str) -> None:
    # Once per user, e.g. at sign-up.
    swarmv.create_relation(f"user:{user_id}", "editor", container_of(user_id))

_clients: dict[str, SwarmV] = {}
def memory_of(user_id: str) -> SwarmV:
    # A client that acts as this user; it fetches a new token whenever the old one expires.
    if user_id not in _clients:
        _clients[user_id] = SwarmV(token_provider=lambda: swarmv.generate_user_token(f"user:{user_id}"))
    return _clients[user_id]

def remember(user_id: str, text: str, kind: str = "fact") -> str:
    id_ = str(secrets.randbits(32))                 # IDs are 32-bit integers
    memory_of(user_id).insert_many([{
        "id": id_,
        "vector": embedder.embed_documents([text])[0],
        "metadata": {"container_id": container_of(user_id), "kind": kind, "text": text,
                     "saved_at": int(time.time() * 1000)},
    }])
    return id_

def recall(user_id: str, question: str, top_k: int = 5) -> list[dict]:
    hits = memory_of(user_id).search(embedder.embed_query(question), top_k=top_k, fresh=True)
    return [{"id": h.id, "text": (h.metadata or {}).get("text", "")} for h in hits]

def forget(user_id: str, id_: str) -> None:
    memory_of(user_id).delete(id_, container_id=container_of(user_id))

fresh: true makes a memory searchable the moment it's saved. A new user's access takes a few seconds to reach the edge, so create their container at sign-up rather than right before the first write. Random IDs are fine for personal memory; if you also keep memories in your own database, store the ID there so you can update or forget them later.

Using it in a conversation

TypeScript
// In a chat turn: recall first, answer with what you found, then save what's worth keeping.
const memories = await recall(user.id, message);

const reply = await llm([
  { role: "system", content: `What you know about this user:\n${memories.map((m) => "- " + m.text).join("\n")}` },
  { role: "user", content: message },
]);

// Your app decides what to remember. A common approach: ask the model for new lasting facts.
const facts = await llm([
  { role: "system", content: "List any lasting facts or preferences the user just shared, one per line. Reply NONE if there are none." },
  { role: "user", content: message },
]);
for (const fact of facts.split("\n").map((f) => f.trim()).filter((f) => f && f !== "NONE")) {
  await remember(user.id, fact, "preference");
}

To share memory across a team instead of one user, give a group access to a shared container (see Authentication). For several agents working on the same task, see Multi-Agent State.