ExAgent (ExAgent v3.0.0)
View SourceA production agent framework for Elixir. Define tools as ordinary functions, get Ecto-validated structs back, stream live updates into Phoenix, and pause sensitive actions for human approval across restarts. Start with one function call — every OTP, persistence and coordination layer is opt-in.
What ExAgent simplifies
- Zero hand-written JSON Schemas:
deftoolderives tool schemas from Elixir type annotations and validates arguments before your function ever runs. - Typed, self-correcting outputs: Pass an
Ecto.Schema embedded_schemamodule (with optionalchangeset/2) asoutput:; JSON Schema and changeset errors feed back to the model automatically (up tooutput_retries) until a valid struct is returned. - One loop for buffered, streamed & local models: Powered by stock ReqLLM across OpenAI, Anthropic, Google Gemini, OpenRouter and local Ollama / vLLM / llama.cpp endpoints (including thinking models and malformed tool-envelope auto-retry). Supported provider profiles
- LiveView-ready supervised conversations:
ExAgent.ServerandExAgent.Conversationshandle history, bounded queues, turn steering, cancellation, demand-paced events and SSE / AI SDK / AG-UI adapters. - Crash-safe human approvals:
ExAgent.Continuationcheckpoints runs in PostgreSQL or ETS and never replays an unconfirmed external side effect. - Multi-agent coordination with shared budgets: Scoped delegation, handoffs,
shared-state
Sessions and durableComposition/Flowworkflows inherit ancestor permissions, deadlines and spend limits. - Skills, MCP, observability & offline CI: On-demand Agent Skills, MCP
client & server,
:telemetry+ optional OpenTelemetry (Langfuse / Opik), recorded cassettes andmix exagent.evalquality gates.
Installation
def deps do
[{:exagent, "~> 3.0.0"}]
endVerified on Elixir 1.18.4 / OTP 28 and Elixir 1.20.0 / OTP 29. A one-shot run
needs no database. Credentials and .env loading
Quick start
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}"test" runs 100% offline using the same execution loop as real providers. With
ANTHROPIC_API_KEY set, swap to model: "anthropic:claude-sonnet-5-5" (see
Models and limits for OpenAI, Gemini,
OpenRouter, Ollama, vLLM and per-tenant credentials). In Phoenix,
mix igniter.install exagent --chat --yes scaffolds a
complete LiveView chat
with PostgreSQL checkpoints and durable approvals.
Tools and typed output
For the MyApp.Forecast Ecto output schema below, add
{:ecto, "~> 3.14 and >= 3.14.3"} to your application's dependencies.
defmodule MyApp.Weather do
use ExAgent.Tools
@doc "Get the weather for a city."
deftool get_weather(_ctx, city :: String.t(), days :: integer()) do
{:ok, "#{city}: sunny for #{days} day(s)"}
end
end
defmodule MyApp.Forecast do
use Ecto.Schema
@primary_key false
embedded_schema do
field :city, :string
field :temp_c, :float
end
def changeset(forecast, attrs) do
forecast
|> Ecto.Changeset.cast(attrs, [:city, :temp_c])
|> Ecto.Changeset.validate_required([:city, :temp_c])
|> Ecto.Changeset.validate_number(:temp_c, greater_than: -100, less_than: 100)
end
end
alias ExAgent.Message.Part.ToolCall
# Offline; with a key use model = "anthropic:claude-sonnet-5-5"
model = %ExAgent.Models.Test{
script: [
{:tool_calls, [%ToolCall{tool_name: "get_weather", args: %{"city" => "Madrid", "days" => 1}}]},
{:tool_calls,
[%ToolCall{tool_name: "final_result", args: %{"city" => "Madrid", "temp_c" => 21.5}}]}
]
}
agent = ExAgent.new(model: model, tools: MyApp.Weather.tools(), output: MyApp.Forecast)
{:ok, result} = ExAgent.run(agent, "What is the weather in Madrid?")
result.output
# => %MyApp.Forecast{city: "Madrid", temp_c: 21.5}ExAgent derives both JSON Schemas automatically, validates get_weather's
arguments before invoking it, checks MyApp.Forecast.changeset/2 on the model's
answer (sending validation errors back for correction), and returns a real
%MyApp.Forecast{} struct.
Tools and structured output covers
permissions, guardrails, sandboxes and approval gates.
Layers at a glance
Start with the top row and add layers only as your application needs them — see Mental model and architecture for a full pattern decision table.
| Layer | Entry points | What it simplifies | Guide |
|---|---|---|---|
| Run | ExAgent.run/3, ExAgent.run_stream/3 | Stateless tool loops & typed Ecto outputs | Tools and output |
| Conversation | ExAgent.Server, ExAgent.Conversations, ExAgent.Chat | Supervised history, streaming & LiveView events | Runtime and events |
| Durability & approvals | store:, ExAgent.Continuation, ExAgent.resume/3 | Crash-safe checkpoints & human approval pauses | Durability and approvals |
| Coordination | ExAgent.Coordination, ExAgent.Session, ExAgent.Handoff | Delegation, shared state & durable workflows | Coordination |
Sync coding-agent guidance (LLMs)
ExAgent ships a dedicated machine-optimized documentation track for coding
agents (usage-rules.md, 11 package skills, llms.txt, single-fetch
llms-full.txt, and contract sheets). To sync ExAgent's rules and skills into
your app automatically, add {:usage_rules, "~> 1.3.1", only: :dev, runtime: false}
to deps/0 and configure project/0:
usage_rules: [
file: "AGENTS.md",
usage_rules: [:exagent],
skills: [location: ".agents/skills", package_skills: [:exagent]]
]Run mix deps.get && mix usage_rules.sync --yes. Codex and Cursor read
AGENTS.md and .agents/skills; for Claude Code use file: "CLAUDE.md" and
location: ".claude/skills". Re-sync after upgrading ExAgent. The installed
dependency also includes usage-rules.md and
usage-rules/skills/<name>/SKILL.md for direct reading.
UsageRules package skills
Stability — Stable.
Summary
Functions
Build an agent from options. Use :output for the output spec.
Options must be a keyword list with known, unique keys. Pass :permissions
in the options for each run. The :context_overflow, :handoffs,
:observability and :spend_budget options use candidate integrations.
Resume a persisted approval from an explicitly supplied trusted agent and configuration.
The catalogue variant takes an ExAgent.Catalog and a runtime :continuation
configuration with the Store, ID and lease settings. The exact saved
definition, policy and model references select the agent and model codec.
An absent version gives {:definition_unavailable, ref}.
A mismatch gives {:definition_incompatible, field}.
Uses the options of run/3 and requires :continuation. The saved limits,
the agent's limits and the candidate :usage_limits override all constrain the
resumed run. Invalid options raise ArgumentError before accessing the
record, including at stream construction for resume_stream/3.
Open a new lazy stream for a persisted continuation. The earlier paused
stream stays terminal. Accepts the options of resume/3, including
the catalogue variant and the candidate :usage_limits option. Options are checked
at construction as in run_stream/3.
Use the same v1 reference as resume/3. Reference and readiness failures
are emitted as {:error, %ExAgent.RunError{}}.
Run the agent against prompt, returning {:ok, result} or {:error, _}.
Run synchronously and return the output value directly.
Run an auxiliary/delegated agent under an existing run's execution scope.
Run the agent, returning a lazy stream of typed {type, data} elements.
Types
@type instruction() :: (ExAgent.RunContext.t() -> String.t() | [String.t()] | nil)
@type output_type() :: ExAgent.Output.schema() | ExAgent.Output.spec() | [ExAgent.Output.schema() | ExAgent.Output.spec() | :text] | :text
@type output_validator() :: (term(), ExAgent.RunContext.t() -> output_validation()) | {:pure, (term() -> output_validation())}
@type prompt() :: String.t() | [ExAgent.Message.Part.User.content_part()]
@type result() :: ExAgent.Result.t()
@type t() :: %ExAgent{ capabilities: [module() | struct()], context_overflow: {module(), keyword()} | nil, handoffs: [ExAgent.Handoff.t()], instructions: [ExAgent.Message.Part.System.t() | instruction()], max_concurrent_tools: pos_integer() | nil, max_history_bytes: pos_integer(), max_payload_bytes: pos_integer(), max_steps: pos_integer(), model: ExAgent.Model.model(), model_settings: ExAgent.ModelSettings.t(), name: String.t() | nil, observability: ExAgent.Observability.OpenTelemetry.t() | nil, on_max_steps: :error | :final, output: output_type(), output_mode: :tool | :native | :prompted, output_retries: non_neg_integer(), output_validators: [output_validator()], rate_limiter: ExAgent.RateLimiter.server() | nil, spend_budget: ExAgent.UsageLimits.Budget.t() | nil, tool_timeout: pos_integer(), tools: [ExAgent.Tool.t()], usage_limits: ExAgent.UsageLimits.t() | nil }
Functions
Build an agent from options. Use :output for the output spec.
Options must be a keyword list with known, unique keys. Pass :permissions
in the options for each run. The :context_overflow, :handoffs,
:observability and :spend_budget options use candidate integrations.
:output is :text, an object JSON Schema map, an Ecto schema module, an ExAgent.Output spec
(ExAgent.Output.tool/2 or the output function ExAgent.Output.function/4)
or a list of them with at most one :text.
Use output: :text or omit :output for plain text with the default output mode.
JSON Schema output returns a string-keyed map after local JSV validation.
Ecto modules require the optional Ecto dependency when compiling ExAgent.
Structured output defaults to output_mode: :tool. Explicit :native sends a
separate JSON Schema to a model declaring native support. Explicit :prompted
includes the schema in a request instruction. The model answers in text, and
that text (or one Markdown fence around it) must contain just the JSON object.
Both modes apply JSV locally and Ecto modules also apply their changeset. The instruction
enters only the request, never the history. :native and :prompted take a
single object JSON Schema or Ecto schema module.
Valid tool schemas are prepared once on the reusable definition. Invalid
schemas still fail as operational RunErrors when running the agent; each
run also checks that a prepared validator matches the tool's current schema.
:instructions is a string, a function (ExAgent.RunContext.t() -> String.t() | [String.t()] | nil) or a list mixing both. Strings are the System parts of
the conversation's first request and stay in its history. Functions are
evaluated in list order once per run attempt, before the first model request,
with the run's context (deps, run_id...). Like a capability's
instructions/2, their text enters only the request, after the history's
leading System parts and before capability instructions, never the history.
A function that raises or returns another value fails the run with
{:capability_failed, ExAgent, :instructions, reason}. Durable composition
steps refuse them, as they refuse capability instructions.
:tool_timeout sets the default timeout for tool calls in milliseconds,
counted from each call's dispatch; the admission before it (hooks,
validation, permissions, :approve) has a separate budget of the same
length (see ExAgent.Tool). It must be a positive integer and defaults to
30_000.
:max_concurrent_tools limits the number of active calls in each parallel
function-tool group. Use a positive integer. Without a limit, groups use
System.schedulers_online(). A run can override the agent's limit.
:max_steps must be a positive integer (default 50). :output_retries
must be a non-negative integer (default 1). Use zero to disable output retries.
:rate_limiter addresses a host-supervised local ExAgent.RateLimiter
by registered atom, via name or PID. Delegated agents inherit it. A limiter
configured with a shared adapter coordinates with other replicas.
:spend_budget takes an ExAgent.UsageLimits.Budget for a trusted tenant or
account. It reserves shared funds before dispatching model attempts.
Descendants inherit the budget from their execution scope.
:handoffs is a list of ExAgent.Handoff destinations for volatile turns.
A generated transfer tool lets the current model ask a specialist to
finish the turn under the same execution scope.
:context_overflow accepts {compactor, options} for one recovery projection
per live run after a provider rejects its input size. The default is nil.
For example, use {ExAgent.Compaction.ClearToolResults, [threshold_tokens: 0, keep_recent: 0]}. See ExAgent.Compaction for the projection contract.
Retention defaults are max_payload_bytes: 1_048_576 and
max_history_bytes: 8_388_608, configurable from 1 byte through 64 MiB. They measure
uncompressed Erlang external term size after decode. Before a tool starts,
its payload limit must accommodate the reserved return, including 4 KiB for
usage and space for the call identity and an omission marker. A tool may
already have performed its effect when its returned payload exceeds a limit:
its outcome/identity are preserved with an explicit payload_omitted marker
and a terminal RunError. Such history cannot be executed again automatically.
:skills takes a list of ExAgent.Skills that the model loads on demand. It
adds a load_skill tool (plus read_skill_file and the skills' gated tools),
an ExAgent.Skills.Gate before :capabilities when a skill has tools, and
ExAgent.Skills.Restore after them; see ExAgent.Skills. Invalid skills or
clashing tool names raise ArgumentError.
:output_validators is a list of fn output, ctx -> ... end checks that run,
in order, on a final output that already passed schema validation, before
the run accepts it. Return :ok, {:ok, output} to replace the output for
later validators and the result, {:retry, message} (or raise ExAgent.ModelRetry) to send message back to the model and continue the
run, or {:error, reason} to fail it with {:output_validation_failed, reason}. Any other return, including a returned %ExAgent.ModelRetry{},
fails it with {:output_validation_failed, {:invalid_validator_result, _}}.
Retries share the :output_retries budget. A validator may call
another model through ExAgent.run_child/4 with its ctx, as
ExAgent.Judge.output_validator/1 does, so that usage counts toward the
run's limits. A resumed run does not check an output it already accepted.
The run's deadline, usage limits and cancellation are checked again after the
validators. A retry on the last step allowed by :max_steps ends the run with
{:max_steps_exceeded, max_steps}. In durable compositions validators require typed
output (the output tool); with text or native output the run fails with
{:unsupported, :output_validators_without_output_tool}.
A validator declared as {:pure, fn output -> ... end} receives only the
validated output and must be deterministic and free of side effects. When
every validator on a direct durable Flow branch is pure, a returned
{:error, reason} certifies a veto of the confirmed output-tool response.
Version the validator chain with the branch's :output_ref.
:on_max_steps chooses what the last allowed step does. :error (default)
allows ordinary tool calls on the last step. :final asks for an answer in
step max_steps: function tools stay declared but cannot be called, and a
request-only instruction says the step limit was reached. Function calls in
that step are not executed and the run fails with {:max_steps_exceeded, max_steps}.
@spec resume( t() | ExAgent.Catalog.t(), ExAgent.Continuation.continuation_reference(), keyword() ) :: {:ok, result()} | {:error, ExAgent.RunError.t()}
Resume a persisted approval from an explicitly supplied trusted agent and configuration.
The catalogue variant takes an ExAgent.Catalog and a runtime :continuation
configuration with the Store, ID and lease settings. The exact saved
definition, policy and model references select the agent and model codec.
An absent version gives {:definition_unavailable, ref}.
A mismatch gives {:definition_incompatible, field}.
Uses the options of run/3 and requires :continuation. The saved limits,
the agent's limits and the candidate :usage_limits override all constrain the
resumed run. Invalid options raise ArgumentError before accessing the
record, including at stream construction for resume_stream/3.
Pass the full v1 :continuation from the decision or authorized recovery
for the run. An invalid or stale reference returns a run error with reason
:continuation_conflict. A matching record that cannot resume gives
{:continuation_not_ready, status} as the reason.
@spec resume_stream( t() | ExAgent.Catalog.t(), ExAgent.Continuation.continuation_reference(), keyword() ) :: Enumerable.t()
Open a new lazy stream for a persisted continuation. The earlier paused
stream stays terminal. Accepts the options of resume/3, including
the catalogue variant and the candidate :usage_limits option. Options are checked
at construction as in run_stream/3.
Use the same v1 reference as resume/3. Reference and readiness failures
are emitted as {:error, %ExAgent.RunError{}}.
@spec run(t(), prompt(), keyword()) :: {:ok, result()} | {:error, ExAgent.RunError.t()}
Run the agent against prompt, returning {:ok, result} or {:error, _}.
prompt is a string or a non-empty list of content parts (text, images and
documents; see ExAgent.Message.Part.User). An invalid part fails with
{:invalid_prompt_part, index} and an empty list or other value with
:invalid_prompt, before any model request.
Operational errors contain an ExAgent.RunError: its reason is the cause
and partial preserves history, usage and the last confirmed model. Retrying
the prompt is a new execution and can repeat effects.
Pass options as a keyword list with known, unique keys and valid
values. Invalid keys or values, and an agent definition changed into an
invalid one after new/1, raise ArgumentError before any IO, including at
stream construction. ExAgent.RunError is reserved for operational failures.
Options:
:deps— dependency value threaded intoRunContext.:message_history— priorMessage.t()list to continue from. Malformed history raisesArgumentError. Restore JSON saved withExAgent.Message.to_json/1usingExAgent.Message.from_json/1.:max_payload_bytes,:max_history_bytes— finite overrides of the definition's postdecode retention bounds. Results expose:retentionmeasurements of history and public data, excluding live model/configuration.:model_settings— per-run settings overrides.:fixture— an openExAgent.Fixtureshared with descendants. Configure:tool_stubson the fixture to require test substitutes. Without this option, a run started synchronously from an:approvecallback or a compaction summarizer of a run with a fixture uses that fixture; passfixture: nilto opt out.:stream_text— stream model text through the same agent loop.:on_steering— optional one-argument callback receiving anExAgent.Steeringhandle for this volatile run. Forward it to the process that takes user corrections. Children opt in separately.:tool_call_deltas— opt in to{:tool_call_delta, _}previews of tool arguments inrun_stream/3and Server events. Previews never enter history; the terminal response carries the authoritative calls.:child_events—:none(default) or:all. With:all, children started withrun_child/4hand their stream elements to this run's stream as{:child, lineage, element}and inherit:stream_text,:tool_call_deltasand:child_eventsunless given. The stream terminal belongs to the root.run_child/4returns its outcome locally.:permissions— anExAgent.Permissionspolicy ornilto add no policy.:approve—(tool_call -> :approve | :deny)callback for:askrules. It cannot be combined with:continuation, which persists the request forExAgent.Continuation.decide/4instead.:on_input— candidate one-argument callback for MCP form rounds on a run without:continuation. It receives the tool name, call reference and reviewed forms in%{tool: name, call_ref: ref, forms: forms}. Return{:ok, input_responses}(keyed by peer request ID) to send another round or:denyto settle locally. The tool worker calls it synchronously within the tool deadline. Children opt in separately.:usage_limits— candidate per-call%ExAgent.UsageLimits{}ornil. The run uses the lowest configured threshold for each dimension. Strict accounting applies if either the agent or this option requires it.:estimate_cost— a one-argument function of usage for a homogeneous model tree, or a two-argument function of model and usage for model-aware pricing. Return nonnegative cents for the usage supplied, or{:partial, cents}when only some of it can be priced. The callback can receive partial usage with both token subtotals. In either case of partial coverage, only the subtotal counts toward estimated limits. Returning nil or:unknownleaves the cost unknown. Strict monetary limits require an estimator before model admission.:deadline— optional absolute monotonic milliseconds; inherited descendants may only shorten it. Admission and native IO timeouts honor it, but arbitrary application callbacks are not preempted.:max_concurrent_requests— optional positive cap, shared with descendants; saturated admission fails explicitly without adding a waiting queue.:max_concurrent_tools— optional positive cap per parallel function-tool group. This value overrides the agent's setting. Waiting for a slot uses the run deadline. A continuation retains the override across attempts.:on_progress— optional runtime callback receiving full result-shaped snapshots; these contain a live model and must not be exported as JSON. In-flight batches include:unknownfor unresolved calls and can show the effect receipt before after-tool hooks finish. A tool-output guardrail withholds the result until approval. In runs without a continuation, progress incorporates each observed task completion, including content transformed by its hooks and calls denied before execution. Continuation progress uses the writer's confirmed evidence until the batch is collected. Final history records outcomes in the original call order.:observability— optionalExAgent.Observability.OpenTelemetryconfig; overrides the agent default.falsedisables instrumentation for this run.:trace_context— ephemeral context captured with the OTel adapter; use for application-owned process boundaries, never persisted snapshots.
Run synchronously and return the output value directly.
A failure raises the ExAgent.RunError that run/3 would return, with its
reason and partial progress. A run paused for a persisted approval is not
a failure, but it has no output: run!/3 raises ExAgent.RunPaused, whose
result carries the :continuation reference for resume/3.
@spec run_child(map(), t(), prompt(), keyword()) :: {:ok, result()} | {:error, ExAgent.RunError.t()}
Run an auxiliary/delegated agent under an existing run's execution scope.
Accepts a RunContext or the state passed to a model capability. Options are
those of run/3, checked the same way. The helper inherits dependencies and
fixes ancestry, tracing and observability after caller options; a builder
cannot replace the inherited scope. Child limits/policies add restrictions to
all ancestors. Child progress is not forwarded as parent conversation history.
In a tool, get the inherited cassette with ExAgent.RunContext.fixture/1.
Pass fixture: Fixture.with_label(fixture, label) to append a stable
label to the child's cassette path.
Inside a run with a persisted continuation, a child without a durable
descriptor cannot reserve its requests in the journal: the call returns
{:error, %ExAgent.RunError{reason: :continuation_child_descriptor_required}}
without running. The execution scope decides, so a context whose
:continuation was cleared is refused too. Use
ExAgent.Coordination.delegation_tool/2 with :continuation for durable
delegation.
@spec run_stream(t(), prompt(), keyword()) :: Enumerable.t()
Run the agent, returning a lazy stream of typed {type, data} elements.
The stream runs the same tools/output/hooks/limits loop as run/3 and ends
with exactly one terminal: {:result, result} (also for a durable pause,
with status: :paused) or {:error, %ExAgent.RunError{}}. Before it:
| Element | Data |
|---|---|
:run_started | run_id, root_run_id, parent_run_id, attempt_id |
:run_step_started | step |
:steering_applied | step, correction_id (the caller's receipt) |
:run_handoff | step, from, to, call_ref (destination identity and opaque call reference) |
:text_delta, :commentary_delta, :thinking_delta | step, text (provisional, every request) |
:tool_call_delta | step, index, tool, fragment (only with tool_call_deltas: true) |
:output_partial | step, output (provisional string-keyed map or Ecto struct with completed fields) |
:model_response | step, response (the accepted %ExAgent.Message.Response{}) |
:tool_call_started | step, tool, call_ref, call (the validated, authorized %Part.ToolCall{}), args_source (:model or :reviewer) |
:tool_call_finished | step, tool, call_ref, return (%Part.ToolReturn{}), duration_ms, duration_measured |
:tool_data | step, call_ref, tool, part_id, name, data, transient (from ExAgent.RunContext.emit/4) |
:guardrail_tripped | step, name, stage (the terminal is {:error, %ExAgent.RunError{}}) |
:context_compacted | step, reason: :context_overflow, estimated_tokens_saved |
:approval_requested | continuation, pending (identifiers of approvals and deferred calls) |
:run_step_finished | step, outcome (:continued, :retry, :succeeded, :paused or :failed) |
{:child, lineage, element} | a child's element with its run_id, parent_run_id and root_run_id (only with child_events: :all) |
Every started step finishes once, before the terminal, also on pause and failure; a worker killed abruptly ends with the terminal alone. A call awaiting approval finishes in the attempt that executes it. Deltas are provisional: validate the terminal, not the text. Match the elements you need and keep a catch-all clause; new element types can be added.
Delivery is synchronous backpressure: the run and each of its tool tasks hand over one element and wait until the consumer demands the next, so an element the consumer has not asked for is not produced. A slow consumer slows the run; it does not bound an adapter's own HTTP buffers.
Accepts the options of run/3, including the candidate :usage_limits. Malformed options
raise ArgumentError when constructing the stream.
The stream closes its worker and guardian before delivering the terminal event, including when the consumer suspends on that event.
Each enumeration starts a new run. Halting enumeration or killing its owner
cancels the owned worker; effects already performed are not rolled back.
Resume or halt a suspended Enumerable continuation in the process that
started enumeration. Calling it with either instruction from another process
raises ArgumentError.