API Reference ExAgent v#3.0.0
View SourceModules
A 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.
A DynamicSupervisor that owns ExAgent.Server processes.
The single extension point of an agent: a package of tools, settings and instructions plus optional hooks around each model request and tool call.
ExUnit assertions for deterministic agent tests.
Trusted, versioned definitions for resuming and recovering persisted runs.
Pure view state for one authorized ExAgent.Server conversation.
Pure encoder for one Server attempt in AG-UI 1.0.
Decode an AG-UI 1.0 run request into a prompt or C7 commands.
Pure encoder for the Vercel AI SDK 7 UI Message Stream Protocol v1.
Present and answer a bounded flat MCP form on an authorized deferred call.
Read and reconcile a chat view from a concrete, already authorized Server PID.
Optional Plug for an authorized Server chat. Mount at a conversation
endpoint with the host's authentication and CSRF policy. The required
:authorize function receives the connection on every request and
returns {:ok, owner_pid} for the conversation or
{:error, :unauthorized | :forbidden | :not_found | :unavailable}.
A state transition whose checkpoint was not confirmed by the configured Store.
A bounded choice among host-defined labels. Use a stock Decisions model, a host-owned Nx serving, or a custom adapter.
A classification failure with a bounded reason and any qualified usage.
Classify with a host-owned Nx serving. A registered name uses the serving's
batching and distribution. An inline serving runs in the classifier's
deadline-bound task. The host includes the optional :nx dependency
and owns the serving's lifecycle.
A classifier over stock ReqLLM.evaluate/4. It sends one choice question
and projects the decoded answer and the public usage fields. Use
ReqLLM.evaluation_models/0 to discover available models.
One declared classification label, optional confidence in 0..1, and
qualified usage. Missing confidence is nil.
Behaviour for reducing the conversation context sent to a model.
Replaces older tool return content with short markers in the model request.
Run history and checkpoints retain the original returns. A marker retains
the reference issued by ExAgent.Tool.OutputLimit, when present.
A bounded, host-supervised store that lets ExAgent.Compaction.Summary reuse
its last summary instead of summarizing on every request.
A compactor that summarizes older messages and keeps a recent window verbatim.
Administrative queries and host-authorized decisions for atomic records.
A pending tool decision read from a trusted scoped Store by
ExAgent.Continuation.pending/2.
An open deferred tool call read from a trusted scoped Store by
ExAgent.Continuation.pending/2.
Supervised recovery for trusted Store namespaces.
Versioned decisions for supervised recovery of an uncertain continuation.
Supervise temporary, lazily restored conversation Servers.
Keys are {namespace, agent_id} using the same identity rules as Server.
The :server factory receives the key as its first argument.
The registry behind ExAgent.Conversations: where a conversation's owner is
named and found.
Orchestration patterns on top of ExAgent.Session and the core loop.
Trusted-host definition of a bounded agent sequence.
A bounded, trusted host router or fan-out/fan-in.
Confirmed workflow result. Per-agent messages and errors belong to the
workflow's steps. A step's output_name is its selected output tool, as in
ExAgent.Result.
Helpers for turning token usage into an estimated cost, used together with
the max_budget_cents field of ExAgent.UsageLimits.
Buffered embeddings and document reranking through stock ReqLLM.
One vector per input, in input order, and the request's qualified usage. The numeric format uses lists of numbers. A provider returning Base64 supplies its encoded strings.
A bounded failure from an embedding or rerank operation.
:result_unconfirmed means the request may have reached the provider.
:quota_admission_unconfirmed means no provider operation was dispatched.
:status holds the HTTP status when available. Usage records any evidence
retained even when the operation fails or the result exceeds its bound.
Reranked results in descending relevance and the request's qualified usage. Each index is a zero-based position in the supplied documents.
Measure an agent on a set of cases: run each case, score the result with evaluators and summarize pass rate, latency, usage and cost.
Export a settled C7 agent turn as a redacted Eval case and an offline cassette.
One evaluation case: a name, the input and what to expect.
A named scoring function; build one with ExAgent.Eval.evaluator/3.
Sample already confirmed terminals with an existing ExAgent.Eval evaluator.
Resolve online evaluators for a host's ExAgent.Jobs.Durable worker.
The results of ExAgent.Eval.run/3 and their summary.
One run of one case. scores holds %{name, score, passed, reason} per
evaluator (score and passed are nil when it skipped). A grading
error adds the optional key error: true and records zero and a failed
check. Use Map.get(score, :error) == true to identify these scores.
The attempt's passed is true when at least one evaluator issued a
grade, every grade passed and neither the target nor any grader failed.
Abstentions and grading errors supply no grade.
A missing or ambiguous grading recording adds :diagnostic with type
"fixture_miss" or "fixture_ambiguous" to the failing score.
A failed run keeps
the usage its partial result reports; usage fields are nil when there is
none (a timeout, a raise or a target without a result).
token_coverage qualifies input and output separately as :complete,
:partial or :unknown. When a successful run reports one direction as
available and the other as partial or unavailable, the available count
keeps its complete coverage. An overall partial status still qualifies
both counts when the target provides no directional accounting.
cost_cents is the run's reported total. known_cost_cents retains that
total or the known subtotal when only part of the run could be priced.
run_status retains the target's reported :succeeded, :paused,
:failed, :cancelled or :running status. Runs, Composition and Flow
report success as :succeeded. Absent or unrecognized statuses give nil.
An evaluator can pass a run whose status is :paused.
A bounded conversation attempt in ExAgent.Eval.
A model that plays the user in an ExAgent.Eval.Scenario.
Callbacks for a named suite discovered by mix exagent.eval.
Versioned, serializable event envelope — ExAgent's UI/runtime contract.
A per-case model cassette, recorded and replayed at the ExAgent.Model
dispatch, never on the wire.
A blocking, decision-only capability. Put guards directly in the agent's
:capabilities list. Within each stage the first tripwire or error wins.
A destination a model may ask to take over the current user turn.
Background jobs: tools and sub-agents that keep working while the agent goes on.
PostgreSQL-backed background agents delivered by a host Oban worker.
Durable jobs that open a turn in the conversation that scheduled them.
A job snapshot returned by either Jobs backend. Both report id, name,
status, bounded result text and an optional error diagnostic.
:backend identifies where the snapshot came from.
A second model that reviews the agent's work: final answers before they are accepted, and tool calls before they run.
Review and certify a persisted :ask decision.
A client for Model Context Protocol servers
over stdio or opt-in Streamable HTTP, exposing tools as ExAgent.Tools.
Host operations for the negotiated MCP Tasks extension.
Pure OAuth helpers for the MCP client host.
Pure JSON-RPC 2.0 encoding and decoding for the Model Context Protocol.
Use ExAgent.MCP.Client to discover and call tools.
A host-owned MCP tools server for the Streamable HTTP Plug.
Streamable HTTP endpoint for a supervised ExAgent.MCP.Server. Mount at a
dedicated path before a body parser. The host supplies the HTTP listener.
Verified declarations for a pinned MCP client.
Buffered media operations backed by stock ReqLLM. Each result carries qualified
usage. Audio and OCR inputs are tagged bytes with a MIME type. Text input is
UTF-8. Host-provided media options and credentials use :req_llm.
A media failure and the qualified usage available for the operation.
Generated images and qualified usage for one provider call.
Markdown and zero-based pages returned by stock OCR, with qualified usage.
Generated audio bytes and qualified usage.
Transcript, detected language, optional timing and qualified usage.
Long-term memory that an agent curates across runs and sessions.
An in-memory ExAgent.Memory backend, per node.
A durable ExAgent.Memory backend on PostgreSQL, through the host's
Ecto.Repo (add ecto_sql and postgrex to your app, as for
ExAgent.Store.Postgres).
Message and part types exchanged between the agent and a model.
A source cited by a model response.
A half-open range. Answer ranges use bytes. Source ranges use the provider's coordinates and unit. Page numbers start at one.
Request & response part structs.
Host notification of a terminal background job. The tool name is the
registered name (the definition ID for durable jobs). Read the result
with the query tools bound to the job's store or durable namespace.
The candidate :follow_up field is the scheduled topic
(String.t() | nil). Other job notices leave it nil.
A retry prompt: validation errors (list of maps) or a plain message, sent back to the model so it can correct itself.
A system / instruction prompt part.
Assistant text with an optional provider phase. Narration has
phase :commentary. Answer text has phase :final_answer or nil.
A reasoning / chain-of-thought part (provider-dependent).
The model asking the agent to run a tool.
The return value of a tool call, fed back to the model.
A user prompt part: a string or a non-empty list of content parts.
A message sent to the model.
A message returned by the model.
Qualified metrics for a response or aggregate. accounting is a versioned,
string-keyed JSON map, separate from additive token details. Reported means
reported to the host by the Model contract, not audited provider presence.
Cost is always an estimate in cents, never an invoice.
Versioned PostgreSQL schema for the bundled ExAgent adapters.
Behaviour that every provider model implements.
The capabilities a model declares for request admission and host discovery.
The model request that capability hooks see and transform.
The per-request contract handed to a model. It bundles the tools the agent has prepared (function tools + output tools), the negotiated output mode, and the structured-output schema (if any).
A tool or output validator can ask the model to correct its input with
raise ExAgent.ModelRetry, message: "Use the current code". A string
argument is also accepted. Request a retry only when repeating the
operation is safe. Raise it; returning the struct, alone or in
{:error, _}, is an invalid result. A tool can also return
{:retry, message}.
Per-request model settings. Non-nil fields override agent defaults.
Custom models can read :extra, which merges by top-level key with request
values taking precedence. ExAgent.Models.ReqLLM rejects nonempty :extra
and documents the provider options supported by each profile.
Retries transient provider failures and falls back to other models.
Model adapter over ReqLLM's public one-interaction APIs (generate_text/3,
stream_text/3 and StreamResponse.process_stream/2), used as published.
A deterministic, in-process model for development and tests.
An application-owned, bounded native OpenTelemetry span processor.
Optional native OpenTelemetry instrumentation, using the application's tracer.
Application-owned ReqLLM tracing with one generation span per provider request.
Optional application-supervised cleanup of the integrated ReqLLM bridge.
Optional histogram adapter for the published OTel experimental API 0.6.
Describes a structured output in an agent's output contract.
Structured output via object JSON Schemas or Ecto schemas and changesets.
Per-tool admission control with :allow, :ask and :deny. Rules match tool
names. Candidate argument rules also match globs or structured comparators
on validated arguments.
A bounded, run-local checklist maintained through the write_todos tool.
Each accepted call replaces the list. The latest list is available in
ExAgent.Result.plan and as user data at the end of the next model request.
Behaviour for broadcasting ExAgent.Events.
In-process PubSub backed by a duplicate-key Registry
(ExAgent.PubSub.Registry, started by the application supervisor).
No-op PubSub (default). Broadcasts are discarded; subscribe/2 is
unsupported. Use when you don't need to observe events (e.g. pure one-shot
ExAgent.run/3).
Delegates to Phoenix.PubSub when available, with no hard dependency.
Supervised provider quota admission shared by agent definitions.
Shared admission and settlement for physical model attempts.
Shared provider admission on the host's PostgreSQL Ecto Repo.
Structured error returned by providers for transport/API failures.
Terminal result of an agent run. On success, output_mode records how the
result was finalized. The modes are :text, :tool, :native and
:prompted. A tool output identifies its selected branch in output_name.
With ExAgent.Plan, plan contains the current run's checklist. The live
model can contain credentials. A handoff sets handoff_target to the last
destination ID and keeps the originating model in model for the next turn.
Subject erasure and inventory in an authorized Store namespace.
The context object threaded through dynamic instructions, tool calls and output validators during a single run.
An operational run failure with the last confirmed execution state.
Raised by ExAgent.run!/3 when the run paused for a persisted approval.
Read-only inspection for trusted operators. Authorize callers in the host application before exposing these queries. Namespace filters select rows.
Opt-in tools for isolated execution in a host-provided sandbox.
Host implementation of an isolated execution sandbox.
Reference Sandbox backend for a trusted local Linux Docker Engine.
In-memory Sandbox backend for deterministic tests. It calls a trusted host function with the operation, code and policy. It never evaluates code.
Convert Elixir type expressions (as written in :: annotations / typespecs)
into JSON Schema fragments — the foundation for deftool and structured
output.
Supervised owner of conversational history, model state and accumulated usage.
Version 4 checkpoint of conversational data, with bounded readers for v1/v2/v3.
Single-writer coordination of application state and a participant roster.
A member of an ExAgent.Session: either an :agent (typically backed by an
ExAgent.Server) or a :human (a real person driving via LiveView/a channel).
A handle placed in RunContext.deps so tools running inside an agent run can
read the session's shared state and propose changes — without ever holding
a mutable reference to it.
JSON checkpoint of coordination data. Version 3 adds bounded continuation references; unbound sessions still write v2, and valid v1/v2 data remains readable.
Optional codec for application state at the Session checkpoint boundary.
Decides the order in which session participants take turns.
Cycles participants in an explicitly given order, forever. Use it when participants act in a fixed, possibly uneven sequence — D&D initiative order, priority-based triage, etc.
Cycles participants in insertion order, forever (each full pass is a "round"). The simplest fair policy — good for chat, brainstorming, or any turn-taking where everyone gets equal time.
A coordinator-driven turn order: a supervisor participant alternates with each worker in turn, forever.
A skill: instructions for one kind of task, loaded by the model when needed.
Skills that the model loads on demand (progressive disclosure).
Capability that contributes the skills' tools and offers a skill's own tools only after the skill is loaded.
Capability that restores loaded skills removed from the request projection.
A handle for live user corrections to one volatile run.
Behaviour for persisting agent/session snapshots and optional atomic records.
ExUnit snapshot contract tests for an ExAgent.Store adapter.
In-process, ETS-backed ExAgent.Store implementation (dev/test default).
A durable ExAgent.Store backed by PostgreSQL, for resume across crashes and
multiple nodes.
Supervised cleanup for a PostgreSQL Store.
Telemetry event helpers.
Per-run tool substitutes for integration tests using an ExAgent.Fixture.
A tool the model may call.
A tool that lets the agent consult a stronger (or different) model mid-task.
Capability that lets the model chain tool calls in one turn.
Model-visible image output from a tool declared with result_mode: :multimodal.
Tools for scheduling a new turn in the current durable Server conversation.
Capability that shortens large successful and :tool_error results before the model sees them.
Capability that tells the model when it keeps repeating an identical tool call.
Storage for the UTF-8 representation of a large tool return.
A host-supervised, private ETS result store. Limits apply across all runs using this instance. Oldest writes are evicted first. Reads do not extend the TTL. An entry larger than the byte budget is rejected without eviction.
PostgreSQL storage for offloaded tool results, using the host's Ecto Repo.
Capability that hides a large tool catalogue behind a search_tools tool.
Define tools as plain Elixir functions, with their JSON Schema derived from
:: type annotations and @doc strings — no hand-written schemas.
Compose ordered tool inventories at agent construction time.
Execution-tree safety net: each run's limits also constrain its framework descendants. The runtime serializes admission across the tree and uses these functions to check limits. Token and cost thresholds are checked again just before dispatch. A request that stops at this check still counts as admitted. The thresholds are retrospective, so already dispatched requests can exceed them.
Shared monetary admission for attempts billed to a host account.
Transactional admission and settlement for a shared monetary account.
A supervised local spend account with a read-only ETS balance.
A shared spend account on the host's PostgreSQL Ecto Repo.
Use the next admissible request for a final answer when a run approaches a configured limit.
A policy decision shared by permissions, judges, classifier-backed guards and evaluators.
Mount bounded text storage as ordinary, permission-controlled agent tools.
By default only /scratch is mounted, with run-local ETS storage. Supply
:mounts to choose the exposed top-level paths. Each entry is
{"/name", backend, :read_only | :read_write}. A custom backend is
{module, handle} implementing ExAgent.Workspace.Backend.
Backend of an ExAgent.Workspace mount. Paths are validated relative paths
with no leading slash. The mount root is the empty string. Text is UTF-8.
A text workspace rooted in an existing POSIX directory. Configure it with
ExAgent.Workspace.directory/1. The backend pins the root's device and inode,
checks path components with File.lstat/2, and reads singly linked regular
files. The host controls the directory tree and its parent directories.
Mount an existing ExAgent.Memory scope. Both interfaces see the same files.
Configure it with ExAgent.Workspace.memory/2.
Read-only mount for ExAgent.Tool.ResultStore. Open a known reference by
its name. The ResultStore contract grants no enumeration authority.
Per-node scratch files for runs and streams. The execution scope owns its ETS table and deletes it when the node closes. A durable attempt reconstructs the files from confirmed tool data when the node resumes.
Mix Tasks
Record the active durable agent definition in priv/exagent/catalog.lock.
Inspect the local model catalogue, transport, optional dependencies and host runtime.
Discovers evals/*/_eval.exs. Replay is the default. Use --record or --record-missing explicitly to write cassettes. See the testing guide.
Generate a host-owned agent, tools, tests and a replayable Eval.
Generate a reviewer inbox with an authenticated Phoenix chat installation.
Generate the host-owned Phoenix chat after running mix exagent.install.
The LiveView reads conversation events in bounded batches from its Server.
Install ExAgent conversation infrastructure in a Phoenix application.
Run mix exagent.eval.capture --run ID --suite NAME to add a redacted case
and cassette to an existing suite. The suite's ExAgent.Eval.Suite.capture/1
callback authorizes and reads the source and supplies a redactor. Use
--fixtures DIR to select the same fixture directory as replay.
Capture a live MCP catalogue in priv/exagent/mcp/<endpoint>.lock.json.
Run seven small checks with stock ReqLLM and the model's automatic ExAgent profile.
Generate the pinned ExAgent.Migration for this ExAgent release.