Tools and structured output
View SourceTools let an agent call your Elixir code; structured output turns a model's final answer into a validated map or Ecto struct. Together they turn free-form LLM calls into strongly typed building blocks your application can trust.
What ExAgent simplifies:
- No hand-written JSON Schemas:
deftoolandtool_plainderive JSON Schemas directly from Elixir type annotations and@docstrings. - Validation before execution: Bad model arguments are caught and returned to the model for self-correction before your function ever runs.
- Changeset-backed outputs: Pass any
Ecto.Schema embedded_schemamodule (with an optionalchangeset/2) asoutput:; ExAgent generates the JSON Schema, checks JSON shape first, runschangeset/2, retries invalid answers up tooutput_retries, and hands you a real struct. - Defense in depth: Layer argument-aware permissions, guardrails, output limits, tool search and Docker sandboxes onto the same tool list without rewriting a single tool.
Need exhaustive schema rules or edge-case contracts?
For full JSON Schema validation vocabularies, exact error tuples and internal capability hooks, see Tools & models contracts.
Define a tool
Use ExAgent.Tools to declare tools as ordinary Elixir functions. @doc
becomes the tool description the model sees, and type annotations generate its
JSON Schema automatically:
defmodule DocumentationTools do
use ExAgent.Tools
@doc "Convert a distance in kilometres to metres."
tool_plain to_metres(kilometres :: integer()) do
{:ok, kilometres * 1000}
end
end
DocumentationTools.tools()- Use
tool_plainwhen the function only needs the model's arguments. - Use
deftoolwhen the function also needs%ExAgent.RunContext{}as its first parameter (for example, to readctx.depsfor a Repo, tenant ID or current user). - Use
ExAgent.Tool.new/1when you want to construct a tool dynamically or supply an explicit JSON Schema (for instance, with optional object keys).
Type annotations cover scalars, inclusive ranges (1..5), lists
(list(integer()), nonempty_list(String.t())), nullable fields
(String.t() | nil) and nested maps (%{quantity: pos_integer(), sku: String.t()}).
Exercise the whole tool loop
Pass the tool list to ExAgent.new/1. Here is the complete tool round-trip
running offline against ExAgent.Models.Test:
alias ExAgent.Message.Part.ToolCall
model = %ExAgent.Models.Test{
script: [
{:tool_calls, [
%ToolCall{tool_name: "to_metres", tool_call_id: "conversion-1",
args: %{"kilometres" => 3}}
]},
"3 kilometres is 3000 metres."
]
}
agent = ExAgent.new(model: model, tools: DocumentationTools.tools())
{:ok, result} = ExAgent.run(agent, "Convert 3 kilometres.")
%{output: result.output, requests: result.request_count, tools: result.tool_calls}
# => %{output: "3 kilometres is 3000 metres.", requests: 2, tools: 1}Swap model: to "anthropic:claude-sonnet-5-5" or "ollama:llama3.3" and the
exact same loop runs live.
Return an Ecto struct
Add {:ecto, "~> 3.14 and >= 3.14.3"} to your application's dependencies
before compiling ExAgent, then pass any embedded_schema module as output:.
ExAgent derives the JSON Schema from your fields and changeset validations,
returns errors to the model for self-correction, and yields a real struct:
defmodule DocumentationDistance do
use Ecto.Schema
@primary_key false
embedded_schema do
field :metres, :integer
end
def changeset(struct, attrs) do
struct
|> Ecto.Changeset.cast(attrs, [:metres])
|> Ecto.Changeset.validate_required([:metres])
|> Ecto.Changeset.validate_number(:metres, greater_than_or_equal_to: 0)
end
end
model = %ExAgent.Models.Test{
script: [{:tool_calls, [
%ExAgent.Message.Part.ToolCall{tool_name: "final_result",
tool_call_id: "distance-1", args: %{"metres" => 3000}}
]}]
}
agent = ExAgent.new(model: model, output: DocumentationDistance)
{:ok, result} = ExAgent.run(agent, "Convert 3 kilometres.")
result.output.metres
# => 3000Your changeset/2 is the final authority across all three output modes:
| Mode | When to use |
|---|---|
output_mode: :tool (default) | Works across all tool-capable models (cloud and local :chat_tools_v1); supports unions ([SchemaA, SchemaB, :text]) and Output.function/4. |
output_mode: :native | Single schema with provider-side constrained decoding on models declaring native JSON Schema support (OpenAI, Anthropic — not Gemini or local :chat_tools_v1). |
output_mode: :prompted | Single schema on text-only models or lightweight endpoints; injects schema instructions into the request and parses JSON from the reply. |
Declare a tool's effect
Tag read-only and side-effecting tools explicitly with effect::
# Inside a module that uses ExAgent.Tools
deftool order_status(ctx, id :: String.t()), effect: :read do
Map.fetch!(ctx.deps.orders, id)
endSupported effect levels are :read (query-only, safe for authorized recovery
replay if an owner dies mid-flight) and :write (the default — any mutation or
external side effect, never replayed automatically). Tagging read-only tools
lets recovery policies, tool programs and approval workflows treat reads cleanly
while keeping writes strictly protected.
Decide what a failure means
Not every error should crash a run — and not every host failure should be leaked to the model. ExAgent gives your tool five clear return shapes so the loop always does the right thing:
| Return value | Who sees it | What ExAgent does |
|---|---|---|
{:ok, value} (or bare JSON value) | Model | Records :succeeded tool return and continues the loop. |
{:tool_error, message} | Model | Records a recoverable failure text so the model can adjust without spending tool retries. |
{:retry, message} (or raise ExAgent.ModelRetry, message: msg) | Model | Asks the model to fix its arguments before any effect, spending the tool's :max_retries budget. (Never return %ModelRetry{} as a value — raise it or return {:retry, message}.) |
{:error, reason} | Host only | Fails the run with {:tool_execution_failed, ...}; history only tells the model "The tool failed." so secrets and internals stay private. |
{:unknown, reason} | Host only | Marks an unconfirmed side effect so durable continuations wait for explicit reconciliation instead of replaying it. |
Prefer {:tool_error, "Order #99 not found"} for expected domain outcomes the
model should reason about, {:error, reason} for infrastructure outages, and
{:unknown, reason} when an HTTP write timed out after leaving your process.
Match permissions against tool arguments
Pass :permissions per run so the same reusable %ExAgent{} can run
read-only in one context, approval-gated in another, and denied in a third.
Rules can match not just tool names, but structured commands, URLs and paths:
permissions =
ExAgent.Permissions.new!(
rules: [
{"shell", :ask, args: %{"command" => {:command, ["git", "status"]}}},
{"sql", :ask, args: %{"query" => "SELECT *"}},
{"http", :allow,
args: %{
["request", "method"] => "GET",
"url" => {:url, "https://api.example.test/v1"}
}},
{"read_files", :allow, args: %{"paths" => {:path, "/srv/reports"}}}
],
default: :deny
)
ExAgent.Permissions.decide(permissions, "shell", %{"command" => ["git", "status", "--short"]})
# => :ask
ExAgent.Permissions.decide(permissions, "shell", %{"command" => "git status; printf sample"})
# => :deny
ExAgent.Permissions.decide(permissions, "read_files", %{"paths" => ["/srv/reports/today.csv"]})
# => :allow:allowruns the tool immediately.:denyblocks the call before execution and tells the model it was denied.:askpauses for approval (using an in-process:approvecallback or a persisted continuation).
Argument matchers prevent shell injection (; / pipes), path traversal (..),
and cross-host URL tricks before your tool code is ever touched.
Control how tool calls run
Control isolation, timeouts, heap ceilings and concurrency per tool without
writing custom Task.Supervisor boilerplate:
write = ExAgent.Tool.new(
name: "write_file",
parameters_json_schema: %{type: "object"},
call: fn _ctx, args -> MyApp.Files.write(args) end,
concurrency: :exclusive,
timeout: 5_000,
max_heap_bytes: 8_388_608
)
tools = [write | Enum.map(DocumentationTools.tools(), &%{&1 | timeout: 2_000})]concurrency: :parallel(default) lets independent tool calls in one model turn run concurrently (bounded bymax_concurrent_tools:on the agent).concurrency: :exclusiveserializes mutations one at a time in model order.timeout:andmax_heap_bytes:protect your BEAM node from runaway tools.
Confirm a background submission
When a tool triggers external async work (like a video render or webhook job)
and must wait for an external callback later, mark requires_deferral: true
and return {:defer, payload}:
render = ExAgent.Tool.new(
name: "render",
requires_deferral: true,
call: fn _ctx, args ->
{:ok, id} = MyApp.RenderQueue.submit(args)
{:defer, %{"job_id" => id}}
end
)In a persisted continuation, the run pauses cleanly until your app supplies the
external result via ExAgent.Continuation.supply_result/4.
Validate a tool's result
Add result_schema: when a tool integrates with an external API or dynamic
plugin and you want ExAgent to verify its JSON output contract before feeding
it back to the model:
ExAgent.Tool.new(
name: "order_total",
result_schema: %{
"type" => "object",
"properties" => %{"total_cents" => %{"type" => "integer"}},
"required" => ["total_cents"]
},
call: fn _ctx, _args -> {:ok, %{"total_cents" => 1250}} end
)Return an image to the model
Set result_mode: :multimodal when a tool returns a screenshot, chart or image
alongside text:
pixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGP4DwABAQEAsTj2FAAAAABJRU5ErkJggg=="
ExAgent.Tool.new(
name: "sample_image",
description: "Show a sample white pixel.",
parameters_json_schema: %{"type" => "object", "properties" => %{}},
result_mode: :multimodal,
call: fn _ctx, _args ->
{:content, [
%{"type" => "text", "text" => "White calibration pixel"},
%{"type" => "image", "media_type" => "image/png", "data" => pixel}
]}
end
)Check Image results from tools for provider support (Anthropic, OpenAI Responses, Gemini and compatible Chat endpoints).
Compose tool lists
When your app grows beyond a handful of tools, ExAgent.Toolset lets you
prefix (Toolset.prefix/2), rename (Toolset.rename/2), filter
(Toolset.filter/2) and require approval (Toolset.require_approval/2) across
tool groups before passing them to ExAgent.new(tools: ...) — raising
ArgumentError eagerly if two tools collide on the same final name.
Reuse a LangChain text tool
Migrating incrementally from langchain? Wrap an existing %LangChain.Function{}
into an ExAgent.Tool without rewriting its handler:
defmodule MyApp.LangChainTools do
def wrap(%LangChain.Function{} = function) do
schema =
function.parameters_schema ||
LangChain.FunctionParam.to_parameters_schema(function.parameters)
ExAgent.Tool.new(
name: function.name,
description: function.description || function.name,
parameters_json_schema: schema,
concurrency: if(function.async, do: :parallel, else: :exclusive),
call: fn ctx, args ->
case LangChain.Function.execute(function, args, ctx.deps) do
{:ok, text} when is_binary(text) -> {:ok, text}
{:ok, text, _processed} when is_binary(text) -> {:ok, text}
{:error, message} when is_binary(message) -> {:tool_error, message}
_other -> raise "LangChain tool did not return a text result"
end
end
)
end
endExtend the loop with capabilities
Capabilities are composable middleware modules (use ExAgent.Capability) that
inject dynamic instructions, add tools, transform model requests (like PII
redaction or compaction), or inspect tool calls — keeping cross-cutting
concerns cleanly separated from your business tools:
defmodule MyApp.Redact do
use ExAgent.Capability
@impl true
def instructions(_cap, ctx), do: "Today is #{ctx.deps.today}."
@impl true
def before_model_request(_cap, req, _ctx),
do: {:ok, %{req | messages: MyApp.redact(req.messages)}}
@impl true
def before_tool_call(_cap, call, _ctx), do: {:ok, call}
endFor simple dynamic system prompts without a custom module, pass functions
directly in :instructions:
ExAgent.new(model: model, instructions: ["Be brief.", fn ctx -> "User: #{ctx.deps.user}" end])Stop a run with a guardrail
Guardrails (ExAgent.Guardrail) enforce hard safety boundaries — stopping the
run immediately with {:guardrail_tripped, name, stage, reason} before a bad
prompt, tool argument, final output or streamed chunk ever leaves your system:
alias ExAgent.{Guardrail, Tool}
pay = Tool.new(
name: "pay",
takes_ctx: false,
parameters_json_schema: %{
"type" => "object",
"properties" => %{"amount" => %{"type" => "integer"}},
"required" => ["amount"]
},
call: fn _ -> {:ok, "paid"} end
)
limit = Guardrail.tool_input("payment_limit", fn
%{tool_name: "pay", args: %{"amount" => n}} when n > 100 -> {:tripwire, "above_limit"}
_ -> :ok
end)
call = %ExAgent.Message.Part.ToolCall{tool_name: "pay", tool_call_id: "p1", args: %{"amount" => 120}}
model = %ExAgent.Models.Test{script: [{:tool_calls, [call]}]}
agent = ExAgent.new(model: model, tools: [pay], capabilities: [limit])
{:error, %ExAgent.RunError{reason: {:guardrail_tripped, "payment_limit", :tool_input, "above_limit"}}} =
ExAgent.run(agent, "Pay the invoice")Review stream windows before publication
In streaming runs, Guardrail.stream/3 inspects sliding text and commentary
windows before releasing deltas to subscribers:
alias ExAgent.Guardrail
review = Guardrail.stream("preview", fn %{text: text, commentary: commentary} ->
if String.contains?(text, "[internal]") or String.contains?(commentary, "[internal]") do
{:tripwire, "internal_marker"}
else
:ok
end
end, max_bytes: 1024, max_ms: 50)
agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Ready"}, capabilities: [review])
{:result, %{output: "Ready"}} =
agent |> ExAgent.run_stream("Continue") |> Enum.at(-1)Check a value with a classifier
Pair any ExAgent.Classifier (LLM or local Nx.Serving) with a guardrail at
:input, :output, :tool_input, :tool_output or :stream:
guard = ExAgent.Classifier.guardrail(classifier, :input, "intake", allow: ["support"])
agent = ExAgent.new(model: "test", capabilities: [guard])See Classify with a decision model.
Keep tool results and loops in check
Large tool responses blow up token budgets and stall models; stuck models sometimes call the same tool in a loop. Two built-in capabilities solve both:
ExAgent.Tool.OutputLimittruncates oversized tool returns inline and optionally offloads the full body to a result store, automatically giving the modelread_resultandgrep_resulttools to inspect only the slices it needs.ExAgent.Tool.RepeatGuarddetects repeated identical tool calls and warns (or stops) the model before it wastes your step budget.
alias ExAgent.Tool.{OutputLimit, ResultStore}
{:ok, cache} = ResultStore.ETS.start_link(max_bytes: 8_388_608, max_entries: 256, ttl_ms: 300_000)
limit = OutputLimit.new(max_bytes: 16_000, offload: {ResultStore.ETS, cache})
agent = ExAgent.new(model: %ExAgent.Models.Test{}, capabilities: [limit])
["read_result", "grep_result"] = Enum.map(agent.tools, & &1.name)Keep references readable after an application restart
Swap ETS for PostgreSQL so offloaded tool references remain readable across deploys and durable approval resumes:
alias ExAgent.Tool.{OutputLimit, ResultStore.Postgres}
handle = Postgres.new(MyApp.Repo, scope: "tenant-42", max_bytes: 8_388_608,
max_entries: 256, ttl_ms: 300_000)
limit = OutputLimit.new(max_bytes: 16_000, offload: {Postgres, handle})
ExAgent.new(model: %ExAgent.Models.Test{}, capabilities: [limit])Host-managed truncation
Prefer your own storage (like S3 or an existing database table)? Supply
:on_truncate and pair it with RepeatGuard:
limit = ExAgent.Tool.OutputLimit.new(
max_bytes: 16_000,
on_truncate: fn %{content: full} ->
case MyApp.Outputs.store(full) do
{:ok, id} -> "Use read_output with ID #{id} for the full result."
{:error, _reason} -> nil
end
end
)
guard = ExAgent.Tool.RepeatGuard.new(warn_at: 3, tools: {:except, ["job_status"]})
ExAgent.new(model: model, tools: tools, capabilities: [limit, guard])Combine OutputLimit with context compaction
for long multi-turn conversations.
Offer a large catalogue on demand
Sending 80+ tool definitions (for instance, from multiple MCP servers) wastes
prompt tokens and degrades tool selection. ExAgent.Tool.Search keeps those
tools deferred behind a lightweight tool_search tool so the model discovers
and loads only the tools a task actually needs:
search = ExAgent.Tool.Search.new(deferred: mcp_tools, max_results: 5)
ExAgent.new(model: model, tools: [lookup_order], capabilities: [search])Keep tool declarations fixed with bridge mode
When prompt caching matters and mutating the declared tool list mid-run would
bust your provider's prefix cache, pass mode: :bridge to Tool.Search.new/1.
The model calls discovered deferred tools through a fixed bridge tool while
keeping every permission check, schema validation and approval boundary intact.
Chain tools in a program
When a workflow requires chaining several read/transform tool calls (fetch ID →
fetch details → format), letting the model submit a small declarative
run_tool_program batch via ExAgent.Tool.CodeMode cuts extra model round
trips while keeping every step schema-validated and permission-checked:
lookup = ExAgent.Tool.new(name: "lookup", effect: :read, call: fn _ctx, _args -> %{"id" => 7} end)
describe = ExAgent.Tool.new(name: "describe", effect: :read, call: fn _ctx, %{"input" => %{"id" => id}} -> "Record #{id}" end)
agent = ExAgent.new(
model: model,
tools: [lookup, describe],
capabilities: [ExAgent.Tool.CodeMode.new(tools: ["lookup", "describe"])]
)Follow the step receipts
Each step in a tool program emits structured receipts and events so UIs and auditors can inspect every inner call, its resolved bindings and its outcome without parsing opaque logs.
Run a tool chain with persisted approval
If any step in a CodeMode program requires approval or deferral under a
persisted continuation, ExAgent pauses at that exact step, preserves already
completed steps, and resumes the remaining program after authorization.
Run code in an isolated sandbox
Need an agent to run Python or shell scripts against user data safely?
ExAgent.Sandbox runs untrusted code inside a bounded backend such as
ExAgent.Sandbox.Docker (no network by default, read-only mounts, hard CPU/time
and output ceilings):
# In your application supervision tree:
{ExAgent.Sandbox.Docker, name: MyApp.Executor, image: "python:3.13-alpine"}
# After authenticating the scope and selecting a resolved ExAgent model:
sandbox = ExAgent.Sandbox.new(
backend: {ExAgent.Sandbox.Docker, MyApp.Executor},
scope: authenticated_scope,
identity: %{"id" => "python-executor", "version" => "1"},
mounts: [{"/srv/project/dataset.txt", "/inputs/dataset"}],
limits: [time_ms: 10_000, output_bytes: 16_384]
)
agent = ExAgent.new(model: model, tools: ExAgent.Sandbox.tools(sandbox, model: model))Check a Docker mount
Verify a read-only mount works as expected inside your container image before exposing the sandbox to agents:
alias ExAgent.Sandbox
id = Sandbox.new_id()
program = """
with open('/inputs/dataset', 'rb') as source:
source.read(1)
"""
with {:ok, %{"status" => "exited", "exit_code" => code}} <- Sandbox.execute(sandbox, id, program),
{:ok, %{"text" => text}} <- Sandbox.read(sandbox, id) do
{code, text}
endDiagnose Docker startup
Run this quick shell preflight to verify your Docker daemon socket, cgroup limits and image availability on the host:
set -eu
socket=${EXAGENT_SANDBOX_SOCKET:-/var/run/docker.sock}
image=${EXAGENT_SANDBOX_IMAGE:-python:3.13-alpine}
for executable in docker bash head timeout; do
command -v "$executable"
done
test -S "$socket"
timeout 5s docker --host "unix://$socket" info \
--format '{{.OSType}} {{.CPUCfsQuota}} {{.MemoryLimit}} {{.SwapLimit}} {{.PidsLimit}}'
timeout 5s docker --host "unix://$socket" image inspect \
--format '{{.Id}} {{json (index .Config "Volumes")}}' "$image"
Isolation and threat model
Sandbox.Docker disables container networking, drops Linux capabilities,
mounts host inputs read-only, and enforces wall-clock and output limits, but
relies on Docker's kernel isolation boundary. Keep secrets out of mounted files
and environment variables, and read
Tools & models contracts for the full
Docker hardening checklist, Jobs integration and lost-result reconciliation.
Return a JSON object without Ecto
Don't need Ecto? Pass a plain JSON Schema map directly as output: and get a
JSV-validated string-keyed map back:
schema = %{
type: "object",
properties: %{metres: %{type: "integer", minimum: 0}},
required: ["metres"],
additionalProperties: false
}
model = %ExAgent.Models.Test{script: [~s({"metres":12})]}
agent = ExAgent.new(model: model, output: schema, output_mode: :prompted)
{:ok, %ExAgent.Result{output: %{"metres" => 12}}} = ExAgent.run(agent, "Distance?")Select among output schemas
Pass a list to output: (such as [MyApp.Answer, MyApp.Clarification] or
[MyApp.Answer, :text]) when an agent may return one of several typed shapes —
for example, either a structured database query or a plain-text clarifying
question. Inspect result.output_name to branch cleanly on which schema won.
Turn the output into a value
Use ExAgent.Output.function/4 to run custom domain logic on the validated
output — transforming it into your final Elixir value or asking the model to
try again with {:retry, reason}:
price = fn %MyApp.Order{} = order, ctx ->
case MyApp.Prices.quote(order, ctx.deps.catalog) do
{:ok, total} -> {:ok, %{"sku" => order.sku, "total_cents" => total}}
{:error, :unknown_sku} -> {:retry, "That SKU does not exist; pick one from the catalog."}
end
end
agent = ExAgent.new(model: model, output: ExAgent.Output.function("quote", MyApp.Order, price))
{:ok, %ExAgent.Result{output: %{"total_cents" => _}, output_name: "quote"}} = ExAgent.run(agent, prompt)Check the final answer
Add :output_validators to enforce business invariants beyond schema shape —
like requiring citations, checking domain constraints, or running an LLM-as-judge
review (ExAgent.Judge.output_validator/1):
cites_sources = fn output, _ctx ->
if output =~ "Source:", do: :ok, else: {:retry, "Cite the source of each figure."}
end
ExAgent.new(model: model, tools: tools, output_validators: [cites_sources], output_retries: 2)Wrap pure, side-effect-free validators as {:pure, fn output -> ... end} when
reusing them inside durable continuations.
Verify a document citation
Here is a complete, runnable validator that verifies a model's claimed quote
and UTF-8 byte range against the original source page in ctx.deps, forcing an
automatic retry when the model gets an offset wrong:
object = fn properties ->
%{type: "object", properties: properties, required: Map.keys(properties),
additionalProperties: false}
end
schema = object.(%{
"claim" => %{type: "string", minLength: 1},
"citation" => object.(%{
"document_id" => %{type: "string", minLength: 1},
"page" => %{type: "integer", minimum: 1},
"start_byte" => %{type: "integer", minimum: 0},
"end_byte" => %{type: "integer", minimum: 1},
"quote" => %{type: "string", minLength: 1}
})
})
verify = fn %{"citation" => citation}, ctx ->
%{"document_id" => id, "page" => page, "start_byte" => first,
"end_byte" => last, "quote" => quote} = citation
with {:ok, text} <- Map.fetch(ctx.deps.pages, {id, page}),
true <- first < last and last <= byte_size(text),
^quote <- binary_part(text, first, last - first) do
:ok
else
_ -> {:retry, "Use a verbatim source quote and half-open UTF-8 byte offsets."}
end
end
prefix = "Página 2. "
quote = "The permit expires in June."
first = byte_size(prefix)
page = prefix <> quote
cited = %{"claim" => quote, "citation" => %{
"document_id" => "permit", "page" => 2, "start_byte" => first,
"end_byte" => byte_size(page), "quote" => quote
}}
wrong = put_in(cited["citation"]["start_byte"], first - 1)
model = %ExAgent.Models.Test{script: [Jason.encode!(wrong), Jason.encode!(cited)]}
agent = ExAgent.new(model: model, output: schema, output_mode: :prompted,
output_validators: [verify])
{:ok, result} = ExAgent.run(agent, "Cite permit page 2 with byte offsets. " <> page,
deps: %{pages: %{{"permit", 2} => page}})
resultApplication citations live in result.output; for native provider citations,
see Read citations from a response.
Choose native output deliberately
Structured output defaults to output_mode: :tool, which works reliably across
every tool-capable provider and supports multiple output schemas. Switch to
output_mode: :native when you have a single schema and want provider-side
constrained decoding on a model that declares native JSON Schema support.
Ask for JSON in text with :prompted
Use output_mode: :prompted for text-only models or lightweight endpoints
where you want JSON directly in the assistant's text response (still validated
locally by JSV and your Ecto changeset):
agent =
ExAgent.new(
model: "google:gemini-3.5-flash-lite",
output: MyApp.Invoice,
output_mode: :prompted
)
{:ok, %ExAgent.Result{output: %MyApp.Invoice{}}} = ExAgent.run(agent, ticket)API: ExAgent.Tools, ExAgent.Tool, ExAgent.Output, ExAgent.Permissions,
ExAgent.Capability, ExAgent.Guardrail, ExAgent.Sandbox,
ExAgent.Tool.OutputLimit, ExAgent.Tool.Search, ExAgent.Tool.CodeMode.