ExAgent.Memory behaviour (ExAgent v2.3.0)

View Source

Long-term memory that an agent curates across runs and sessions.

Memory is a small tree of text files under /memories, one tree per scope (for example one per user, team or project). The agent reads and edits it through one tool, tool/2, whose commands match Anthropic's memory tool (view, create, str_replace, insert, delete, rename), so models trained on that tool use it well, but it is an ordinary function tool and works with any provider.

memory = {ExAgent.Memory.ETS, ExAgent.Memory.ETS}   # or :ets

tool = ExAgent.Memory.tool(memory, scope: fn ctx -> "user:" <> ctx.deps.user_id end)

agent = ExAgent.new(model: model, tools: [tool])
ExAgent.run(agent, "Plan my week", deps: %{user_id: "42"})

The tool description tells the agent to view its memory before it starts, to record durable facts, preferences and progress, and to keep files concise. The host decides the scope: never derive it from model input, or one user could read another user's memory.

Backends

A backend implements this behaviour over one record per scope: the whole tree as a map of path to text, with an integer version for compare-and-swap. Every command loads the tree, applies the change and stores it only if the version is unchanged, retrying a few times on conflict, so concurrent agents sharing a scope never lose each other's edits. Limits keep each tree small (by default 128 KB in at most 100 files), so loading it whole is cheap.

Safety

Memory persists text the model wrote, possibly after reading untrusted tool output, into later runs. The tool tells the agent to treat memory as notes, not instructions, and never to store secrets; hosts should still scope memory narrowly, use read_only: true where an agent must not write, and inspect or clear a scope with files/2, update/3 and clear/2.

Command errors (a missing file, an ambiguous str_replace, a full memory) and an unavailable backend are returned to the model as text starting with Error:, so it can correct the call or continue without memory; only a scope that cannot be resolved fails the run. Telemetry event [:exagent, :memory, :command] reports each command with %{count: 1} and metadata %{command, status}, where status is :ok, :rejected, :busy or :unavailable; the metadata never carries the scope or file content.

Memory edits are effects outside the run: they are not undone when a run fails, and a persisted continuation records the tool result like any other tool.

Summary

Types

t()

A backend and its config, or :ets for the default ETS table.

Callbacks

Load a scope's files and version. An absent scope is {:ok, 0, %{}}.

Store files only if the stored version is still expected (0 means absent). Returns the new version or {:error, :conflict}. Storing %{} may delete the record. A backend must never give a scope a version it had before, even after deleting it, or a stale writer could overwrite newer content.

Check the config when a tool is built, so a misconfigured backend fails at startup rather than on every command. Optional.

Functions

Delete all of a scope's files.

Read a scope's files as a map of path to text.

Render a scope's memory as text to put in the agent's instructions, so the agent starts with it and needs no view round trips.

Build the memory tool for a backend.

Change a scope's files atomically, for seeding, migration or moderation.

Types

files()

@type files() :: %{required(String.t()) => String.t()}

scope()

@type scope() :: String.t()

t()

@type t() :: {module(), term()} | :ets

A backend and its config, or :ets for the default ETS table.

version()

@type version() :: non_neg_integer()

Callbacks

load(config, scope)

@callback load(config :: term(), scope()) :: {:ok, version(), files()} | {:error, term()}

Load a scope's files and version. An absent scope is {:ok, 0, %{}}.

store(config, scope, expected, files)

@callback store(config :: term(), scope(), expected :: version(), files()) ::
  {:ok, version()} | {:error, :conflict | term()}

Store files only if the stored version is still expected (0 means absent). Returns the new version or {:error, :conflict}. Storing %{} may delete the record. A backend must never give a scope a version it had before, even after deleting it, or a stale writer could overwrite newer content.

validate(config)

(optional)
@callback validate(config :: term()) :: :ok | {:error, term()}

Check the config when a tool is built, so a misconfigured backend fails at startup rather than on every command. Optional.

Functions

clear(memory, scope)

@spec clear(t(), scope()) :: :ok | {:error, term()}

Delete all of a scope's files.

files(memory, scope)

@spec files(t(), scope()) :: {:ok, files()} | {:error, term()}

Read a scope's files as a map of path to text.

preload(memory, scope, opts \\ [])

@spec preload(t(), scope(), keyword()) :: {:ok, String.t()} | {:error, term()}

Render a scope's memory as text to put in the agent's instructions, so the agent starts with it and needs no view round trips.

{:ok, memory_text} = ExAgent.Memory.preload(memory, "user:42")
agent = ExAgent.new(model: model, instructions: base <> "

" <> memory_text, tools: [tool])

Whole files are included in path order while they fit in :max_bytes (default 8_000); the remaining files are listed by path so the agent can view them. The text marks the content as notes written in earlier sessions, not instructions, but it does reach the system prompt: preload only scopes whose writers you trust as much as the agent itself.

tool(memory, opts)

@spec tool(t(), keyword()) :: ExAgent.Tool.t()

Build the memory tool for a backend.

Options:

  • :scope (required) — the scope string, or a function of the ExAgent.RunContext returning it (for example from ctx.deps). At most 200 bytes.
  • :name — tool name (default "memory").
  • :description — replaces the default description and memory protocol.
  • :read_only — offer only view (default false).
  • :max_file_bytes — per file (default 32_000).
  • :max_total_bytes — per scope (default 128_000).
  • :max_files — per scope (default 100).

Writes that would exceed a limit fail with a message that asks the agent to condense or delete content; a scope already above a limit (for example seeded by the host) still accepts edits that do not grow it.

update(memory, scope, fun)

@spec update(t(), scope(), (files() -> {:ok, files()} | {:error, term()})) ::
  {:ok, files()} | {:error, term()}

Change a scope's files atomically, for seeding, migration or moderation.

fun receives the current files and returns {:ok, files} or {:error, reason}. Paths must be valid memory paths (/memories/...) and values UTF-8 text; limits are not enforced here. Retries on conflict.