ExAgent. Memory behaviour
(ExAgent v3.0.0)
View Source
Long-term memory that an agent curates across runs and sessions.
Stability — Stable.
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"})capability/2 contributes the same tool. By default the model reads notes
through a tool call. Pass preload: true to include them as background data
in the active user turn.
agent = ExAgent.new(model: model, capabilities: [ExAgent.Memory.capability(memory, scope: scope)])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
edit loads the tree and stores the change only if the version is unchanged.
On conflict the command retries against the latest tree. A create based on
an earlier view can still overwrite another agent's edit to the same file.
Use str_replace for a targeted edit. It requires the old text to match
exactly once in the current file. Limits keep each tree small (by default
128 KB in at most 100 files), so loading it whole is cheap.
ExAgent.Memory.ETS— in memory, per node; the library starts a default table namedExAgent.Memory.ETS, and:etsis a shortcut for it.ExAgent.Memory.Postgres— durable, through the host'sEcto.Repo.
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 rejections (a missing file, an ambiguous str_replace, a full memory),
a busy scope and backend load failures return a :tool_error result whose
text starts with Error:. The model can correct the request or continue
without memory; the run continues and no tool retry is spent. An unconfirmed write ends the
run with an :unknown tool return and reason :memory_write_unconfirmed.
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. The
preload of capability/2 reports command: :preload with :ok or
:unavailable.
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
Callbacks
Erase an exact storage scope for ExAgent.Retention.erase/3 after its writers quiesce.
Load a scope's files and version. Version 0 is reserved for an absent
scope and must be returned as {:ok, 0, %{}}.
If this callback throws a term, the host API returns
{:error, {:memory_backend_throw, term}}.
Store files only if the stored version is still expected (0 means
absent). On success, return a fresh positive version even if the files
are identical. Positive versions are opaque and must never be reused for
a scope, even after deleting it. Reuse could let a stale writer overwrite
newer content. Storing %{} may leave the scope absent and return {:ok, 0}.
Use {:error, :conflict} when the compare-and-swap rejects the write.
An expected version outside the backend's representable range also conflicts.
A thrown term returns the same host error as in load/2. The tool
reports the write as unconfirmed, including when the term is :conflict.
Check the config when a tool is built, so a misconfigured backend fails at startup rather than on every command. Optional.
Functions
Build a capability that gives the agent the memory tool. A view returns
notes as tool data and counts against the run's tool-call budget.
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
Callbacks
@callback erase_scope(config :: term(), scope()) :: ExAgent.Retention.outcome() | {:error, term()}
Erase an exact storage scope for ExAgent.Retention.erase/3 after its writers quiesce.
Load a scope's files and version. Version 0 is reserved for an absent
scope and must be returned as {:ok, 0, %{}}.
If this callback throws a term, the host API returns
{:error, {:memory_backend_throw, term}}.
@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). On success, return a fresh positive version even if the files
are identical. Positive versions are opaque and must never be reused for
a scope, even after deleting it. Reuse could let a stale writer overwrite
newer content. Storing %{} may leave the scope absent and return {:ok, 0}.
Use {:error, :conflict} when the compare-and-swap rejects the write.
An expected version outside the backend's representable range also conflicts.
A thrown term returns the same host error as in load/2. The tool
reports the write as unconfirmed, including when the term is :conflict.
Check the config when a tool is built, so a misconfigured backend fails at startup rather than on every command. Optional.
Functions
@spec capability(t(), keyword()) :: ExAgent.Capability.t()
Build a capability that gives the agent the memory tool. A view returns
notes as tool data and counts against the run's tool-call budget.
memory_cap =
ExAgent.Memory.capability(:ets,
scope: fn ctx -> "user:" <> ctx.deps.user_id end,
preload: [max_bytes: 8_000]
)
agent = ExAgent.new(model: model, capabilities: [memory_cap])It accepts every option of tool/2 plus :preload:
false(default) — contribute only the tool.true— add stored notes to the active user turn as data.- A keyword list — set
:mode(:databy default),:max_bytes(default8_000) or:priority_paths(default[]).mode: :systemrequiresread_only: trueand a scope whose writers the operator controls.
The capability loads and renders the scope once per run attempt, before its first fresh model request. The block identifies its source and stays in the request projection. Its byte limit includes framing, escaped files, path listings and notices. If the framing cannot fit, the projection omits the block. The tool remains available for follow-up reads.
A scope resolution error fails the run as
{:capability_failed, ExAgent.Memory.Capability, hook, {:throw, reason}}.
The hook is :preload in data mode and :instructions in system mode.
A backend load failure produces a bounded notice and the telemetry metadata
%{command: :preload, status: :unavailable}.
Durable Composition and Flow reject preloading with
{:unsupported, :composition_request_projection}. Unknown or duplicate
options, including those inside :preload, raise ArgumentError.
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.
{: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 by default. Pass :priority_paths
to put exact files first in the given order. Missing paths and directories
are skipped. Paths use the memory tool's normalization and must be unique
after normalization. Remaining files follow in path order.
At the first file that does not fit in :max_bytes (default 8_000),
preloading switches to listing the remaining paths in the same order.
The budget covers the entire block, including the surrounding instructions,
separators, escaped file text and any listing. Returns {:ok, ""} if the
framing or the empty-memory notice cannot fit. Preload only scopes whose
writers you trust as much as the agent itself, because their notes reach the
system prompt.
Unknown or duplicate options raise ArgumentError before loading memory.
@spec tool(t(), keyword()) :: ExAgent.Tool.t()
Build the memory tool for a backend.
Options:
:scope(required) — the scope string, or a function of theExAgent.RunContextreturning it (for example fromctx.deps). At most 200 bytes. Keep the selector free of side effects. If it raises, throws or exits, the tool fails before reading or writing memory. Its reason is{:memory_scope_failed, kind}, wherekindis the exception module,:throwor:exit.:name— tool name (default"memory").:description— replaces the default description and memory protocol.:read_only— offer onlyview(defaultfalse).:overwrite_on_create— allowcreateto replace an existing file (defaulttrue). Set tofalseto require a new path even when a concurrent edit forces a retry. Ignored for a read-only tool.:max_file_bytes— per file (default32_000).:max_total_bytes— per scope (default128_000).:max_files— per scope (default100).
Unknown or duplicate options raise ArgumentError when building the tool.
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.
For a file view, the first line of view_range must exist. A range
ending past the last line returns the remaining lines with their original numbers.
A bounded page stops rendering at the requested end line after the scope is loaded.
Line insertion scans to the requested position and builds the updated file
as a binary. New lines use CRLF when the existing file uses CRLF throughout.
@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}. Return a plain map from valid memory paths
(/memories/...) to UTF-8 text. On a version conflict the
callback may run again with the latest files. Keep external effects outside it.
For edits prepared from a prior read, compare the current files (or their
digest) with what the user reviewed inside the callback. Returning
{:error, :stale} there preserves a concurrent edit.
Tool limits apply only to model edits. A store error other than :conflict
can follow a committed write. Confirm the outcome, for example with
files/2 after the pending write settles, before repeating the edit.