Skip to content

Retry and fall back when a provider fails

View as Markdown

mw.Retry is model middleware that retries a model call which failed before yielding any event: rate limits, overload, transport errors, an idle stream. It backs off between tries and honours the provider’s retry-after. mw.Fallback tries a backup model when the primary still fails. Both report every attempt on the run’s record.

Retry the model, in middleware/retries.go:

middleware/retries.go
agt := weft.New(primary,
weft.WrapModel(mw.Retry(
mw.MaxRetries(3), // retries after the first try (default 3)
mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s
mw.MaxWait(30*time.Second), // a longer retry-after fails at once (default 60s)
mw.Classifier(func(err error) bool {
return mw.Retryable(err) || errors.Is(err, errWarmingUp)
}),
)),
attempts(w), // print each reported attempt
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))

middleware/retries.go on GitHub

The scripted model fails twice, then answers. The agent’s weft.Logger prints each reported attempt:

attempt attempt=1 model=large err=model is warming up
attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests
attempt attempt=3 model=large layer=retry wait=5ms
retry: "Order 1234 has shipped." after 3 requests

The first failure is retried because the custom classifier accepts it, after a backoff of about 10 ms (between 7.5 and 12.5 ms: ±25% jitter). The second is a 429 that asked for 5 ms, and Retry waited exactly that.

The loop never retries a model call itself. Retries are model-seam middleware, installed with weft.WrapModel like any other: see Add behaviour with middleware.

Retry and Fallback act only on a call that failed before any event reached the loop. Once part of a reply has been consumed, no middleware can take it back, so a failure after the first event is the run’s error. With the default classifier and fallback predicate, context cancellation and the WEFT_MODEL_REQUESTS=deny kill switch never retry and never fall through; a custom mw.Classifier or mw.FallbackWhen predicate replaces those rules and can change that. Retry itself never retries once the run’s context is done.

Each attempt gets its own copy of the request’s slices and Params values. What a failed attempt’s model, or a middleware inside Retry, wrote into its request never reaches the next attempt (rewrite a request).

The vendor SDKs have transport retries of their own, below the adapter. mw.Retry is the layer above them that you can see: its backoff shows in the attempt records and in mw.Log.

mw.Retry(opts...) takes mw.RetryOption values:

OptionDefaultEffect
mw.MaxRetries(n)3Retries after the first try. 0 disables retrying; the retry-after rule and the classifier still apply. A negative n is ignored.
mw.BaseDelay(d)500msThe first backoff. Delays double per retry (0.5s, 1s, 2s, …), capped at 8s; ±25% jitter is applied after the cap, so a capped delay lands between 6s and 10s. 0 means no delay.
mw.MaxWait(d)60sThe longest retry-after ask Retry sleeps on. A longer ask fails at once. 0 removes the cap.
mw.Classifier(fn)mw.RetryableReplaces the test that decides whether an error is retried.

A retry-after the provider sends wins over the backoff. Retry reads the retry-after-ms header, then retry-after (seconds, or an HTTP date), and an x-should-retry header overrides the status rule. When the retries run out, the last error comes back wrapped as mw: giving up after 3 retries: …, so errors.As on the SDK’s error type still works. The package example is ExampleRetry.

A provider that asks for longer than MaxWait gets no sleep. The call fails at once wrapping mw.ErrRetryAfterTooLong, with the provider’s own error underneath, so a queue or a person can decide:

middleware/retries.go
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
var apiErr *apiError
fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr))

middleware/retries.go on GitHub

Here the provider asked for two minutes against the 60-second default; the output is too long: true true after one request. This check outranks the retry budget, so even MaxRetries(0) reports ErrRetryAfterTooLong rather than the raw error.

The default classifier is mw.Retryable:

  • Retried: weft.ErrStreamIdle, any net.Error, and HTTP 408, 409, 429 and 5xx.
  • Never retried: context errors, the kill switch, weft.ErrUnsupported, weft.ErrModelContract, every other 4xx (quota, billing, a bad request), and a context-window overflow.

mw imports no vendor SDK. It finds the status and headers on the error chain by shape, which the helpers expose for your own classifier:

middleware/retries.go
err := providerError(429, "250")
status, _ := mw.HTTPStatus(err) // 429, from the StatusCode field
ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms
fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err))
overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum")
fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow))

middleware/retries.go on GitHub

  • mw.HTTPStatus(err) reads an exported integer StatusCode field (openai-go, anthropic-sdk-go) or Code field (genai) on any error in the chain.
  • mw.RetryAfter(err, now) reads the retry-after headers from a Response field on the chain. It reports false for a missing header and for a value that cannot become a duration (unparseable, negative, or too large).

The example prints helpers: 429 250ms true and overflow: true false.

mw.IsContextOverflow(err) reports whether the error’s text names a context-window overflow, such as context_length_exceeded or prompt is too long. Retryable treats such an error, and weft.ErrContextOverflow that the first-party adapters wrap, as terminal: the same request cannot succeed again. Route it to compaction instead; see Keep long sessions inside the context window.

Pair Retry with the adapter’s MaxRetries(0)

Section titled “Pair Retry with the adapter’s MaxRetries(0)”

The OpenAI and Anthropic SDKs retry twice by default, and they sleep on the provider’s retry-after inside the adapter’s idle timer. A long ask then fails as ErrStreamIdle with the 429 and its header discarded. Pass openai.MaxRetries(0) or anthropic.MaxRetries(0) to switch the SDK’s retries off, so mw.Retry owns every retry, honours the ask under MaxWait and records it. See Connect a model provider.

mw.Fallback(models...) tries the given models in order when the wrapped model fails before yielding any event, for example an outage or a capability gap (weft.ErrUnsupported). Put it outside mw.Retry so the primary is retried first:

middleware/retries.go
agt := weft.New(primary,
weft.WrapModel(
mw.Fallback(backup), // outer: switch models once Retry gives up
mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary
),
attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))

middleware/retries.go on GitHub

attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable
attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable
attempt attempt=3 model=small layer=fallback
fallback: "Order 1234 has shipped.", backup requests 1

Retry spent its one retry on the primary, gave up, and Fallback sent the request to small, marked layer=fallback. A max_tokens finish is a successful stream, so Fallback does not switch on it. A failure after events were yielded is not retried anywhere. The agent’s Info still reports the primary. The package example is ExampleFallback.

When every model in the chain fails, the run error is the last model’s error alone. The earlier models’ errors are not on its chain; they are on the attempt spans, one per request, and in Studio’s attempts.

The order matters. With Retry outside Fallback, Retry retries the fallback chain as a whole: the primary gets one try per retry cycle, each followed by the backup, and Retry never sees the primary’s transient failures.

mw.FallbackWhen(when, models...) tries the next model only for errors when accepts. A nil when is Fallback’s default: anything but cancellation and the kill switch.

middleware/retries.go
onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) }
agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup)))
res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice."))

middleware/retries.go on GitHub

The ErrUnsupported failure (a PDF the primary cannot read) goes to the vision backup; a 503 is not accepted, so the run fails with it.

The predicate receives each failed model’s error before the next model is tried, so it is the place to classify the primary’s failure: count a 429 or log the outage there.

Inside the model chain, weft.ReportFromContext(ctx) returns the current model call’s weft.Reporter. Reporter.Attempt records one provider request: an attempt span under the step’s chat span and, with the agent’s logger at Debug, a model attempt line. mw.Retry and mw.Fallback report every try this way; your own middleware can too:

middleware/retries.go
// reportAttempts reports every call through it as one attempt on the
// run's record: an attempt span under the step's chat span, and a
// "model attempt" Debug line on the agent's Logger.
func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} }
type attemptReporter struct{ next weft.Model }
func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
return func(yield func(weft.ModelEvent, error) bool) {
info, start := weft.InfoOf(m.next), time.Now()
var failed error
for ev, err := range m.next.Stream(ctx, req) {
failed = err
if !yield(ev, err) || err != nil {
break
}
}
status, _ := mw.HTTPStatus(failed)
weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{
Model: info.Name, Provider: info.Provider,
Start: start, End: time.Now(),
Err: failed, HTTPStatus: status,
})
}
}
func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m attemptReporter) Unwrap() weft.Model { return m.next }
// ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback)
// that this one reports, so each request is reported once.
func (m attemptReporter) ReportsAttempts() bool { return true }

middleware/retries.go on GitHub

Install it like any model middleware. Its ReportsAttempts method tells the mw.Retry above it to stay silent, so each request is reported once:

middleware/retries.go
agt := weft.New(primary,
weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports
attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))

middleware/retries.go on GitHub

attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error
attempt attempt=2 model=large
A run whose model call was retried: the header counts one model attempt retried, and the waterfall's model row holds attempt 1, marked model_error, and attempt 2, which answeredA run whose model call was retried: the header counts one model attempt retried, and the waterfall's model row holds attempt 1, marked model_error, and attempt 2, which answered
A run page with a retried model call: the model row holds attempt 1, which failed, and attempt 2, which answered.

The reporter numbers the attempts 1, 2, … itself, per model call. An weft.AttemptInfo carries what the reporting code saw; a field it does not know stays zero:

FieldMeaningOn the attempt span
Model, ProviderThe model id requested and its providergen_ai.request.model, gen_ai.provider.name
Start, EndWhen the attempt ran; both or neither, else ignoredthe span’s times
ErrThe failure, nil on successerror.type (classified, below), status Error
RetryAfterThe wait the provider asked forweft.attempt.retry_after_ms
Layerweft.AttemptLayerFallback ("fallback") on a request mw.Fallback sent to a backup, weft.AttemptLayerRetry ("retry") on one mw.Retry sent again after a failure; empty on a first tryweft.attempt.layer
WaitHow long the layer waited before sending itweft.attempt.wait_ms
HTTPStatusThe provider’s HTTP status, when known; mw.Retry and mw.Fallback read it with mw.HTTPStatushttp.response.status_code
GiveUpWhy the reporting layer stopped after this failed attempt: weft.AttemptGiveUpBudget (budget, its retries spent), AttemptGiveUpNotRetryable (not_retryable, a failure it does not retry), AttemptGiveUpRetryAfter (retry_after_too_long, a retry-after past MaxWait)weft.attempt.giveup_reason

mw.Retry fills Wait, HTTPStatus and GiveUp. GiveUp is that layer’s stop, not always the call’s: a Retry under a Fallback marks where it stopped, and the call may go on to the backup. It is empty on an attempt the layer followed with another and on a success. It is also empty when the run was cancelled (the run names its own cause), when the failed attempt had already streamed output (Retry stops once output was yielded, without a give-up reason), and when a model that reports its own attempts sits under the layer. The package example ExampleAttemptInfo (giveUp) shows it.

A failed attempt’s error.type is a closed set, finer than the run’s: the context errors and weft’s own failures as the run reads them (stream_idle, …), context_overflow, then by the provider’s HTTP status rate_limit (429), overloaded (503, 529), timeout (408, 504, or a transport timeout), auth (401, 403), server_error (any other 5xx), and model_error for the rest. Before 0.20.0 every provider failure read model_error; the run’s own error.type keeps its table. Studio words each cause in the attempts list (“rate limited (429)”), ends a failed call with “gave up: retries spent (2 attempts)”, and draws an attempt’s weft.attempt.wait_ms as a hatch before its bar.

From the second attempt on, each report also adds its own request record. A layer that holds the attempt’s wire bytes can report them with Reporter.Raw before its Attempt; they are recorded only when a destination asks for raw bodies (otel.RawBodies, development only), and dropped otherwise. Reporting is not a seam: no report changes a step, a retry or the model chosen. A report never returns an error, never blocks, and a panicking tracer or log handler is contained and counted in Agent.TapPanics.

Outside a run’s model call the reporter is a no-op, never nil: in a tool handler, on a bare Model.Stream, or on a context the loop did not hand the chain. AttemptLayerFallback is what Studio’s fallbacks counter keys on, never a comparison of model names; a reader that took any non-empty layer for a fallback must compare with fallback since 0.20.0 added retry. A backup under its own mw.Retry beneath mw.Fallback marks every request it sends fallback, its retries included, so the counter counts the run it answered. The run row also counts attempts_retried: failed attempts a later attempt of the same call followed. The package example ExampleReportFromContext wraps a model the same way. To see the attempts on a run, open it in Studio: Read a run in Studio.

middleware/retries.go runs every snippet on this page. Its apiError type stands in for a vendor SDK’s error, which mw reads by shape:

middleware/retries.go
package main
import (
"context"
"errors"
"fmt"
"io"
"iter"
"log/slog"
"net/http"
"strings"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/mw"
"github.com/weftgo/weft/wefttest"
)
// apiError stands in for a vendor SDK's error type. mw reads it the way
// it reads openai-go's and anthropic-sdk-go's: structurally, an int
// StatusCode field and a Response whose Header carries retry-after.
type apiError struct {
StatusCode int
Response *http.Response
}
func (e *apiError) Error() string {
return fmt.Sprintf("provider: %d %s", e.StatusCode, http.StatusText(e.StatusCode))
}
// providerError is a failed response; retryAfterMS, when set, is the
// provider's retry-after-ms header.
func providerError(status int, retryAfterMS string) error {
h := http.Header{}
if retryAfterMS != "" {
h.Set("retry-after-ms", retryAfterMS)
}
return &apiError{StatusCode: status, Response: &http.Response{StatusCode: status, Header: h}}
}
// named gives a scripted model a provider and model name, as an adapter
// reports them.
type named struct {
weft.Model
info weft.ModelInfo
}
func (n named) Info() weft.ModelInfo { return n.info }
func model(provider, name string, turns ...wefttest.Turn) (*wefttest.Model, weft.Model) {
s := wefttest.Script(turns...)
return s, named{Model: s, info: weft.ModelInfo{Provider: provider, Name: name}}
}
// attemptLog is a slog handler that prints the loop's "model attempt"
// Debug lines, the log form of each reported attempt, and drops the rest.
type attemptLog struct{ w io.Writer }
func (h attemptLog) Enabled(context.Context, slog.Level) bool { return true }
func (h attemptLog) WithAttrs([]slog.Attr) slog.Handler { return h }
func (h attemptLog) WithGroup(string) slog.Handler { return h }
func (h attemptLog) Handle(_ context.Context, r slog.Record) error {
if r.Message != "model attempt" {
return nil
}
var b strings.Builder
r.Attrs(func(a slog.Attr) bool {
switch a.Key {
case "wait": // rounded to 5 ms: a backoff carries ±25% jitter
fmt.Fprintf(&b, " wait=%v", a.Value.Duration().Round(5*time.Millisecond))
case "attempt", "model", "layer", "retry_after", "status", "err":
fmt.Fprintf(&b, " %s=%v", a.Key, a.Value)
}
return true
})
fmt.Fprintln(h.w, " attempt"+b.String())
return nil
}
func attempts(w io.Writer) weft.Option { return weft.Logger(slog.New(attemptLog{w})) }
// errWarmingUp is an application error a custom classifier retries.
var errWarmingUp = errors.New("model is warming up")
func retryDemo(ctx context.Context, w io.Writer) error {
script, primary := model("acme", "large",
wefttest.Fail(errWarmingUp), // retried by the custom classifier, after a backoff
wefttest.Fail(providerError(429, "5")), // rate limited: asks for 5 ms
wefttest.Say("Order 1234 has shipped."),
)
agt := weft.New(primary,
weft.WrapModel(mw.Retry(
mw.MaxRetries(3), // retries after the first try (default 3)
mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s
mw.MaxWait(30*time.Second), // a longer retry-after fails at once (default 60s)
mw.Classifier(func(err error) bool {
return mw.Retryable(err) || errors.Is(err, errWarmingUp)
}),
)),
attempts(w), // print each reported attempt
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintf(w, "retry: %q after %d requests\n", res.Text(), len(script.Requests()))
return nil
}
func retryAfterTooLong(ctx context.Context, w io.Writer) error {
script, primary := model("acme", "large", wefttest.Fail(providerError(429, "120000"))) // asks for 2 minutes
agt := weft.New(primary, weft.WrapModel(mw.Retry()))
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
var apiErr *apiError
fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr))
fmt.Fprintf(w, "too long: %d request\n", len(script.Requests()))
return nil
}
func retryHelpers(w io.Writer) {
err := providerError(429, "250")
status, _ := mw.HTTPStatus(err) // 429, from the StatusCode field
ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms
fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err))
overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum")
fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow))
}
func fallbackDemo(ctx context.Context, w io.Writer) error {
_, primary := model("acme", "large",
wefttest.Fail(providerError(503, "5")),
wefttest.Fail(providerError(503, "5")),
)
backupScript, backup := model("other", "small", wefttest.Say("Order 1234 has shipped."))
agt := weft.New(primary,
weft.WrapModel(
mw.Fallback(backup), // outer: switch models once Retry gives up
mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary
),
attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintf(w, "fallback: %q, backup requests %d\n", res.Text(), len(backupScript.Requests()))
return nil
}
func fallbackWhenDemo(ctx context.Context, w io.Writer) error {
for _, failure := range []error{
fmt.Errorf("%w: pdf input", weft.ErrUnsupported),
providerError(503, ""),
} {
_, primary := model("acme", "large", wefttest.Fail(failure))
_, backup := model("other", "vision", wefttest.Say("The invoice total is 120 EUR."))
onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) }
agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup)))
res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice."))
if err != nil {
fmt.Fprintln(w, "fallback-when:", err) // a 503 is not ErrUnsupported: no fallback
continue
}
fmt.Fprintf(w, "fallback-when: %q\n", res.Text())
}
return nil
}
// reportAttempts reports every call through it as one attempt on the
// run's record: an attempt span under the step's chat span, and a
// "model attempt" Debug line on the agent's Logger.
func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} }
type attemptReporter struct{ next weft.Model }
func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
return func(yield func(weft.ModelEvent, error) bool) {
info, start := weft.InfoOf(m.next), time.Now()
var failed error
for ev, err := range m.next.Stream(ctx, req) {
failed = err
if !yield(ev, err) || err != nil {
break
}
}
status, _ := mw.HTTPStatus(failed)
weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{
Model: info.Name, Provider: info.Provider,
Start: start, End: time.Now(),
Err: failed, HTTPStatus: status,
})
}
}
func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m attemptReporter) Unwrap() weft.Model { return m.next }
// ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback)
// that this one reports, so each request is reported once.
func (m attemptReporter) ReportsAttempts() bool { return true }
func reportDemo(ctx context.Context, w io.Writer) error {
_, primary := model("acme", "large",
wefttest.Fail(providerError(500, "")),
wefttest.Say("Order 1234 has shipped."),
)
agt := weft.New(primary,
weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports
attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
// Outside a run's model call the reporter is a no-op: nothing prints.
weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{Model: "ignored"})
fmt.Fprintf(w, "report: %q\n", res.Text())
return nil
}
// demoRetries is the retries-and-fallback page's complete example.
func demoRetries(ctx context.Context, w io.Writer) error {
if err := retryDemo(ctx, w); err != nil {
return err
}
if err := retryAfterTooLong(ctx, w); err != nil {
return err
}
retryHelpers(w)
for _, demo := range []func(context.Context, io.Writer) error{fallbackDemo, fallbackWhenDemo, reportDemo} {
if err := demo(ctx, w); err != nil {
return err
}
}
return nil
}

View middleware/retries.go on GitHub

Run it from docs-site/examples:

Terminal window
go run ./middleware retries
go test ./middleware
attempt attempt=1 model=large err=model is warming up
attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests
attempt attempt=3 model=large layer=retry wait=5ms
retry: "Order 1234 has shipped." after 3 requests
too long: true true
too long: 1 request
helpers: 429 250ms true
overflow: true false
attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable
attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable
attempt attempt=3 model=small layer=fallback
fallback: "Order 1234 has shipped.", backup requests 1
fallback-when: "The invoice total is 120 EUR."
fallback-when: weft: run failed at step 0: model stream: provider: 503 Service Unavailable
attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error
attempt attempt=2 model=large
report: "Order 1234 has shipped."

The attemptLog handler rounds wait to 5 ms, because a backoff carries jitter.

  • Put mw.Fallback outside mw.Retry. The primary is retried to exhaustion before the backup is tried. (Source: weft/core/mw/doc.go:15-19)
  • Switch the SDK’s retries off when you use mw.Retry. openai.MaxRetries(0) and anthropic.MaxRetries(0) stop the SDK sleeping on a retry-after inside the idle timer. (Source: weft/core/mw/retry.go:93-108, weft/CHANGELOG.md:5660)
  • Expect nothing to be retried after the first event. Part of the reply has reached the loop; the failure is the run’s error. (Source: weft/docs/adr/0006-seams.md:93-96)
  • Do not retry a context overflow. The same bytes cannot fit; compact or shorten the request. (Source: weft/core/mw/retry.go:283-291, weft/core/mw/retry.go:467-473)
  • Use BaseDelay(0) only in tests. The default is 500ms doubling to 8s; zero removes the spacing a rate-limited provider needs. (Source: weft/mw/example_test.go:28)
  • Expect the backup’s error when the backup fails too. errors.Is(err, weft.ErrUnsupported), an mw.HTTPStatus check for a 429, or a log line on the run error all see the last model’s error, so a misconfigured backup (no key, a wrong model id) hides the primary’s real failure. Read the primary’s error on the attempt spans or in Studio’s attempts, or classify it in a FallbackWhen predicate before the backup runs. (Source: weft/core/mw/model.go:118-125, weft/core/mw/model.go:38-44)
  • Declare ReportsAttempts when your layer reports. Without it, a mw.Retry above reports the same requests again. (Source: weft/core/report.go:151-157, weft/core/mw/model.go:253-283)

Symbols used: mw.Retry · mw.RetryOption · mw.MaxRetries · mw.BaseDelay · mw.MaxWait · mw.Classifier · mw.Retryable · mw.RetryAfter · mw.HTTPStatus · mw.IsContextOverflow · mw.ErrRetryAfterTooLong · mw.Fallback · mw.FallbackWhen · weft.WrapModel · weft.ReportFromContext · weft.Reporter · Reporter.Attempt · Reporter.Raw · weft.AttemptInfo · weft.AttemptLayerFallback · weft.InfoOf · weft.Logger · weft.ErrStreamIdle · weft.ErrUnsupported · weft.ErrContextOverflow · openai.MaxRetries · anthropic.MaxRetries · wefttest.Script