Skip to main content

Stream Transport Helpers

The Go AI SDK provides transport-oriented helpers for converting stream results into HTTP-friendly payloads and reading them back.

CreateTextStreamResponse​

func CreateTextStreamResponse(ctx context.Context, result *ai.StreamTextResult) (*http.Response, error)

Returns an *http.Response with a plain text body (text/plain; charset=utf-8) built from text chunks.

PipeTextStreamToResponse​

func PipeTextStreamToResponse(ctx context.Context, result *ai.StreamTextResult, w io.Writer) error

Writes text chunks to w as plain UTF-8 text. On an http.ResponseWriter it first sets Content-Type: text/plain; charset=utf-8 and writes status 200. PipeTextStreamToResponseWithInit(ctx, result, w, init) takes a *ai.TextStreamResponseInit to change the status or add headers. Mirrors TS pipeTextStreamToResponse.

CreateUIMessageStream​

func CreateUIMessageStream(ctx context.Context, result *ai.StreamTextResult, opts ...ai.UIMessageStreamResultOptions) (<-chan ai.UIMessageChunk, <-chan error)

Converts stream chunks to UI message chunks.

CreateUIMessageStreamResponse​

func CreateUIMessageStreamResponse(ctx context.Context, result *ai.StreamTextResult, opts ...ai.UIMessageStreamResultOptions) (*http.Response, error)

Returns an *http.Response with Server-Sent Events (text/event-stream) UI message chunks.

PipeUIMessageStreamToResponse​

func PipeUIMessageStreamToResponse(ctx context.Context, result *ai.StreamTextResult, w io.Writer, opts ...ai.UIMessageStreamResultOptions) error

Writes UI message chunks as Server-Sent Events. On an http.ResponseWriter it first sets the UI message stream headers (see UIMessageStreamHeaders) and writes status 200; PipeUIMessageStreamToResponseWithInit takes an init with a different status or extra headers. Other writers get only the body. Mirrors TS pipeUIMessageStreamToResponse.

PipeUIMessageChunksToResponse​

func PipeUIMessageChunksToResponse(chunks <-chan ai.UIMessageChunk, w io.Writer, init *ai.UIMessageStreamResponseInit) error

Writes any UI message chunk stream to w as Server-Sent Events, ending with data: [DONE]. Use it for a stream that isn't a single StreamTextResult, such as one built with CreateUIMessageStreamWithOptions that writes custom data parts and merges an agent stream. Mirrors TS pipeUIMessageStreamToResponse({ response, stream }). On an http.ResponseWriter it first sets the UI message stream headers (overridden by init.Headers) and writes the status (200 unless init.Status is set). init may be nil. When writing fails it returns without draining chunks, so create the stream with a context you cancel, such as the request's.

chunks, _ := ai.CreateUIMessageStreamWithOptions(r.Context(), ai.UIMessageStreamOptions{
Execute: func(writer ai.UIMessageStreamWriter) {
writer.Write(ai.UIMessageChunk{"type": "data-status", "id": "status", "data": map[string]any{"step": "searching"}})
result, err := ai.StreamText(r.Context(), ai.StreamTextOptions{Model: model, Prompt: "Hello"})
if err != nil {
writer.Write(ai.UIMessageChunk{"type": "error", "errorText": err.Error()})
return
}
uiChunks, _ := ai.CreateUIMessageStream(r.Context(), result)
writer.Merge(uiChunks)
},
})
if err := ai.PipeUIMessageChunksToResponse(chunks, w, nil); err != nil {
log.Printf("stream: %v", err)
}

CreateUIMessageChunksResponse​

func CreateUIMessageChunksResponse(chunks <-chan ai.UIMessageChunk, init *ai.UIMessageStreamResponseInit) (*http.Response, error)

Returns an *http.Response that streams any UI message chunk stream, with the same status and headers as CreateUIMessageStreamResponse. Mirrors TS createUIMessageStreamResponse({ stream }).

UIMessageStreamHeaders​

func UIMessageStreamHeaders() http.Header

Returns the headers a UI message stream response carries: Content-Type: text/event-stream, Cache-Control: no-cache, Connection: keep-alive, X-Vercel-AI-UI-Message-Stream: v1 and X-Accel-Buffering: no. The Pipe* helpers set them on an http.ResponseWriter for you; use this when you write the response another way. Mirrors TS UI_MESSAGE_STREAM_HEADERS.

Keep-alive​

CreateUIMessageStreamResponseWithInit and PipeUIMessageStreamToResponseWithInit accept a *ai.UIMessageStreamResponseInit with a KeepAliveMs *time.Duration field. When set to a positive duration, the pipeline writes an opening : stream-open\n\n SSE comment immediately — so a reverse proxy sees the response start right away instead of buffering an empty connection — and then a : keep-alive\n\n comment whenever that duration elapses with no other write, resetting on every real chunk:

keepAlive := 15 * time.Second
err := ai.PipeUIMessageStreamToResponseWithInit(ctx, result, w, &ai.UIMessageStreamResponseInit{
KeepAliveMs: &keepAlive,
})

ReadUIMessageStream and ReadUIMessages already skip SSE comment lines (any line starting with :), so a client reading a keep-alive-enabled stream needs no changes.

ReadUIMessageStream​

func ReadUIMessageStream(r io.Reader) ([]ai.UIMessageChunk, error)

Reads Server-Sent Events UI chunk payloads from a reader.

ConsumeStream​

func ConsumeStream(ctx context.Context, stream provider.TextStream) error

Consumes a stream until completion or context cancellation.

CreateTextStreamResponseWithInit​

func CreateTextStreamResponseWithInit(ctx context.Context, result *ai.StreamTextResult, init *ai.TextStreamResponseInit) (*http.Response, error)

Like CreateTextStreamResponse, with a custom status, status text and headers from init.

FieldTypeDescription
Statusint
StatusTextstring
Headersmap[string]string

CreateTextStreamResponseFromStream​

func CreateTextStreamResponseFromStream(ctx context.Context, stream provider.TextStream, init *ai.TextStreamResponseInit) (*http.Response, error)

Builds the plain text response from a provider.TextStream instead of a StreamTextResult.

PipeTextStreamToWriter​

func PipeTextStreamToWriter(ctx context.Context, stream provider.TextStream, w io.Writer) error

Writes the text deltas of a provider stream to w as UTF-8. If a write fails or ctx ends first, it closes the stream before it returns, so a client that disconnects does not leave a provider connection open.

ToTextStream​

func ToTextStream(ctx context.Context, stream provider.TextStream) (<-chan string, <-chan error)

Returns the text deltas of a stream as a channel of strings, with a channel for the error.

CreateUIMessageStreamWithOptions​

func CreateUIMessageStreamWithOptions(ctx context.Context, options ai.UIMessageStreamOptions) (<-chan ai.UIMessageChunk, <-chan error)

Creates a UI message stream from an Execute function that writes chunks and merges other streams. Use it to add custom data parts or to combine several streams. The option fields are in UI message chunks.

ToUIMessageStream and ToUIMessageChunk​

func ToUIMessageStream(ctx context.Context, stream provider.TextStream, opts ...ai.UIMessageStreamResultOptions) (<-chan ai.UIMessageChunk, <-chan error)
func ToUIMessageChunk(part provider.StreamChunk, opts ai.UIMessageStreamResultOptions) (ai.UIMessageChunk, bool)

ToUIMessageStream converts a provider stream to UI message chunks. ToUIMessageChunk converts one chunk and returns false when the part has no UI chunk.

CreateUIMessageStreamResponseWithInit and PipeUIMessageStreamToResponseWithInit​

func CreateUIMessageStreamResponseWithInit(ctx context.Context, result *ai.StreamTextResult, init *ai.UIMessageStreamResponseInit, opts ...ai.UIMessageStreamResultOptions) (*http.Response, error)
func PipeUIMessageStreamToResponseWithInit(ctx context.Context, result *ai.StreamTextResult, w io.Writer, init *ai.UIMessageStreamResponseInit, opts ...ai.UIMessageStreamResultOptions) error

The WithInit forms take an *ai.UIMessageStreamResponseInit for the status, status text, headers, repeated headers, a stream consumer and keep-alive. The fields are in UI message chunks.

ReadUIMessages​

func ReadUIMessages(ctx context.Context, opts ai.ReadUIMessagesOptions) (<-chan ai.UIMessage, <-chan error)

Folds a chunk stream into progressively updated ai.UIMessage snapshots. See UI messages.

IsUIMessageStreamError​

func IsUIMessageStreamError(err error) bool

Reports whether err is an *ai.UIMessageStreamError, which the stream reports through OnError when a chunk refers to a part that does not exist.

SmoothStream​

func SmoothStream(opts ai.SmoothStreamOptions) (ai.StreamTransformFunc, error)

Returns a stream transform that re-chunks text deltas and delays them, so text appears at an even pace. Pass it as ExperimentalTransform in ai.StreamTextOptions.

FieldTypeDescription
DelayInMs*intDelayInMs is the delay between emitted chunks. nil means unset and defaults to 10ms (TS default); a non-nil pointer to 0 disables the delay entirely (TS delayInMs: null). This mirrors the *int "unset vs explicit zero" convention used elsewhere in this package (see GenerateTextOptions.MaxRetries), applied to TS's number | null.
Chunkinginterface{}Chunking controls how text is split for streaming. One of: - "word" (default): split on \S+\s+ (word boundaries). - "line": split on \n+. - a *regexp.Regexp: must not match an empty string. - a ChunkDetector function.

ElementStream and ElementStreamWithOutput​

func ElementStream[ELEMENT any](result *ai.StreamTextResult, opts ai.ElementStreamOptions[ELEMENT]) <-chan ai.ElementStreamResult[ELEMENT]
func ElementStreamWithOutput[ELEMENT any](result *ai.StreamTextResult, output ai.Output[[]ELEMENT, []ELEMENT]) <-chan ai.ElementStreamResult[ELEMENT]

Emits each element of a streamed JSON array as soon as it is complete. See Utilities for the option and result fields.

ChatTransport​

ai.ChatTransport is the client-side interface that sends a chat's message history and receives UI message chunks. workflow.WorkflowChatTransport and the LangSmith deployment transport implement it.

type ChatTransport interface {
SendMessages(ctx context.Context, req ChatTransportSendMessagesRequest) (<-chan UIMessageChunk, <-chan error)
ReconnectToStream(ctx context.Context, req ChatTransportReconnectToStreamRequest) (<-chan UIMessageChunk, <-chan error)
}

ReconnectToStream closes both channels without values when no stream is active.

FieldTypeDescription
ChatIDstringChatID identifies the conversation. Callers that run a single conversation per process (such as pkg/tui's AgentTUIRunner) typically generate this once per runner instance.
MessageIDstringMessageID is the id of the message being responded to, when known.
TriggerstringTrigger describes why SendMessages was called (for example "submit-message" or "regenerate-message"), matching the TypeScript ChatTransport's trigger field.
Messages[]types.MessageMessages is the full message history sent to the transport.
FieldTypeDescription
ChatIDstringChatID identifies the conversation whose in-progress stream should be resumed.