Mental model and architecture
View SourceIf you are coming to ExAgent for the first time, this page gives you the whole picture in five minutes: how the pieces fit together, what complexity ExAgent removes from your app, and which primitive to choose for a given job.
The 10-second mental model
ExAgent separates definition from execution, and execution from stateful OTP supervision:
%ExAgent{} (immutable blueprint — like an Ecto.Query or Req.Request)
├─ model: provider string, ReqLLM struct, local Ollama/vLLM, or Test
├─ instructions: static system prompts + per-run dynamic functions
├─ tools: Elixir functions with derived JSON Schemas & guards
├─ output: plain :text, JSON Schema, or validated Ecto embedded_schema
└─ limits: max_steps, usage_limits, rate_limiter, spend_budget
│ pass the same blueprint into whichever layer you need:
▼
┌─────────────────────────────────────────────────────────────────────┐
│ 1. One-shot Run ExAgent.run/3, ExAgent.run_stream/3 │
│ Stateless model ⇄ tool loop. No database, no GenServer needed. │
├─────────────────────────────────────────────────────────────────────┤
│ 2. Conversation ExAgent.Server, ExAgent.Conversations │
│ Supervised process owning history, queue, backpressure & events. │
├─────────────────────────────────────────────────────────────────────┤
│ 3. Durability store: + ExAgent.Continuation + ExAgent.resume │
│ Confirmed checkpoints & crash-safe human approval pauses. │
├─────────────────────────────────────────────────────────────────────┤
│ 4. Coordination run_child, Handoff, Session, Composition, Flow │
│ Multi-agent delegation, shared state & durable pipelines. │
└─────────────────────────────────────────────────────────────────────┘Three ideas unlock the entire library:
- An
%ExAgent{}is just a struct. It holds no processes, no sockets and no conversation history. Build it once, store it in a module function, and reuse it safely across thousands of concurrent tasks or LiveViews. - One loop powers everything. Whether you call
ExAgent.run/3in a Mix task, stream tokens to a LiveView throughExAgent.Server, or pause a tool for human review in PostgreSQL, the exact same model ⇄ tool ⇄ validation loop runs underneath. - Every layer above
run/3is opt-in. You never pay for Oban, PostgreSQL, PubSub or OpenTelemetry until you explicitly opt into them.
What ExAgent simplifies
Without an agent framework, wiring a single LLM feature into a production Elixir app quickly accumulates subtle infrastructure bugs. Here is what ExAgent takes off your plate:
| Problem you normally hand-roll | What ExAgent gives you instead |
|---|---|
| Writing and syncing JSON Schemas for every tool and output | deftool derives JSON Schemas from Elixir type annotations; output: MyEctoSchema derives schemas from Ecto.Schema and validates with your changeset/2. |
| Models returning malformed JSON or violating constraints | Automatic local validation and self-correction retries (output_retries, tool argument retries, and malformed-envelope batch recovery) before your code ever sees the value. |
| GenServers for streaming chat, cancellation and UI reconnects | ExAgent.Server + ExAgent.Conversations give you bounded queues, idempotency keys, live cancellation, demand-paced event cursors (events_since/3 + ack_events/4), and SSE / AI SDK / AG-UI adapters. |
| Pausing for human approval without double-charging on crash | ExAgent.Continuation records an atomic checkpoint before executing effects and never guesses or replays an uncertain external call after a crash. |
| Runaway token bills or sub-agents blowing past budgets | Unified UsageLimits, RateLimiter, and ExAgent.UsageLimits.Budget (spend_budget: (candidate)) enforced across parent runs and every delegated child. |
| Flaky, expensive tests that hit live LLM APIs | ExAgent.Models.Test scripted models, cassette recording/replay, and ExAgent.Eval CI quality gates run 100% offline. |
Choosing the right pattern
Reach for the simplest primitive that solves your problem. You can always move down this table later without rewriting your tools or Ecto output schemas.
| What you are building | Use this | What it simplifies | Skip it when… |
|---|---|---|---|
| Data extraction, classification, summarization, or an Oban worker | ExAgent.run/3 | One function call returns {:ok, %ExAgent.Result{output: struct}} or {:error, %ExAgent.RunError{partial: ...}}. | You need multi-turn history managed automatically or live streaming tokens. |
| Streaming CLI output or one-shot HTTP SSE endpoint | ExAgent.run_stream/3 (or ExAgent.Chat.SSE) | Lazily streams typed events (:text_delta, :tool_call_started, :result) while keeping the same validation guarantees. | You need persistent multi-turn chat state across browser reconnects. |
| Multi-turn chat in Phoenix LiveView | ExAgent.Server + ExAgent.Conversations | Manages conversation history, bounded queues, turn steering, conversation forking and idle hibernation/eviction. | You only run single prompt → response jobs. |
| High-risk actions (refunds, deletes, external writes) needing human sign-off | store: + ExAgent.Continuation + ExAgent.resume/3 | Pauses cleanly on approval/deferral, survives deploys and node restarts, authorizes reviewers per request, and resumes safely. | Every tool is read-only and idempotent, and losing an in-flight request on deploy is acceptable. |
| Slow research/scraping work spawned by an agent | ExAgent.Jobs (or ExAgent.Jobs.Durable) | Returns a job ID immediately so the agent keeps talking to the user and checks or receives results asynchronously. | The tool completes quickly within :tool_timeout. |
| A manager agent calling specialist sub-agents as tools | ExAgent.Coordination.delegation_tool/2 or ExAgent.run_child/4 | Child runs inherit ancestor permissions, cancellation, deadlines and token/cost budgets automatically. | You want the specialist to take over the conversation directly instead of reporting back to the manager. |
| Triage routing where a specialist takes over the user's turn | ExAgent.Handoff (candidate) | Exposes transfer_to_<id> tools that hand a bounded, provider-neutral history view to the destination agent. | The parent needs to aggregate multiple specialists' answers before replying. |
| Multiple agents collaborating over shared structured state | ExAgent.Session | Gives all participants one supervised state writer and a pluggable turn policy (round-robin, supervisor, initiative). | A single agent or simple manager-to-child delegation is enough. |
| Deterministic multi-step chains, routers or bounded parallel fan-out | ExAgent.Coordination.Composition / ExAgent.Coordination.Flow | Runs fixed Elixir-controlled pipelines and parallel branches with ordered results and the same approval/durability model. | You want the LLM itself to decide every next step dynamically. |
One domain, three stages
To see how these layers compose without rewriting application code, watch a single order-refund assistant grow from a one-shot script to a LiveView chat to a crash-safe approval workflow.
Define your tools and typed output once
defmodule MyApp.BillingTools do
use ExAgent.Tools
@doc "Look up an order's status and total amount in cents."
deftool lookup_order(_ctx, order_id :: String.t()), effect: :read do
{:ok, %{order_id: order_id, status: "delivered", amount_cents: 4_500}}
end
@doc "Issue a refund for an order."
deftool issue_refund(_ctx, order_id :: String.t(), amount_cents :: integer()),
effect: :write do
# Your payment gateway call goes here.
{:ok, %{refunded: true, order_id: order_id, amount_cents: amount_cents}}
end
end
defmodule MyApp.RefundSummary do
use Ecto.Schema
@primary_key false
embedded_schema do
field :order_id, :string
field :action, :string
field :summary, :string
end
def changeset(struct, attrs) do
struct
|> Ecto.Changeset.cast(attrs, [:order_id, :action, :summary])
|> Ecto.Changeset.validate_required([:order_id, :action, :summary])
|> Ecto.Changeset.validate_inclusion(:action, ["refunded", "declined", "escalated"])
end
endNow build the reusable %ExAgent{} blueprint:
refund_agent =
ExAgent.new(
name: "refund_assistant",
model: "anthropic:claude-sonnet-5-5",
instructions: "Verify the order before refunding. Summarize the final action.",
tools: MyApp.BillingTools.tools(),
output: MyApp.RefundSummary,
usage_limits: %ExAgent.UsageLimits{request_limit: 5, tool_calls_limit: 4}
)Stage 1: Stateless one-shot run (scripts & Oban workers)
When a background job just needs an answer and no human needs to intervene:
{:ok, result} =
ExAgent.run(refund_agent, "Check order #1042 and explain whether it can be refunded.",
permissions:
ExAgent.Permissions.new!(
rules: [{"lookup_order", :allow}, {"issue_refund", :deny}],
default: :deny
)
)
%MyApp.RefundSummary{order_id: "1042", action: action, summary: summary} = result.outputNotice that permissions: is passed per run, not hardcoded on the agent. The
same refund_agent definition can run read-only in a background triage job and
approval-gated in an interactive dashboard.
Stage 2: Supervised multi-turn conversation (Phoenix LiveView)
When a support rep wants a live multi-turn chat with streaming deltas and
history persisted across idle eviction, supervise an ExAgent.Conversations
manager backed by a Store (ETS in dev, PostgreSQL in production):
# In your application supervision tree:
{ExAgent.Conversations,
name: MyApp.Chats,
server: fn {namespace, id} ->
[agent: refund_agent, namespace: namespace, agent_id: id, store: store]
end}
# Inside your LiveView mount/3:
{:ok, server} = ExAgent.Conversations.ensure(MyApp.Chats, {"tenant-acme", "ticket-1042"})
:ok = ExAgent.Server.attach(server, self(), delivery: :demand)
{:ok, page} = ExAgent.Server.history_page(server, projection: :chat, include_draft: true)
{:ok, _receipt} = ExAgent.Server.send_message(server, "Look up order #1042", stream_text: true)In :demand mode, your LiveView receives a single lightweight
{:exagent_events_ready, server, notice} signal per burst, reads a bounded
page of %ExAgent.Event{} structs with ExAgent.Server.events_since/3 (or
ExAgent.Chat.Reader.notice/3), applies the update, and acknowledges the new
cursor with ExAgent.Server.ack_events/4 (PubSub is the separate channel that
delivers {:exagent_event, event} directly). See
Read conversation events on demand.
When no viewers are attached and the conversation goes idle, Conversations
hibernates and evicts the process automatically and restores it lazily from
store on the next message.
Stage 3: Crash-safe human approval (PostgreSQL durability)
Now ask for approval on issue_refund via ExAgent.Permissions (or
ExAgent.Toolset.require_approval/2) and add a scoped store and
continuation_config (see
Configure an agent continuation):
# 1. Run pauses *before* issue_refund executes and writes a confirmed checkpoint.
{:ok, %{status: :paused, continuation: paused_ref}} =
ExAgent.run(refund_agent, "Refund order #1042 in full.",
continuation: continuation_config,
permissions:
ExAgent.Permissions.new!(
rules: [{"lookup_order", :allow}, {"issue_refund", :ask}],
default: :deny
)
)
# 2. Hours later (even after a deploy), an authorized manager approves it.
# Capture the NEW continuation reference returned by decide/4 (it stays nil
# until every pending approval on the run is resolved):
{:ok, [request]} = ExAgent.Continuation.pending(store, paused_ref.id)
{:ok, %{status: :approved, continuation: approved_ref}} =
ExAgent.Continuation.decide(store, request, :approve,
actor: current_manager,
authorize: &MyApp.Approvals.authorize/3
)
# 3. Resume with approved_ref (never the old paused_ref) to run the tool once:
{:ok, %{status: :succeeded, output: %MyApp.RefundSummary{action: "refunded"}}} =
ExAgent.resume(refund_agent, approved_ref, continuation: continuation_config)Your tools, Ecto schema and instructions did not change across any of the three stages.
Understanding the ownership boundary
ExAgent draws a clear line between what the framework guarantees and what your application owns. Knowing this boundary upfront prevents surprises in production:
- ExAgent owns the model/tool execution loop, JSON Schema and changeset validation, retry budgets, bounded mailboxes/history, confirmed store checkpoints, and OTP cleanup of framework-owned processes.
- Your application owns provider credentials, business authorization
(
authorize/3and:permissions), database/Oban supervision, and reconciling any external side effect whose network outcome was interrupted mid-flight. - Unknown is never zero. If a provider omits token counts or a tool crashes
after sending an HTTP request to Stripe, ExAgent reports the value as unknown
or
:uncertainrather than inventing0or blindly retrying an unconfirmed effect.
Where to go next
- Hands-on in 5 minutes: Getting started
- Tools, permissions & Ecto schemas: Tools and structured output
- Cloud & local models (Ollama/vLLM) + budgets: Models, budgets and limits
- LiveView streaming & Conversations: Runtime and events
- Crash-safe approvals & PostgreSQL: Durability and approvals
- Multi-agent delegation, handoffs & workflows: Coordination
- Layer-by-layer ownership reference: Architecture and ownership