ExAgent.Models.Fallback (ExAgent v3.0.0)

View Source

Retries transient provider failures and falls back to other models.

Stability — Stable.

primary = ExAgent.Models.ReqLLM.new(model: ..., foreign_history: :portable)
backup = ExAgent.Models.ReqLLM.new(model: ..., foreign_history: :portable)

model = ExAgent.Models.Fallback.new(models: [primary, backup])
ExAgent.new(model: model, tools: tools)

Each model request tries models in order. A candidate whose optional no-IO continuation preflight reports a history from another target, routing or mode (%ExAgent.RequestError{reason: {:continuation_mismatch, _}}) is skipped without a request or retry. Other preflight errors end the request before dispatching that candidate, including a later candidate's preflight inside a nested fallback. Ordinary runs can use candidates without a preflight callback. When a run opens its execution scope, an invalid fallback group fails with {:model_request_failed, %ExAgent.RequestError{provider: :fallback, reason: {:invalid_option, field}}} before the first request is counted; request/4 and request_stream/4 return the same RequestError. Explicit continuation preflight returns {:invalid_option, field} as the error reason. Persisted continuations require the callback on every candidate, including models in nested fallbacks. Selection calls validators in order and stops at the first acceptance or terminal error. A model is retried up to :max_retries times with exponential backoff (:backoff_ms doubling up to :max_backoff_ms, with jitter) and then the next model is tried at once. Only failures that returned no output are retried or fall back:

  • ExAgent.RequestError with an HTTP status in :retry_statuses (default 408, 429, 500, 502, 503, 504 and 529), with no partial response or a report carrying only usage. Reported counters are accumulated across dispatched attempts;
  • with retry_transport: true, also connection failures, a timeout waiting for the first stream event, and total timeouts. The provider may already have processed (and billed) such a request, so this is opt-in.

A gateway may still bill an upstream attempt behind a 502 or 504. Other errors, including configuration errors detected before IO, return immediately. A streaming request is retried only when its first event is a retryable error. An incomplete model reply commits the attempt. The first nonterminal event commits the stream, even a :usage update that produced no public text. A later failure returns the error and its usage without making another provider attempt. A buffered result that violates ExAgent.Model.request/4 ends the request with a RequestError whose reason is :invalid_model_result before the response or candidate state is used. Fallback's own failures use provider: :fallback.

A retryable HTTP error can supply RequestError.retry_after_ms. The same candidate waits for at least this delay. Time spent in synchronous retry telemetry handlers counts toward the wait. If the hint exceeds :max_backoff_ms, or the retry delay with or without a hint cannot fit before the run deadline, Fallback skips the candidate's remaining retries and can send a request to the next configured model immediately.

With :fallback_on_quota_denial enabled, a confirmed host rate limiter refusal skips the leaf's remaining retries and continues with compatible backups. Local admission checks for capacity without joining the FIFO queue. The default is false. The opt-in applies throughout that group's subtree. An unacknowledged permit ends the request. If every compatible leaf refuses before a dispatch, the run reports the shortest finite quota delay, then :queue_full, :unknown, or :infinity in that order. Each dispatched attempt uses its own permit.

The loop counts one admitted model request however many attempts it makes. When a candidate supplies updated state in RequestError.model, Fallback retains it in the group and checks that state's optional continuation preflight before retrying the candidate. The retry event and backoff precede this check. Its own RequestError.model is the updated group when any attempt reported state. If an earlier dispatched attempt failed without a usage report, the answering candidate's usage is partial, including usage supplied in RequestError.partial_response. Strict metric limits can then stop the run before tools execute. Each ReqLLM candidate inherits its own receive timeout when settings.timeout is nil. The remaining run time caps the selected timeout. The run deadline (ModelRequestParameters.deadline) bounds all attempts together, so an expired deadline stops selection before the next candidate's preflight or dispatch. A preflight already running can finish. If selection exhausts the deadline, the caller receives the last dispatched error, or a total timeout when no attempt supplied one. A retry decision emits [:exagent, :model, :retry] telemetry before the wait and preflight.

Different models only accept each other's responses in the history when configured for it, e.g. ExAgent.Models.ReqLLM with foreign_history: :portable; otherwise incompatible candidates are skipped and the request fails if none accepts the history. This lets a persisted history from a backup continue with that compatible model. If selection ends with only skipped candidates after a dispatched request failed, Fallback returns that provider error. If every candidate was skipped, it returns the first mismatch. Malformed history and other configuration errors remain terminal. The required capabilities must be present in every leaf before dispatch or continuation selection, including unused backups. model_name/1 and system/1 report the first model. A two-argument estimate_cost callback receives this fallback struct and the usage. To budget across candidates with different prices, pass the highest input rate and highest output rate across models to ExAgent.CostGuard.estimator/1. After the run, a response's model_name identifies a candidate only when the adapter supplies a name unique within the group.

Build the group with new/1. Each leaf model must export request/4, model_name/1 and system/1. Resolve catalogue entries and spec strings with ExAgent.Model.resolve/2 first. The group checks its full candidate tree before dispatching. A provider error carrying an unusable replacement model struct ends the group with its prior usable state.

Summary

Functions

Compose a continuation codec for this Fallback tree. Pass a leaf codec such as ExAgent.Models.ReqLLM.codec/0 or a function that selects the codec from the supplied leaf model. Each selected codec must provide dump/1 and load/2 before its state can be stored. The codec stores each leaf's portable state in candidate order. Restore uses the matching host-configured tree for credentials, policies and other static options.

Builds a fallback model from a keyword list; :models is required. Unknown, duplicate or missing options and invalid field values raise ArgumentError. To override defaults, pass Keyword.merge(defaults, overrides).

Types

leaf_codec()

@type leaf_codec() :: %{
  dump: (ExAgent.Model.model() -> {:ok, term()} | {:error, term()}),
  load: (ExAgent.Model.model(), term() ->
           {:ok, ExAgent.Model.model()} | {:error, term()})
}

t()

@type t() :: %ExAgent.Models.Fallback{
  backoff_ms: non_neg_integer(),
  fallback_on_quota_denial: boolean(),
  max_backoff_ms: non_neg_integer(),
  max_retries: non_neg_integer(),
  models: [ExAgent.Model.model()],
  retry_statuses: [pos_integer()],
  retry_transport: boolean()
}

Functions

codec(codec)

@spec codec(leaf_codec() | (ExAgent.Model.model() -> leaf_codec())) :: leaf_codec()

Compose a continuation codec for this Fallback tree. Pass a leaf codec such as ExAgent.Models.ReqLLM.codec/0 or a function that selects the codec from the supplied leaf model. Each selected codec must provide dump/1 and load/2 before its state can be stored. The codec stores each leaf's portable state in candidate order. Restore uses the matching host-configured tree for credentials, policies and other static options.

new(opts)

@spec new(keyword()) :: t()

Builds a fallback model from a keyword list; :models is required. Unknown, duplicate or missing options and invalid field values raise ArgumentError. To override defaults, pass Keyword.merge(defaults, overrides).