Runtime and events

View Source

ExAgent.run/3 handles single-shot scripts and background workers cleanly, but interactive applications need more: conversation history, live streaming tokens, user cancellation, backpressure for slow browsers, conversation forking and background jobs. ExAgent gives you an OTP runtime that solves all of those without hand-rolling fragile GenServer state machines.

What ExAgent simplifies:

  • Supervised conversations (ExAgent.Server & ExAgent.Conversations): Own conversation history, bounded turn queues, idle hibernation/eviction and lazy restoration from ETS or PostgreSQL.
  • Demand-paced LiveView delivery: Subscribers pull bounded event batches on demand (attach/3, events_since/3, ack_events/4) so a burst of streaming tokens never floods a LiveView mailbox.
  • Standard web streaming protocols: Project conversation events directly to Phoenix LiveView (ExAgent.Chat), SSE (ExAgent.Chat.SSE), Vercel AI SDK (ExAgent.Chat.AISDK) and AG-UI (ExAgent.Chat.AGUI).
  • Live steering, branching & background jobs: Interrupt or redirect a running agent (steer/3), fork/regenerate messages, and offload slow tools to ExAgent.Jobs.

Need exact event envelope schemas or delivery state tables?

For complete PubSub payload contracts, admission receipt limits and wire specs, see Runtime & ops contracts.

Start a conversation

Start a supervised ExAgent.Server with a trusted namespace: (from your authenticated session) and stable agent_id::

{:ok, server} = ExAgent.AgentSupervisor.start_agent(
  agent: ExAgent.new(model: "test", instructions: "Be concise."),
  agent_id: "docs-conversation",
  namespace: "docs-workspace",
  pubsub: :local,
  max_pending: 2
)

{:ok, first} = ExAgent.Server.chat(server, "Hello!")
{:ok, second} = ExAgent.Server.chat(server, "Continue.")
%{first: first.output, second: second.output}

Every runtime call shares one honest failure vocabulary when a reply is lost:

ReplyMeaningSafe action
{:error, :unavailable}Not dispatched (or discarded unread).Safe to retry once the owner is reachable.
{:error, {:delivery_unconfirmed, request_id}}Admission sent, ack lost; ID already fixed.Look up Server.receipt/2 with your idempotency key before retrying.
{:error, :result_unconfirmed}Request sent; effect may have run.Inspect history, events or Continuation.get/2 before repeating.

For multi-user web apps, supervise an ExAgent.Conversations manager instead of starting servers manually — it lazily activates conversations on demand, hibernates idle owners, evicts inactive ones, and restores them automatically on the next message:

children = [
  {ExAgent.Conversations, name: MyApp.Chats,
   server: fn _key -> [agent: ExAgent.new(model: "test"), store: :ets] end}
]

Subscribe before asynchronous admission

For interactive UIs, submit turns asynchronously with ExAgent.Server.send_message/3 and subscribe before submitting so you never miss an early event. Always match namespace, agent_id, request_id and run_id on every %ExAgent.Event{}:

alias ExAgent.{Event, PubSub, Server}

pubsub = PubSub.normalize(:local)
namespace = "docs-workspace"
conversation_id = "docs-conversation"
topic = Event.agent_topic(conversation_id, namespace)

with :ok <- PubSub.subscribe(pubsub, topic),
     {:ok, %{request_id: request_id, run_id: run_id}} <-
       Server.send_message(server, "Continue asynchronously.", stream_text: true) do
  receive do
    {:exagent_event, %Event{namespace: ^namespace, agent_id: ^conversation_id,
      request_id: ^request_id, run_id: ^run_id, type: type, payload: payload}}
    when type in [:run_finished, :run_failed, :run_paused, :server_request_cancelled] ->
      {type, payload}
  after
    2000 -> {:error, :event_not_observed}
  end
end

On :run_paused, load pending approvals from your store using payload.continuation. On :tool_call_finished with status: :unknown, reconcile the external effect before retrying.

Recover a turn admission after losing the reply

When a browser or worker retries after a timeout, pass an idempotency key from Server.new_admission_key/1 so the exact same logical turn is never submitted twice:

turn = %{
  key: ExAgent.Server.new_admission_key(60_000),
  request_id: request_id,
  input: "Summarize the incident"
}

Submit with idempotency_key: turn.key, and if you receive {:error, {:delivery_unconfirmed, _}}, look up the stored receipt with Server.receipt/2 instead of minting a fresh key:

alias ExAgent.{Conversations, Server}

submit = fn server ->
  Server.send_message(server, turn.input,
    queue: false, idempotency_key: turn.key, request_id: turn.request_id)
end

case Conversations.call(manager, conversation, submit) do
  {:error, {:delivery_unconfirmed, _attempt_id}} ->
    Conversations.call(manager, conversation, &Server.receipt(&1, turn.key))

  reply ->
    reply
end

Read conversation events on demand

For long-lived LiveViews and GenServers, prefer demand delivery over raw PubSub broadcasts: the Server sends a single lightweight {:exagent_events_ready, server, notice} signal per burst, and your LiveView pulls bounded pages with Server.events_since/3 and advances its cursor with Server.ack_events/4:

alias ExAgent.Server

agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Ready"})
{:ok, server} = Server.start_link(agent: agent)
:ok = Server.attach(server, self(), delivery: :demand)
{:ok, page} = Server.history_page(server, projection: :chat, include_draft: true)
{:ok, _receipt} = Server.send_message(server, "Start", stream_text: true)

receive do
  {:exagent_events_ready, ^server, notice} ->
    with {:ok, %{items: items, cursor: cursor}} <-
           Server.events_since(server, page.event_cursor, notice: notice),
         view = %{items: items, cursor: cursor},
         :ok <- Server.ack_events(server, notice, view.cursor) do
      {:ok, view}
    end
after
  2000 -> {:error, :event_not_observed}
end

If a reader falls behind retention ({:error, {:cursor_expired, _}}), fetch a fresh Server.history_page(server, projection: :chat, include_draft: true) and acknowledge the notice with page.event_cursor — seamlessly resyncing the UI including any in-progress streaming draft. Call Server.detach/2 when leaving the conversation.

Read a conversation window

Use Server.history_page/2 to paginate long chat histories cleanly into a UI without transferring the entire transcript on mount. Set projection: :chat for display-ready items (including active assistant drafts, tool progress, narration and citations), or pair it with ExAgent.Chat (SSE, AISDK, AGUI) for standard HTTP/frontend streaming protocols.

Wire a Phoenix LiveView by hand

Prefer wiring an existing Phoenix LiveView directly instead of using mix exagent.gen.live? Here is the complete demand-paced LiveView loop using ExAgent.Conversations, ExAgent.Chat, ExAgent.Chat.Reader, and durable PostgreSQL approvals — note that Chat.Reader.notice/3 reads and reduces the batch while your LiveView explicitly acknowledges chat.cursor with Server.ack_events/4:

defmodule MyAppWeb.SupportChatLive do
  use MyAppWeb, :live_view
  alias ExAgent.{Chat, Chat.Reader, Conversations, Server}

  @impl true
  def mount(%{"id" => conversation_id}, _session, socket) do
    namespace = "user/#{socket.assigns.current_user.id}"
    chat = Chat.new(namespace, conversation_id)

    if connected?(socket) do
      {:ok, server} = Conversations.ensure(MyApp.Chats, {namespace, conversation_id})
      Process.monitor(server)
      :ok = Server.attach(server, self(), delivery: :demand)
      {:ok, chat, _rows} = Reader.history(server, chat, :latest)
      {:ok, pending} = Server.pending(server)
      {:ok, assign(socket, server: server, chat: chat, pending: pending)}
    else
      {:ok, assign(socket, server: nil, chat: chat, pending: [])}
    end
  end

  @impl true
  def handle_event("send", %{"prompt" => prompt}, %{assigns: %{server: server}} = socket) do
    key = Server.new_admission_key()
    {:ok, _receipt} = Server.send_message(server, prompt, idempotency_key: key, stream_text: true)
    {:noreply, socket}
  end

  @impl true
  def handle_event("approve", %{"call_id" => call_id}, socket) do
    request = Enum.find(socket.assigns.pending, &(&1.call_id == call_id))

    with {:ok, %{continuation: ready_ref}} <-
           Server.decide(socket.assigns.server, request, :approve,
             actor: socket.assigns.current_user,
             authorize: &MyApp.Approvals.authorize/3
           ),
         false <- is_nil(ready_ref) do
      # Resume in a supervised task or Oban worker using the NEW ready_ref:
      Task.Supervisor.start_child(MyApp.TaskSup, fn ->
        Server.resume(socket.assigns.server, ready_ref, stream_text: true)
      end)
    end

    {:noreply, socket}
  end

  @impl true
  def handle_info({:exagent_events_ready, server, notice}, %{assigns: %{server: server}} = socket) do
    case Reader.notice(server, socket.assigns.chat, notice) do
      {:ok, chat, _rows_or_nil, _events} ->
        :ok = Server.ack_events(server, notice, chat.cursor)
        {:ok, pending} = Server.pending(server)
        {:noreply, assign(socket, chat: chat, pending: pending)}

      {:error, _reason} ->
        {:noreply, socket}
    end
  end
end

Stream a one-shot run

Need streaming tokens without a persistent conversation process (for a CLI tool or one-shot HTTP endpoint)? Enumerate ExAgent.run_stream/3 directly:

agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Hello from Elixir"})

ExAgent.run_stream(agent, "Hello!")
|> Enum.reduce(nil, fn
  {:text_delta, %{text: text}}, nil ->
    IO.write(text)
    nil

  {type, _} = terminal, nil when type in [:result, :error] ->
    terminal

  _element, nil ->
    nil
end)

Streaming deltas (:text_delta, :thinking_delta, :commentary_delta) are provisional for UI responsiveness; always wait for {:result, result} before delivering validated structured output.

Track a delegation in the stream

When a parent tool delegates to child agents (child_events: :all), correlate tool starts and finishes by call_ref (which stays unique even if a model provider reuses tool_call_id across turns):

Enum.reduce(events, %{}, fn
  {:tool_call_started, %{call_ref: ref, call: %{tool_name: "inspect_chart"}}}, calls ->
    Map.put(calls, ref, :running)

  {:tool_call_finished, %{call_ref: ref, return: %{tool_name: "inspect_chart"} = result}}, calls ->
    Map.put(calls, ref, result.status)

  {:error, _}, calls ->
    Map.new(calls, fn
      {ref, :running} -> {ref, :interrupted}
      closed -> closed
    end)

  _event, calls ->
    calls
end)

This reducer pairs with the Plan delegation example. For CodeMode chains, see Follow the step receipts.

Correct a live run

ExAgent distinguishes between correcting an active run mid-flight and queuing a priority follow-up turn:

  • ExAgent.Server.steer_run/3 (candidate, volatile runs only) injects a correction into the currently executing run at its next step boundary without starting a second turn ({:unsupported, :continuation_steering} on persisted C7 runs). For direct one-shot runs, use :on_steering (candidate) with ExAgent.Steering.correct/2.
  • ExAgent.Server.steer/3 queues a separate, high-priority turn at the front of the Server queue (returning its own admission receipt).

Fork and regenerate conversations

Let users explore alternate branches or retry a turn cleanly without mutating confirmed source history:

  • ExAgent.Conversations.fork/3 branches a conversation at a chosen settled root_run_id into a new agent_id while preserving history lineage (and cooperating with subject erasure).
  • ExAgent.Server.regenerate/2 forks before the selected settled turn into a mandatory destination: {manager, new_id} and submits the original (or edited) prompt there with queue: false, leaving the source conversation intact:
ExAgent.Server.regenerate(server,
  destination: {MyApp.Chats, "ticket-1042-retry"},
  at: run_id,
  run_options: [stream_text: true]
)

Cancel and checkpoint

ExAgent.Server.abort_run(server, receipt.run_id)
  • Call ExAgent.Server.checkpoint/2 to flush state to your configured Store — and if a previous persistence write failed (:checkpoint_pending), calling checkpoint/2 retries saving that exact snapshot without re-running the prompt or any tool.

Drain a conversation manager

During rolling deploys, call ExAgent.Conversations.drain/2 before shutting down a node so active servers checkpoint and finish cleanly instead of being abruptly killed mid-turn.

Inspect running processes

Call ExAgent.Server.health/1 for live queue depth (pending, pending_bytes), active run status and persistence health, and ExAgent.Runtime.list/1 / ExAgent.Runtime.info/2 to inspect supervised ExAgent servers and sessions on the current node.

Run work in the background

Slow tasks (deep web research, multi-minute scraping) shouldn't block a chat turn or trip :tool_timeout. ExAgent.Jobs wraps any tool or sub-agent so it returns a job ID immediately and lets the model keep conversing while work runs in the background (for jobs that survive node restarts, use durable Oban jobs):

alias ExAgent.{Conversations, Jobs, Tool}
require Logger

key = {namespace, conversation_id}
jobs = MyApp.SupportJobs
jobs_child = Supervisor.child_spec({Jobs, name: jobs, namespace: namespace}, id: jobs)

research =
  Jobs.agent_tool(
    jobs: jobs,
    name: "research",
    description: "Research a topic in depth. Takes minutes.",
    agent: research_agent,
    notify: fn job, _ctx ->
      destination = Conversations.via(MyApp.Chats, key)

      with {:error, reason} <- Jobs.notify_server(destination, job) do
        category = if is_atom(reason), do: reason, else: :admission_error
        Logger.warning("Notification for job #{job.id} returned #{category}")
      end
    end
  )

crawl_tool = Tool.new(
  name: "crawl",
  parameters_json_schema: %{type: "object"},
  takes_ctx: true,
  call: fn ctx, args -> ctx.deps.crawl.(args) end
)

crawl = Jobs.background(crawl_tool, jobs: jobs, notify: nil)
agent = ExAgent.new(model: model, tools: [research, crawl | Jobs.tools(jobs, max_wait_seconds: 15)])

Jobs.tools/2 gives the model job_status, wait_job and cancel_job. When a job with :notify completes, Jobs.notify_server/2 opens a new Server turn carrying a %ExAgent.Message.Part.JobNotice{} (also used by scheduled follow-up reminders). Volatile jobs live in node RAM and run outside the starting run's deadline and usage limits; check Jobs.status/2 or your business record before resubmitting any timed-out job.

API: ExAgent.Server, ExAgent.Conversations, ExAgent.Event, ExAgent.Chat, ExAgent.Jobs, ExAgent.Jobs.Durable, ExAgent.Runtime.