Chapter 21

AI Backends

Stream a model over Server-Sent Events, serve the streaming and non-streaming shape from one handler, relay an upstream provider and classify what it returns.

An AI backend is a web service whose responses are produced by a model rather than by a database, and that one difference reorganises the HTTP layer around it. The answer arrives in fragments over seconds or minutes, it is not all prose, the same endpoint has to serve it as a stream and as a single document, the thing producing it is a third party that fails in five distinct ways, and the client is entitled to leave halfway through. The ai package is the vocabulary for that shape. It renders a model’s output on the wire, relays somebody else’s, and classifies what went wrong upstream. It ships no vendor SDK and no provider schema: what travels over the wire is your business, and the shape of the wire is this package’s.

Background

A language model generates its answer one token at a time, and each token depends on every token before it. There is no way to produce the last word faster than the first, so the total time is set by the length of the answer: a few hundred words is tens of seconds of work. Holding all of it back until the end therefore means a client that waits and shows nothing, which is why every AI product streams. The number that matters to a reader is not the duration but the time to the first fragment, because after that the text arrives at reading speed.

What the model emits is not only prose. Four other things travel on the same channel. Many models produce a reasoning trace, a running commentary on the problem that most interfaces render differently from the answer or hide behind a toggle. A model with tools available emits a tool call instead of text, and its arguments arrive in fragments that are not valid JSON until the last one lands. The provider reports usage, the token counts a turn cost, sometimes at the start and sometimes at the end and sometimes in both places. And a generation that started successfully can fail halfway, after the response has already begun with a 200.

That last point is the one that bends HTTP. A status code is written once, before the body, and a streamed answer commits it with the first fragment. Everything that goes wrong after that has to be reported inside the body, in a channel the client is already parsing as content, which means the transport needs a way to say “this ended badly” and a way to say “this ended”. Truncation is the failure to worry about: a proxy idle timeout closes a stream cleanly, so a client that assumes a closed connection means a finished answer will silently show half an answer as the whole.

The wire format for all of this is Server-Sent Events, covered in Chapter 6, because a model stream is one-way text and a WebSocket buys nothing for it. The ai package sits on the sse package and adds the vocabulary: what the fragments are, how a non-streaming client gets the same answer as one document, and what to do when the upstream that produces them refuses.

One Handler, Both Shapes

Every OpenAI-shaped API takes a stream field in the request body and serves both answers from one endpoint: a stream of fragments when it is true, one JSON document when it is not. Writing that as two handlers duplicates the generation loop, and writing it as one handler with branches duplicates it inside. ai.Open removes the choice from the handler body:

Go
package main

import (
    "strings"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/ai"
    "github.com/kataras/iris/v14/rest/errors"
)

// ChatRequest is the request body. Stream mirrors what every
// OpenAI-shaped API puts there.
type ChatRequest struct {
    Prompt string `json:"prompt"`
    Stream bool   `json:"stream"`
}

// Validate runs automatically inside ctx.BindJSON.
func (r ChatRequest) Validate() error {
    if strings.TrimSpace(r.Prompt) == "" {
        return iris.ErrEmptyForm
    }

    return nil
}

func chat(ctx iris.Context) {
    req, ok := ctx.BindJSON[ChatRequest]()
    if !ok {
        return // BindJSON has already written the 400.
    }

    o := ai.DefaultOptions()
    o.Stream = &req.Stream // honour the request body.

    res, err := ai.Open(ctx, o)
    if errors.HandleError(ctx, err) {
        return
    }

    for delta := range generate(req.Prompt) {
        if err := res.Send(ai.Text("m1", delta)); err != nil {
            res.Close(err)
            return
        }
    }

    res.Send(ai.Meter(ai.Usage{InputTokens: 12, OutputTokens: 24}))
    res.Close(nil)
}

When the request asks to stream, each part goes out as it is produced. When it does not, the parts are accumulated and Close writes them as one JSON document. Nothing between Open and Close changes, and res.Streaming() reports which shape the turn took for the handful of cases that care.

ai.DefaultOptions() carries two other settings worth knowing before the first run. Options.SSE is the sse.Options from Chapter 6, so the heartbeat and the send deadline are configured there. And Options.Coalesce defaults to 100 milliseconds, which means consecutive text and reasoning deltas leave as at most one frame of each per interval rather than one frame per token. It batches parts rather than encoded bytes, because concatenating two rendered frames would destroy the structure the client is parsing. Zero disables it.

Options.Stream is a *bool rather than a bool because the zero value has to stay distinguishable from “not configured”. Left nil, Open negotiates on the Accept header and streams when the client asked for text/event-stream. A plain bool in a struct-valued option would mean “do not stream” for every caller who did not set it, which is the opposite of what half of them intend.

Like sse.Open, ai.Open writes nothing. An authorization check or a policy veto after it still produces an ordinary status code with an ordinary body, and res.Committed() reports whether that is still possible.

The Part Vocabulary

A Part is one increment of an answer. There are seven kinds, and each has a constructor:

ConstructorKindCarries
ai.Text(id, delta)KindTextA fragment of the answer
ai.Reasoning(id, delta)KindReasoningA fragment of the reasoning trace
ai.ToolCall(id, name, args)KindToolCallA tool the model wants called, with raw JSON arguments
ai.ToolResult(id, result)KindToolResultWhat the tool returned
ai.Meter(usage)KindUsageWhat the turn cost
ai.Error(err)KindErrorA failure that happened after the response began
ai.Data(name, raw)KindDataAnything this vocabulary does not model, passed through under its own name

Part’s fields are unexported, so an invalid combination cannot be constructed: there is no way to build a tool call carrying reasoning text or a usage part with a delta, and therefore no encoder has to defend against one. That is as close as Go gets to a sum type, and it turns the grammar into an invariant rather than a doc comment. Read a part back through Kind(), ID(), Delta(), Name(), Args(), Result(), Usage(), Raw() and Err(), each of which answers for the kinds that have it.

Seven kinds is a deliberate ceiling. A richer grammar of start, delta and end triples per content block buys compile-time sequence safety, but only to a framework that owns the generation loop, and this one deliberately does not. The id argument gives an interface the same correlation for a fraction of the surface: parts sharing an id belong to the same message.

KindData is the escape hatch and it earns its place. Providers add event types continuously, and a closed union would reject a valid-but-newer producer, so a relay passes an unrecognised event through under its own name instead of dropping it. Strict on emit, lenient on parse.

Encoders

An Encoder renders parts in a wire dialect. Three ship with the package:

EncoderWireUse it for
ai.SSEJSON()One SSE frame per part, named for its kind, carrying neutral JSONThe default. Browsers and anything that speaks SSE
ai.NDJSON()One JSON object per line, no SSE framing, ending with {"type":"done"}A server-to-server consumer, where the framing buys nothing and parsing is one json.Decoder
ai.PlainText()The text deltas and nothing elsecurl, and a client that wants prose rather than a protocol

PlainText drops reasoning, tool calls and usage, because the dialect has nowhere to put them, and it has neither a terminator nor an in-band error: a failure still reaches the logger and the collector, just not the reader. NDJSON has both, so its consumer detects truncation the way an SSE client does, by the missing terminal line; a failure after the first byte arrives as {"type":"error","error":{...}} before it, carrying the same rest/errors envelope the SSE error frame carries. Selecting an encoder is one field, so serving three formats from the handler above is one condition:

Go
if ctx.Query().Get("format") == "text" {
    o.Encoder = ai.PlainText()
}

The Encoder interface is the one seam through which a vendor shape may enter, and it points outward on purpose. The AI SDK UI Message Stream, AG-UI and the OpenAI chat.completion.chunk shapes are vendor response schemas, and a framework that ships one has signed up to track that vendor forever: that format alone changed its framing, its transport, its header name and its semantics inside eighteen months, and its header carries someone else’s brand. Those belong in iris-contrib, written against this interface and pinned to a version. Implementing one means five methods (ContentType, Header, Open, Encode, Close) writing into a Sink, which offers Frame for an event stream and Write for a line-oriented dialect.

Reasoning Fenced in a Tag

Some providers return the reasoning trace in its own field, which decodes straight into an ai.Reasoning part. Others emit it inline, fenced by a tag such as <think>, in the same text channel as the answer. Splitting that with a strings.Contains on each delta does not work, because the tag arrives split across deltas as often as not: "<th" in one chunk and "ink>" in the next. The check misses the tag and the characters leak into the answer.

Go
splitter := ai.TagSplit("m1", "<think>", "</think>")

for delta := range generate(req.Prompt) {
    for _, part := range splitter.Write(delta) {
        if err := res.Send(part); err != nil {
            res.Close(err)
            return
        }
    }
}

// At the end of the stream, release whatever is still held back.
for _, part := range splitter.Flush() {
    res.Send(part)
}

Write holds back only what could still turn out to be the start of a tag, so at most len(tag)-1 characters are ever delayed and a tag split across any number of chunks is recognised. Flush matters as much as Write: a tag that never completed is not a tag, its characters are part of the answer, and dropping them would truncate it silently. Inside() reports where the splitter currently is, and StartInside() covers the real and otherwise baffling dialect of a model that emits a closing tag having never emitted an opening one.

Policy and Accounting

Two hooks on ai.Options cover what a production turn needs around the generation itself.

OnPart runs before each part is encoded, and has three outcomes. Returning the part forwards it, possibly rewritten. Returning ai.ErrDropPart drops it and keeps the stream going. Returning any other error fails the turn. That is the whole policy surface, and it is block-only by construction: you cannot revise what has already gone out, so the restriction lives in the type rather than in a warning. A hook that could rewrite history would pass its tests and fail on the wire.

Go
o.OnPart = func(ctx iris.Context, p ai.Part) (ai.Part, error) {
    if p.Kind() == ai.KindReasoning && !ctx.Values().GetBool("staff") {
        return p, ai.ErrDropPart // internal readers only.
    }

    return p, nil
}

OnFinish runs exactly once after the turn ends, under context.WithoutCancel, with the assembled answer and the usage. It runs on success, on failure and on client disconnect alike, which is the whole reason it exists: a client that hung up is exactly when recording what the upstream already spent matters most. Persistence, billing and metrics belong here. The stream is an optimisation and never the source of truth, because a design in which the only copy of the answer is on the wire loses answers.

Go
o.OnFinish = func(ctx context.Context, r *ai.Result) {
    if err := store.SaveTurn(ctx, r.Text, r.Usage); err != nil {
        app.Logger().Errorf("saving turn: %v", err)
    }
}

The ai.Result it receives is also available from res.Result() and is complete after Close:

FieldWhat it holds
Streaming, Committed, DisconnectedWhich shape the turn took, whether any byte reached the client, and whether the client left
AbandonedThe handler returned without calling Close. The framework ended the turn before the response was recycled: nothing was written after that, a pending part was dropped, and the client got no terminator
Text, ReasoningThe assembled answer and trace
ToolCallsThe tool-call parts, which already carry the id, the name and the raw arguments
UsageAccumulated across every usage part the turn produced
PartsEvery part, when Options.KeepParts is set
ErrWhy the turn ended badly, or nil
TTFP, DurationTime to the first part, and the whole turn

KeepParts is off by default because a long generation would otherwise be held twice, once as assembled text and once as every delta that built it. TTFP is the field to watch: total duration is dominated by how long the answer is, so it measures the model rather than the service, while time to the first part is the latency a reader actually perceives.

Usage carries token counts and deliberately no money. Pricing a provider means tracking every provider’s price list forever, and it changes more often than a framework ships. Compute cost in OnFinish, where you already know which model ran.

OnDisconnect decides what a vanished client does to the work in progress. ai.DisconnectCancel, the default, ends the turn as soon as the client goes away, because an abandoned generation burns tokens nobody will read. ai.DisconnectDetach keeps consuming the upstream so OnFinish records what was actually spent. Detaching does not mean the handler returns and work continues in the background: the handler still runs to completion, only the client is gone.

Relaying an Upstream

A service that calls a provider rather than running its own model is relaying: read an upstream event stream, translate each event into parts, forward them. ai.Relay is that loop.

Go
resp, err := httpClient.Do(req)
if ue := ai.Classify(resp, err); ue != nil {
    return res.Close(ue)
}

return res.Close(ai.Relay(res, resp, decoder, ai.RelayOptions{
    Read: sse.ReadOptions{Terminators: []string{"[DONE]"}},
}))

Relay closes the response body, classifies the response before reading it so a non-2xx upstream comes back as a typed error rather than as an empty stream, and checks the content type so a gateway that answers 200 with a JSON error does not silently become a blank answer. That last check is on by default and RelayOptions.AllowNonEventStream turns it off, handing the body to the decoder as a single event.

Every failed read of the upstream body comes back the same way: a reset, a timeout, a stream cut mid-event, or one closed cleanly without the sentinel RelayOptions.Read.Terminators promised, all pass through Classify as a transient upstream error wrapping the cause. The client gets a BAD_GATEWAY error frame (DEADLINE_EXCEEDED when the cause was a timeout) rather than a terminator claiming the answer was complete, and a gateway’s failover logic sees the upstream failure it is. A client that hangs up mid-read stays ClassCanceled. Relay sets sse.ReadOptions.RequireTerminator whenever terminators are configured, with no opt-out.

The Decoder is your code, one method turning one upstream event into zero or more parts. The framework has no business knowing what a particular vendor calls a delta this month:

Go
decoder := ai.DecoderFunc(func(ev sse.Event) ([]ai.Part, error) {
    var chunk struct {
        Delta string `json:"delta"`
        Usage *struct {
            In  int64 `json:"in"`
            Out int64 `json:"out"`
        } `json:"usage"`
    }

    if err := json.Unmarshal(ev.Data, &chunk); err != nil {
        return nil, fmt.Errorf("decoding %q: %w", ev.Data, err)
    }

    var parts []ai.Part
    if chunk.Delta != "" {
        parts = append(parts, ai.Text("m1", chunk.Delta))
    }
    if chunk.Usage != nil {
        parts = append(parts, ai.Meter(ai.Usage{
            InputTokens:  chunk.Usage.In,
            OutputTokens: chunk.Usage.Out,
        }))
    }

    return parts, nil
})

Returning zero parts is normal and correct: providers emit keep-alives, role announcements and empty deltas that carry nothing worth forwarding.

Typed Upstream Failures

ai.Classify turns an upstream exchange into an *ai.UpstreamError, or nil when nothing went wrong. It takes the response and not only the error, and that signature is the whole point: a well-behaved Go HTTP client returns a non-2xx response with a nil error, so a Classify(err) form would have to recover the status code from a string and would recreate exactly the type erasure it exists to delete. The alternative is what AI gateways actually end up with, which is a regular expression over err.Error().

The classification answers the only three questions a caller has: retry, try a different credential, or give up.

ClassMeaningRetryable
ai.ClassNoneThe response was finen/a
ai.ClassFatalThe request is wrong and would be just as wrong on another credentialNo
ai.ClassTransientA 5xx, a reset, a dial error, or a timeoutYes
ai.ClassRateLimitedA 429Yes, after RetryAfter
ai.ClassExhaustedThis credential or account cannot serve the request at allYes, on another credential
ai.ClassCanceledThe caller went away, and only that: context.CanceledNo

A timeout is a transient failure, not a cancellation. Only context.Canceled is ClassCanceled; context.DeadlineExceeded and any net.Error whose Timeout() is true are transient, retryable, and reported as 504, with ue.Timeout() to tell them apart. The distinction matters because net/http’s own timeout errors, from http.Client.Timeout and Transport.ResponseHeaderTimeout, satisfy errors.Is(err, context.DeadlineExceeded): read as cancellations, a stalled provider became an empty 200 that nothing retried and nothing reported. The one exception is Relay under DisconnectCancel: when the turn’s own context ends, whatever ended it, the result is ClassCanceled with the cause kept, because nobody is waiting for a retry.

Two of those rows are opinions, and both are load-bearing. Rate limiting is its own class rather than a kind of exhaustion because it is a routing signal and not a health signal: a credential pool that counts a 429 as a fault quarantines a perfectly healthy key for being popular. And 401 and 403 map to exhaustion rather than fatal, because in a gateway they almost always mean this credential is finished rather than this request is malformed. Treating them as fatal is how one rotated key takes a whole service down instead of failing over.

The error carries what a support conversation needs: Status, Class, the provider’s own Message and Code, the RequestID it reported in the body or a header, the RetryAfter it asked for, and up to 64 KB of the response Body, because the body is where providers put the reason. ai.AsUpstream(err) extracts it from an error chain and Unwrap exposes the transport error, so errors.Is against context.Canceled keeps working.

HTTPStatus() is the status code to give your own caller, and it is not the upstream’s. A 401 from a provider means the gateway’s credential is finished, which is a 502 to the caller: telling them they are unauthorised sends them off to check a key they do not have. The one code that passes through is 429, because rate limiting is the caller’s problem too and the delay is worth forwarding. For anything more than the number, the next section is the fuller path: it produces the whole error envelope, logged and redacted, and it works after the response has already begun.

Errors After the First Byte

A failure before the first byte is an ordinary HTTP error, and Chapter 9 covers it. A failure after the first byte is the case a streaming API has to answer for, and it needs a different mechanism, because the status code is spent and the only channel left is the one the client is reading as content.

The temptation is to write the error’s own text into a frame and move on. That loses twice. Nothing is logged or collected, so the failure is invisible to whatever sink the rest of the application reports to, and whatever the upstream said goes straight to the client, naming a vendor, a model or a host that the caller has no business learning.

Close therefore renders its error event through the ErrorFrame option, whose default runs the error through errors.Report: the route’s mappings apply, the logger and the collector fire, an id is generated, and an unmapped or private error is redacted to a generic message. The frame carries the same rest/errors envelope an ordinary failure would have produced. A turn opened with ai.Open installs an AI-aware version of that renderer, which adds one thing: a classified upstream failure keeps its canonical code instead of collapsing into a generic internal error.

ai.ClassCanonical codeStatus
ClassRateLimitederrors.ResourceExhausted429
ClassExhaustederrors.Unavailable503
ClassFatalerrors.InvalidArgument, or errors.TooLarge for a 413400, 413
ClassTransient, timed out (ue.Timeout())errors.DeadlineExceeded504
ClassTransient, anything elseerrors.BadGateway502
ClassCancelednone: nobody is listeningnone

ue.ErrorCode() returns that code and ue.Report(ctx) runs the pipeline under it, returning the client-safe *errors.Error or nil when there is nothing to report. The client is told what the failure means and never what the provider said: a rate limit arrives as RESOURCE_EXHAUSTED with “the service is rate limited, try again shortly”, while the provider’s own message, code and request id go to the logger and the collector where they are useful. The error is wrapped as private on the way in, so the pipeline would redact it even if that wording were removed.

Because Report writes nothing, the same call serves both sides of the committed line. That is what lets a gateway hand its caller one envelope shape whether the upstream failed on the first attempt or halfway through the answer, which is the version the handler below uses.

Two options adjust the result. Options.Redact rewrites the client-facing message and detail last, after the pipeline has already made them safe, for the case it cannot cover on its own: an error the application deliberately mapped and described, whose description still names something internal. A strings.Replacer is the natural implementation and is safe to share across requests.

Go
o.Redact = strings.NewReplacer(
    "gpt-4o-mini", "the model",
    "api.openai.com", "the provider",
).Replace

And OnPart sees the terminal error too, as a KindError part, so the failure a client is told about passes the same gate everything else does. Returning ai.ErrDropPart there writes no error frame at all and the stream still gets its terminator, which is the shape for a client that should learn only that the answer ended.

A Gateway with Failover

Put those pieces together and a gateway is a loop over a chain of backends with one guard in it:

Go
// relayWithFailover walks the chain until one upstream serves the request.
func (g *gateway) relayWithFailover(ctx iris.Context, res *ai.Response) error {
    var lastErr error

    for _, b := range g.chain {
        // Once a delta has reached the client the status code is spent and
        // the answer has begun. Restarting now would splice two different
        // answers into one response, so this is where failover stops.
        if res.Committed() {
            return lastErr
        }

        err := g.relayOnce(ctx, res, b)
        if err == nil {
            return nil
        }
        lastErr = err

        ue, ok := ai.AsUpstream(err)
        if !ok {
            return err // our own bug: do not paper over it.
        }

        switch ue.Class {
        case ai.ClassCanceled:
            // Nobody is waiting for the answer any more.
            return err
        case ai.ClassFatal:
            // The request is wrong; it would be just as wrong on the next one.
            return err
        }

        // Transient, rate limited or exhausted: try the next backend.
    }

    return lastErr
}

Committed() is the guard that makes the difference between a gateway and a bug generator. Retrying is safe exactly until the first byte reaches the client, and after that a second attempt splices two different answers into one response, which reads as a model losing its mind rather than as an infrastructure failure.

The handler around it has to spend the status code when there is still one to spend, which is the branch a gateway forgets. The symptom is a 200 with an empty body:

Go
res, err := ai.Open(ctx, o)
if errors.HandleError(ctx, err) {
    return
}

err = res.Close(g.relayWithFailover(ctx, res))
if err == nil || res.Committed() {
    // Either it worked, or the answer had already begun and Close
    // reported the failure in-band. Both are finished responses.
    return
}

// Nothing reached the client, so the status code is still ours to spend.
// Report is the same call the streaming path makes, so the caller gets one
// envelope either way.
if ue, ok := ai.AsUpstream(err); ok {
    reported := ue.Report(ctx)
    if reported == nil {
        return // cancelled: nobody is listening.
    }

    if ue.RetryAfter > 0 {
        ctx.SetHeader("Retry-After", strconv.Itoa(int(ue.RetryAfter.Seconds())))
    }

    ctx.StopWithJSON(reported.ErrorCode.Status, reported)
    return
}

errors.Internal.Err(ctx, err)

One detail in the client that sits behind such a gateway is worth stating, because it is invisible until it truncates an answer. http.Client.Timeout covers the whole lifecycle including reading the body, so any non-zero value cuts a long generation off mid-sentence. Leave it at zero and let cancellation ride the request context, where it belongs. The full program, with two fake providers so the failover path is visible rather than theoretical, is _examples/16-advanced/ai-gateway.

What Breaks in Production

Five failures account for most of what goes wrong with a streaming endpoint, and none of them show up in a unit test.

Timeout.HandlerTimeout makes streaming impossible. It wraps the router in http.TimeoutHandler, whose response writer implements neither http.Flusher nor http.Hijacker, so every write buffers and the client gets a 503 page. sse.Open and ai.Open report sse.ErrNotStreamable before writing a byte, and an application that sets it logs a warning at startup. Bound slow handlers individually instead.

Server.WriteTimeout is absolute, not idle. It is a deadline on the whole response, not on one write, so a two-minute generation dies at the limit however busy the connection was. The first Send clears it for that response only, which is why streaming through the sse package survives a server configuration that would otherwise have to disable the timeout globally.

A buffering middleware de-streams everything. middleware/compress writes into a compressor and middleware/recorder writes into a bytes.Buffer, which accesslog installs whenever it reads the response body, and which iris.NewBuilder().LogRequests(true) therefore turns on. The first Send removes both for that response, so the combination works now; before it did, an access log was enough to turn every event stream into one lump on return.

A disconnected client is invisible for fifteen minutes. Only a real FIN or RST, or a failing write, cancels a request context. A closed lid or a dropped link produces none of those, and TCP retransmits for roughly 924 seconds on Linux before giving up, all of it billed upstream. The heartbeat is what turns that into a failed write within seconds, and OnDisconnect decides what happens next.

Shutdown does not cancel a request context. http.Server.Shutdown waits for handlers to return, and a handler blocked in a stream loop has no way to learn the process is stopping. Select on ctx.ShuttingDown() alongside the stream’s own context, as the loop in Chapter 6 does, or graceful shutdown waits for its full timeout on every open stream.

One more is about the client rather than the server. EventSource cannot send a request body, which is why every LLM client is built on fetch instead, and why Last-Event-ID arrives as a query parameter as often as a header. sse.Stream.LastEventID reads both.

Summary

  • An AI backend streams because a model’s answer takes as long as the answer is long; the number a reader feels is the time to the first fragment, which ai.Result.TTFP measures.
  • ai.Open serves the streaming and the non-streaming shape from one handler. Options.Stream is a *bool so that nil can mean “negotiate on Accept”, and nothing between Open and Close changes between shapes.
  • Seven Part kinds cover text, reasoning, tool calls, tool results, usage, errors and a KindData passthrough. Part’s fields are unexported, so an invalid part cannot be built.
  • ai.SSEJSON is the default encoder, ai.NDJSON suits a server-to-server consumer and ai.PlainText suits curl. Vendor dialects belong behind the Encoder interface, not inside the package.
  • ai.TagSplit separates reasoning fenced in a tag such as <think> across chunk boundaries, and Flush releases a tag that never completed rather than truncating the answer.
  • OnPart is block-only policy; OnFinish runs exactly once under context.WithoutCancel, on success, failure and disconnect alike, and is where persistence, billing and metrics belong.
  • ai.Relay forwards an upstream stream through a Decoder you write. ai.Classify takes the response as well as the error and returns a typed *ai.UpstreamError whose Class says whether to retry, switch credential or stop, and whose HTTPStatus is what to tell your caller.
  • Committed() is where failover has to stop, because after the first delta a retry splices two answers into one response.
  • A failure after the first byte goes out as an error frame rendered through the rest/errors pipeline, so it is mapped, logged, collected and redacted. A classified upstream failure keeps its canonical code: ClassRateLimited reaches the client as RESOURCE_EXHAUSTED, not as a generic internal error. Options.Redact rewrites the client-facing text last, and OnPart can drop the error frame entirely.

Further Reading

Twenty-five chapters, about 85,000 words. Try BindJSON, graceful shutdown or error map.