Memory
Core memory files the model edits with Anthropic's memory tool commands, archival facts found by similarity, and recall over a user's earlier messages.
The memory block keeps what an assistant should remember between chats.
It has three parts:
- Core memory: a few small files under
/memoriesthat go into every prompt. The model reads and edits them with the commands of Anthropic's memory tool (view,create,str_replace,insert,delete,rename). - Archival memory: a list of facts with embeddings, searched when the model asks.
- Recall: one embedding per chat message, so the assistant can find what a user said in an earlier chat. Temporary chats get none.
better-supabase add memory # adds tenant, access and vector-search as well| Table | Holds |
|---|---|
memories | Core files (kind core, with a path) and archival facts (archival), each with version |
memory_message_embeddings | One embedding per chat message and user |
Every memory belongs to a namespace: the user (the default), an agent,
a chat or a project of that user, or the organization. A project
namespace names an ai-chat project with projectId, so every chat in the
project can share it. A user reads only their
own memories and the organization's; nobody else reads them, admins
included. Changing organization memory needs the manage permission.
| Permission | Lets a member | Default roles |
|---|---|---|
memory.read | use memory in the tenant | owner, admin, member |
memory.manage | change the organization's memory | owner, admin |
Rename the keys with blocks.memory.permissions.read and .manage.
The maxContent option (100,000 characters by default) limits one memory,
and dimensions and type set the embedding column as in
knowledge. maxItems keeps at most that many
archival facts per user (or per shared namespace) in a tenant: saving one
more forgets the oldest, as forget does. Core memory files don't count.
tenant: false lets personal memory live outside every organization: pass
null as the organization and the memory is the caller's alone. Organization
memory and shared record memory still need an organization.
blocks: {
memory: { options: { tenant: false, maxItems: 500 } },
},Server
Server code calls the memory instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useMemory } = defineDataHooks(
"memory",
(db: AppDb) => db.memory,
);const rows = await db.memory.list({ limit: 50 }).orThrow();"use client";
import { useMemory } from "@/lib/supabase/hooks";
const rows = useMemory({ limit: 50 });| Group | Methods |
|---|---|
core | view, write, strReplace, insert, remove, rename, list |
archival | upsert, search, list, forget, restore, purge |
recall | index, search |
| (top level) | run, render, saveExtracted, embedPending |
Each method takes the organization and an optional namespace, such as
{ scope: "agent", agentId } or { scope: "project", projectId }. The service role passes ownerId to act for
a user. { scope: "record", subject } is memory about one record (any type in the subject registry, such
as a deal): every member reads it, and only admins change it, as with organization memory.
Add private: true to an organization or record namespace to keep a
member's own notes there: the memory gets the caller as its owner, only that
owner reads and changes it, and it needs no manage permission. The service
role names the owner with ownerId.
await db.memory.core
.write(organizationId, "/memories/deal.md", "Call back on Friday.", {
scope: "record",
subject: { type: "deal", id: dealId },
private: true,
})
.orThrow();Paging archival facts
archival.page pages the facts of one namespace by keyset (ADR 1077), with facets and count, and archival.get returns a not_found error for an unknown id. Pass ns to read a namespace other than the caller's own. Sorts are createdAt (newest first), updatedAt, path, useCount and lastUsedAt, kind and category filter by a list of values, and q searches the content. archival.list keeps working and is deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Core memory
const reply = await memory
.run(organizationId, {
command: "create",
path: "/memories/preferences.md",
file_text: "Prefers metric units.\n",
})
.orThrow();run takes one memory tool command and returns the text the model
expects back, such as File created successfully at: /memories/preferences.md.
Paths must stay under /memories. str_replace fails with
MEMORY_NO_MATCH or MEMORY_AMBIGUOUS unless the old text appears once,
and write with expectedVersion fails with MEMORY_CONFLICT when the
file changed. render(organizationId) returns the core files as delimited
text for the system prompt, cut at maxRender characters (8,000).
Archival memory and recall
await memory.archival
.upsert(organizationId, "Works in the Lisbon office")
.orThrow();
const hits = await memory.archival
.search(organizationId, "where do they work")
.orThrow();Search ranks by embedding similarity and full text together.
saveExtracted(organizationId, facts) saves only facts that aren't close
to one already saved (similarity 0.92 by default, dedupeThreshold);
forget(id, { supersededBy }) keeps the old fact but hides it.
saveExtracted embeds every fact in one embedder call.
upsert and saveExtracted take a category (a lowercase slug such as
preference), a confidence from 0 to 1 that weighs the fact's search
score, and an expiresAt after which lists and searches skip it. Each
search counts its hits in useCount and lastUsedAt, so a review screen
can show which facts the agent leans on.
await memory.archival
.upsert(
organizationId,
"Renewal talks start in March",
{ scope: "record", subject: { type: "deal", id: dealId } },
{
category: "fact",
confidence: 0.8,
expiresAt: Temporal.Now.instant().add({ hours: 24 * 90 }),
},
)
.orThrow();forget(id) soft deletes: the fact leaves lists and searches, and
restore(id) brings it back. purge({ retentionDays }) (service role,
default 30 days) removes facts deleted before then and facts past their
expiry; run it on a schedule. Pass organizationId to purge one tenant.
recall.index(message) runs as the service role after a message is
stored; recall.search(organizationId, query, { excludeChat }) returns the
caller's closest earlier messages. Facts saved without an embedder wait
for embedPending(), which embeds a batch in one call and writes it with
one set_memory_embeddings RPC. Each vector is written only while the
fact still has the text it was computed from, so a fact edited meanwhile
stays pending. A wrong number of vectors, mixed lengths or non-finite
numbers fail with the hint EMBEDDING_INVALID. Search sets
hnsw.iterative_scan for its query and puts the caller's value back.
Importing an existing table
importMemories copies the rows of a table you already have into archival
memory and keeps the embeddings they carry, so a large history needs no new
embedding calls. It reads in id order, stores each row through
archival.upsert({ embedding }) and returns lastId, so a failed or sliced
run continues with after.
import { importMemories } from "better-supabase/blocks/memory";
const result = await importMemories({
memory, // createMemory on a service transport
source: pool, // any client with queryRaw, such as createPostgres()
table: "legacy.agent_memories",
organizationId,
columns: { category: "kind", confidence: "score" },
embeddingModel: "text-embedding-3-small",
limit: 5000,
}).orThrow();
// result.imported, result.skipped (rows without content), result.lastIdThe embedding column has to match the memory block's halfvec(1536) length.
Rows are not deduplicated, so continue from lastId instead of running the
same range twice. table and the column names have to be plain identifiers.
archival.upsert also takes embedding and embeddingModel for a single
memory whose vector you already have.
Documents for agent runtimes
memory.documents stores versioned text documents under an opaque scope
key and a path, for runtimes that keep their own memory format, such as
eve's file memory. Only the service role reads and writes them.
const doc = await memory.documents.read("eve", "user:42/notes.md").orThrow();
await memory.documents
.write("eve", "user:42/notes.md", "- Prefers short answers", {
expectedVersion: doc?.version ?? null,
})
.orThrow();A write names the version it read (null when the document must not
exist yet); a stale version fails with the hint MEMORY_DOCUMENT_CONFLICT,
so the caller reads again and retries. expiresIn sets a lifetime in
seconds, and documents.purge() deletes expired documents.
eve uses the table for file memory and for its recall
records.
AI SDK
better-supabase/ai-sdk/memory gives the model the
memory tool, a recall tool, core memory in its instructions and a job that
extracts facts from a conversation.
Hooks
createMemory takes hooks, keyed by method name, that run your code
before and after a call: refuse it with a DbError, rewrite its arguments
or observe the result (see extending blocks). Methods in a group take their hooks under the group's name,
such as hooks: { core: { write: { before } } }.
Without the client
db.memory is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { embedWith } from "better-supabase/ai-sdk/embeddings";
import { createMemory, rpcTransport } from "better-supabase/blocks/memory";
export const memoryFor = (supabase: SupabaseClient, admin: SupabaseClient) =>
createMemory({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
embedder: embedWith("openai/text-embedding-3-small"),
});Last updated on
Knowledge
Documents chunked and embedded per organization, agent, project, chat or user, with hybrid search that ranks full text and vector matches together.
Agents
Saved assistants with their own instructions, model, tools, connectors and knowledge, shared in an organization or a public store with installs and ratings.