Packages

A layered agent framework for Elixir: structured output, tool-calling, streaming, stateful supervised agents, multi-agent sessions, durable persistence, compaction/cost/permissions and MCP — powered by the BEAM.

Current section

Files

Jump to
exagent docs guides memory.md
Raw

docs/guides/memory.md

# Long-term memory

A conversation only remembers its current message history. `ExAgent.Memory`
gives an agent a bounded, scoped set of Markdown/text notes under `/memories`
that persists across conversations, restarts and cluster nodes (with
PostgreSQL) — while `ExAgent.Plan` and `ExAgent.Workspace` add per-run
checklists and sandboxed file mounts.

**What ExAgent simplifies:**

- **Provider-agnostic memory tool:** Implements Anthropic's memory commands
  (`view`, `create`, `str_replace`, `insert`, `delete`, `rename`) as a standard
  function tool that works on *any* model provider.
- **Automatic optimistic concurrency:** Concurrent edits retry safely on
  version conflict, with built-in size quotas and clear error recovery.
- **Optional zero-round-trip preloading:** Inject existing user notes or
  operator policies into the prompt automatically so the agent starts informed.
- **Run-scoped plans & workspaces:** Give agents a structured `write_todos`
  checklist and controlled mounts (`/scratch`, `/notes`, `/results`, or real
  host directories) without custom file-tool plumbing.

## Give an agent memory

Every memory store is partitioned by a host-chosen **scope** (such as a user,
team or project ID). Never derive a scope from model input:

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

agent = ExAgent.new(model: model, tools: [tool])
ExAgent.run(agent, "I'm vegetarian. Suggest a dinner.", deps: %{user_id: "42"})
```

Keep the scope function pure and side-effect-free. Expected model mistakes
(missing files, ambiguous `str_replace` matches) return `{:tool_error, ...}`
so the agent self-corrects without consuming retries; backend read outages let
the agent continue gracefully while reporting telemetry.

Here is a complete offline example seeding a note, letting the agent read it,
and asserting on the tool return:

```elixir
alias ExAgent.{Memory, Models.Test}
alias ExAgent.Message.Part.{ToolCall, ToolReturn}

scope = "delivery-test-#{System.unique_integer([:positive])}"
{:ok, _} =
  Memory.update(:ets, scope, fn _files ->
    {:ok, %{"/memories/delivery.md" => "Delivery moved to Friday."}}
  end)

memory = Memory.tool(:ets, scope: scope, read_only: true)
read = %ToolCall{
  tool_name: "memory",
  tool_call_id: "delivery-note",
  args: %{"command" => "view", "path" => "/memories/delivery.md"}
}

model = %Test{script: [{:tool_calls, [read]}, "I'll check on Friday."]}
agent = ExAgent.new(model: model, tools: [memory])
{:ok, %{status: :succeeded, new_messages: messages}} = ExAgent.run(agent, "Read the delivery note.")

[note] = for message <- messages,
  %ToolReturn{tool_name: "memory", status: :succeeded, content: content} <- message.parts,
  do: content

true = note =~ "Delivery moved to Friday."
:ok = Memory.clear(:ets, scope)
```

## Start with the memory already loaded

Want the agent to see stored notes immediately without spending an extra tool
call? Install `ExAgent.Memory.capability/2` with `preload:` so ExAgent projects
existing notes into the active turn (keeping canonical history clean):

```elixir
memory = ExAgent.Memory.capability(:ets,
  scope: fn ctx -> "user:" <> ctx.deps.user_id end,
  preload: [max_bytes: 8_000]
)

agent = ExAgent.new(model: model, instructions: base_instructions, capabilities: [memory])
```

Files fit within `:max_bytes` (default `8_000`), visiting `:priority_paths`
first and listing remaining paths for on-demand `view` calls. (Inside durable
`Composition` / `Flow` steps, use `Memory.tool/2` instead of preload.)

### Load operator guidance

For read-only company policies or operator runbooks, set `read_only: true` and
`preload: [mode: :system]` on a strictly operator-controlled scope:

```elixir
guidance = ExAgent.Memory.capability(:ets,
  scope: "operator:policy",
  read_only: true,
  preload: [mode: :system]
)

agent = ExAgent.new(model: model, instructions: base_instructions, capabilities: [guidance])
```

### Render a fixed block

Use `ExAgent.Memory.preload/3` directly when you want full control over where
notes are placed — or pin operator guidance in a versioned agent definition
when durable approval resumes must see the exact reviewed text:

```elixir
{:ok, notes} =
  ExAgent.Memory.preload(:ets, "user:42",
    max_bytes: 512,
    priority_paths: ["/memories/preferences.md"]
  )
```

## Store memory durably

`:ets` lives in node RAM (great for dev and tests). For multi-node persistence
across deploys, apply the unified ExAgent migration on your PostgreSQL Repo
([Store rollout](migration.md#upgrade-postgresql-and-roll-out-a-store-format-level))
and point `Memory.tool/2` or `Memory.capability/2` at `ExAgent.Memory.Postgres`:

```elixir
tool = ExAgent.Memory.tool({ExAgent.Memory.Postgres, MyApp.Repo}, scope: "team:7")
```

- **Safe concurrency:** Every write uses optimistic version checks and retries
  automatically on conflict. Pass `overwrite_on_create: false` when multiple
  agents share a scope and should not overwrite an existing filename with
  `create`.
- **Privacy & telemetry:** PostgreSQL queries suppress Ecto logs so private
  notes never leak into SQL logs; monitor command counts via
  `[:exagent, :memory, :command]`.
- **Unconfirmed writes:** If a database write outcome is uncertain, the tool
  returns `:unknown` and persisted continuations wait for
  [explicit reconciliation](durability-and-approvals.md#reconcile-an-effect)
  rather than guessing.
- **Custom backends:** Implement `ExAgent.Memory` (`load/2`, `store/4` and
  optional `validate/1`).

## Save a reviewed edit

Building an admin or user UI to edit an agent's memory files? Guard against
lost concurrent edits by computing a digest when opening the form and checking
it inside `ExAgent.Memory.update/3`:

```elixir
digest = fn files ->
  entries = Enum.sort(files)
  :crypto.hash(:sha256, :erlang.term_to_binary(entries, minor_version: 1))
end

{:ok, files} = ExAgent.Memory.files(memory, scope)
reviewed_digest = digest.(files)
```

When the user submits `edited_files`:

```elixir
ExAgent.Memory.update(memory, scope, fn current ->
  if digest.(current) == reviewed_digest do
    {:ok, edited_files}
  else
    {:error, :stale}
  end
end)
```

On `{:error, :stale}`, keep the user's draft and show the refreshed files so
nothing is silently overwritten.

## Keep memory safe and small

- **Built-in quotas:** Default 32 KB per file, 128 KB total across up to 100
  files per scope. Exceeding a quota asks the model to condense notes cleanly.
- **Paged reads:** Models read large files in slices via `view_range`
  (e.g., `[26, 50]` or `[26, -1]`) and insert cleanly with `insert_line`.
- **Read-only mode:** Pass `read_only: true` when an agent should read but
  never modify memory.
- **Treat notes as untrusted data:** Memory can reflect earlier tool output;
  keep scopes narrow and inspect or clear them with `Memory.files/2`,
  `Memory.update/3` and `Memory.clear/2`.

## Give a run a plan and a workspace

For multi-step tasks, combine the candidate `ExAgent.Plan.capability/1` (a
structured `write_todos` checklist projected into `result.plan`) with the
candidate `ExAgent.Workspace.capability/1` (mounted virtual or real text files):

```elixir
alias ExAgent.{Plan, Workspace}
alias ExAgent.Message.Part.ToolCall

item = %{"id" => "verify", "content" => "Check the receipt", "status" => "pending"}
call = %ToolCall{tool_name: "write_todos", tool_call_id: "plan-1", args: %{"items" => [item]}}
model = %ExAgent.Models.Test{script: [{:tool_calls, [call]}, "Ready."]}

workspace = Workspace.capability(mounts: [
  {"/scratch", :scratch, :read_write},
  {"/notes", Workspace.memory(:ets, fn ctx -> ctx.deps.scope end), :read_only}
])
agent = ExAgent.new(model: model, capabilities: [Plan.capability(), workspace])
{:ok, result} = ExAgent.run(agent, "Make a plan.", deps: %{scope: "project:42"})
[^item] = result.plan
```

`Plan` reminds the model of its current checklist on each step without mutating
canonical history, and reconstructs cleanly on durable continuation resume.

### Mounted text files

`Workspace` gives the agent six bounded text-file tools (`ls`, `read_file`,
`write_file`, `edit_file`, `glob`, `grep`) across any mix of mounts:

| Mount backend | Mode | Best for |
|---|---|---|
| `:scratch` | `:read_write` | Ephemeral per-run working files (auto-cleaned when the run ends; reconstructed on durable resume). |
| `Workspace.memory(backend, scope)` | `:read_only` / `:read_write` | Exposing an `ExAgent.Memory` scope through standard file tools. |
| `Workspace.results(store)` | `:read_only` | Reading offloaded `Tool.OutputLimit` references at `/results/<ref>` ([PostgreSQL result storage](tools-and-output.md#keep-references-readable-after-an-application-restart)). |
| `Workspace.directory("/path")` | `:read_only` / `:read_write` | Host-controlled POSIX directories with device/inode verification and atomic `.exagent-write-lock` writes. |

Protect writable mounts with standard `ExAgent.Permissions` rules (for example,
`[{"write_file", :ask}, {"edit_file", :ask}]`), and tune scan/file caps with
`:max_entries`, `:max_results`, `:max_file_bytes` and `:max_total_bytes`.
Custom backends implement `ExAgent.Workspace.Backend`.

API: `ExAgent.Memory`, `ExAgent.Memory.Postgres`, `ExAgent.Plan`,
`ExAgent.Workspace`, `ExAgent.Workspace.Backend`.