Getting started

View Source

This guide gets you from zero to a working ExAgent application in five minutes. You will run your first agent offline without API keys, carry a multi-turn conversation, handle success, pauses and failures cleanly, connect a real cloud or local model, and optionally scaffold a full Phoenix LiveView chat with durable human approvals.

Want the big picture first?

Read Mental model and architecture for a quick map of ExAgent's layers and a decision table showing which primitive to pick for scripts, LiveViews, approvals and multi-agent workflows.

Install ExAgent

Add ExAgent 3.0 to your mix.exs dependencies:

def deps do
  [{:exagent, "~> 3.0.0"}]
end

Working against a local source checkout? Point at the clone beside your app with {:exagent, path: "../exagent"}.

Run mix deps.get, then open iex -S mix. ExAgent targets Elixir 1.18 / OTP 28 and Elixir 1.20 / OTP 29 (see Supported features and limits) and starts its own lightweight supervision tree automatically — a one-shot run needs no database, Phoenix or tracing setup.

If your application manages its own environment variables and you do not want stock ReqLLM reading a .env file from your working directory, disable dotenv loading in config/config.exs before application startup:

import Config
config :req_llm, load_dotenv: false

Before supplying live credentials, you can inspect any model profile and see which optional integrations are installed with mix exagent.doctor:

mix exagent.doctor --model openai:gpt-5.5
mix exagent.doctor --model test --json

mix exagent.doctor inspects the local catalogue offline. To verify a live Store, Repo, or Recovery supervisor in your host app, see Inspect an installation. To test companion packages from local release TARs, see Try local release candidates together.

Run your first agent

Start with the built-in "test" model so you can verify your wiring and result handling before making a single network call:

agent = ExAgent.new(model: "test", instructions: "Be concise.")
{:ok, result} = ExAgent.run(agent, "Hello!")

%{output: result.output, status: result.status, requests: result.request_count}
# => %{output: "a test response", status: :succeeded, requests: 1}

What just happened — and what this simplifies:

  • ExAgent.new/1 creates an immutable blueprint (%ExAgent{}). It holds no process or conversation state, so you can build it once and reuse it safely across concurrent requests.
  • "test" is a deterministic in-process adapter that runs the exact same loop as Anthropic, OpenAI, Gemini, Ollama or vLLM. You can test tools, retries, limits and approvals with zero network latency or cost.
  • Every ExAgent constructor validates its keyword options eagerly: an unknown, duplicate or malformed option raises ArgumentError naming the key (never leaking a secret value) before any IO happens. When overriding defaults, merge with Keyword.merge(defaults, overrides).

Keep a conversation

Because %ExAgent{} is stateless, a follow-up turn in a script or background job simply passes the previous messages and updated model forward:

{:ok, first} = ExAgent.run(agent, "Hello!")
{:ok, second} =
  ExAgent.run(%{agent | model: first.model}, "And next?",
    message_history: first.messages
  )
second.output

Always carry both first.messages and first.model (stateful adapters like scripted test models track their cursor on the model struct). Need to store history in a database column or cache? Serialize with ExAgent.Message.to_json/1 and restore with {:ok, history} = ExAgent.Message.from_json(json) (preserving each tool return's content field; JSON null restores as nil).

When to upgrade to ExAgent.Server: Passing message_history: manually is great for short scripts and background jobs. Once you have interactive users, concurrent messages, streaming UI updates or cancellation, wrap the same agent in ExAgent.Server instead of writing your own GenServer.

Handle success and failure

In production, an agent run has three meaningful outcomes: it succeeded with validated output, it paused waiting for human approval or an external tool result, or it failed operationally with partial progress attached:

case ExAgent.run(agent, "Hello!") do
  {:ok, %{status: :succeeded, output: output}} ->
    {:answer, output}

  {:ok, %{status: :paused, continuation: reference}} ->
    {:paused, reference}

  {:error, %ExAgent.RunError{reason: reason, partial: partial}} ->
    {:failed, reason, partial.status}
end

Why ExAgent returns partial on error: Suppose your agent called a database or payment tool on step 1, then hit a network timeout on step 2. Rather than discarding everything, %ExAgent.RunError{} hands you partial — containing the messages, tool returns and usage recorded up to the failure — so your app can inspect or reconcile what already happened.

  • When a run returns :paused, save reference and follow the approval workflow.
  • Avoid logging raw %ExAgent.Result{} or %ExAgent.RunError{} structs verbatim in production; live model adapters can carry credentials, so log an explicit projection (result.run_id, result.status, result.usage).

Connect a real model

Swapping from "test" to a real cloud or local model takes one line.

Cloud providers (environment keys): Set ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY or OPENROUTER_API_KEY and pass the model string:

agent =
  ExAgent.new(
    model: "anthropic:claude-sonnet-5-5",
    instructions: "Be concise."
  )

ExAgent resolves the provider profile from its catalogue via stock ReqLLM and reads the environment variable per request without storing it on the struct.

Per-tenant / explicit credentials: Build the adapter directly with ExAgent.Models.ReqLLM.new/1 and api_key: — see Models, budgets and limits for explicit keys, local Ollama / vLLM / llama.cpp servers, rate limiting and spend budgets.

Verify your deployed endpoint

A catalogue entry gives ExAgent the right wire profile, not a guarantee that a custom proxy or local model follows every protocol rule. Before shipping to production, run a tool call, streamed reply and structured output against your exact endpoint (or use mix exagent.qualify). See Supported features and limits.

Generate a Phoenix chat

Want a complete, production-structured Phoenix 1.8 LiveView chat with PostgreSQL persistence, Oban background recovery, streaming UI and durable approvals wired up automatically? Use the Igniter installer:

mix archive.install hex phx_new
mix archive.install hex igniter_new
mix phx.new my_app --no-install
cd my_app
mix igniter.install exagent --chat --yes
mix setup
mix test
mix exagent.doctor --model test --check-store --check-recovery --check-catalog-lock

--check-recovery is a candidate Doctor switch.

What the generator builds for you:

  • Adds Oban, runs the unified ExAgent PostgreSQL migrations, supervises ExAgent.Continuation.Recovery, and generates priv/exagent/catalog.lock (commit this file alongside your generated modules).
  • Generates a LiveView chat at /chat backed by ExAgent.Conversations, complete with tests that pause for a tool approval, restart the conversation process, and resume cleanly.
  • Protects routes automatically: apps with Phoenix Accounts require sign-in; fresh apps get local routes with a production guard (pass --auth or --no-auth to override).

In an existing Phoenix app, run mix ecto.migrate after installing. Against a local checkout, use exagent@path:/absolute/path/to/exagent. Start mix phx.server, visit /chat, and pass --model when you are ready to switch off "test". Keep the igniter_new archive around to run additional generators (mix exagent.gen.agent, mix exagent.gen.approvals). See Resume recovered conversations for configuring Recovery across namespaces and timers.

Generate an approvals inbox

On top of an authenticated generated Phoenix chat, you can scaffold a full reviewer inbox at /approvals in one command:

mix exagent.gen.approvals --yes

Configure which requester namespaces each reviewer is allowed to inspect and approve:

config :my_app, :exagent_review_namespaces, %{"user/42" => ["user/17"]}

For background workers created with mix exagent.gen.agent, grant access with {MyApp.Agents.Billing.Refunds.Worker, "user/17"} (submitting jobs with the requester's namespace as tenant), or add the named Oban instance as a third tuple element: {MyApp.Agents.Billing.Refunds.Worker, "user/17", MyApp.JobsOban}.

How authorization works end to end:

  • MyApp.Agents.Approvals.grants/1 returns the requester namespaces visible to the signed-in reviewer.
  • Loading /approvals or opening a 24-hour signed review link checks authorized_source/2, and submitting an approval re-checks authorize/3 against the exact stored request revision.
  • Each review card shows the decision revision, the permission rule that paused the tool, any candidate child delegation path, and held spend-budget cents. Hook Slack, email or push alerts into the generated notify_reviewers/2 callback.

Require an independent reviewer

To enforce separation of duties — preventing users from approving their own requests and restricting approval to @audit.example reviewers — replace grants/1 in MyApp.Agents.Approvals:

defp grants(%{user: %{email: email}} = scope) when is_binary(email) do
  with reviewer when is_binary(reviewer) <- principal(scope),
       true <- String.ends_with?(email, "@audit.example") do
    grants = Application.get_env(:my_app, :exagent_review_namespaces, %{})

    Enum.reject(grants[reviewer] || [], fn
      ^reviewer -> true
      {_worker, ^reviewer} -> true
      {_worker, ^reviewer, _oban} -> true
      _ -> false
    end)
  else
    _ -> []
  end
end

defp grants(_scope), do: []

This strips the reviewer's own requester namespace from both chat and worker grants across the inbox and signed links while keeping authorize/3 active at decision time.

Next steps

Try a real browser pause-and-restart demo from a source checkout with bash examples/approval_demo/run.sh, or continue into the guides:

API: ExAgent.new/1, ExAgent.run/3, ExAgent.RunError.

Try local release candidates together

Install ExAgent 3.0 from Hex and try the companion dashboard, Ash and Kino packages locally while their separate releases are pending. From a test app, set CANDIDATES to the directory containing the three 0.1.0 Hex TARs and extract each package into its own directory:

mkdir -p vendor/exagent_dashboard vendor/exagent_ash vendor/kino_exagent
tar -xOf "$CANDIDATES/exagent_dashboard-0.1.0.tar" contents.tar.gz | tar -xzf - -C vendor/exagent_dashboard
tar -xOf "$CANDIDATES/exagent_ash-0.1.0.tar" contents.tar.gz | tar -xzf - -C vendor/exagent_ash
tar -xOf "$CANDIDATES/kino_exagent-0.1.0.tar" contents.tar.gz | tar -xzf - -C vendor/kino_exagent

Add the core and whichever companion packages you want to deps/0:

[
  {:exagent, "~> 3.0.0"},
  {:exagent_dashboard, path: "vendor/exagent_dashboard"},
  {:exagent_ash, path: "vendor/exagent_ash"},
  {:kino_exagent, path: "vendor/kino_exagent"}
]

Dashboard requires phoenix_live_dashboard ~> 0.8.7 or ~> 0.9. Run mix deps.get and verify versions with mix deps. In an Ash app, run mix igniter.install exagent_ash@path:vendor/exagent_ash --yes. In Livebook, pass the core and Kino entries to Mix.install/2 using the absolute path to the unpacked Kino directory.

To use a companion directory from a source checkout, set EXAGENT_DASHBOARD_HEX=1, EXAGENT_ASH_HEX=1 or EXAGENT_KINO_HEX=1 so the companion resolves the core from Hex.