
Streaming model replies in Go
Reading a reply that arrives as it is written (server-sent events) in Go, and rebuilding tool calls from fragments.
On the agent compass Stage 2 of 4 · Call the modelAn agent that waits for whole replies gives its user long stretches of nothing. The terminal sits blank for a few seconds, prints an entire turn, and goes blank again. From the outside a slow model, a hung connection, and a crashed program all look the same. With streaming, text appears while the model is producing it, and the agent loop gets a much earlier signal when a connection has died.
New to streams in Go? Streams in Go covers io.Reader, bufio.Scanner, and the server-sent events format first.
Here is how a stream looks on the wire, how to consume one in Go, and the details that catch out a stream reader written too quickly.
What streaming buys, measured
In one recorded experiment, each of four models answered one question ten times, half streamed and half not.
With the default model, anthropic/claude-haiku-5.5, streamed replies started showing text at a median of 1.6 seconds; the same reply without streaming appeared all at once after 2.7.
Total time barely moved: for three of the four models, streamed and unstreamed replies finished within half a second of each other.
What streaming improves, then, is what the user sees and how fast the program notices a failure; it doesn’t make the model finish any earlier.
Reasoning models complicate the picture.
z-ai/glm-5.3-flash delivered its first chunk in under a second but its first word of the actual answer only after a median of 12.2 seconds, since everything before that was reasoning.
If your display shows only the answer, the user stares at an empty screen for twelve seconds while data is flowing the entire time.
Server-sent events
Models produce output a token at a time, which lets a provider forward each piece the moment it exists.
You opt in with "stream": true in the request, and add "stream_options": {"include_usage": true} if you still want token counts at the end.
The reply is an HTTP 200 whose body keeps arriving, formatted as server-sent events (SSE), a plain-text format that lets a server push lines to a client over one open connection.
The format is line-based.
A line beginning data: holds the payload, an empty line separates one event from the next, and a line beginning with a colon is a comment to be ignored.
Every data: line here is one JSON chunk of the reply, and the final one is the literal data: [DONE].
OpenRouter sends comments like : OPENROUTER PROCESSING while a slow model warms up, so the connection never looks idle.
The opening of a recorded stream, one chunk per line:
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":"","role":"assistant","reasoning_details":[{"type":"reasoning.text","signature":"CAQShAYKEAgSGAI4AUIIdGhp...","format":"anthropic-claude-v1","index":0}]},"finish_reason":null,"native_finish_reason":null}]}
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":"The bug is in the","role":"assistant"},"finish_reason":null,"native_finish_reason":null}]}
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":" unit table: `'m'","role":"assistant"},"finish_reason":null,"native_finish_reason":null}]}
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":"` is","role":"assistant"},"finish_reason":null,"native_finish_reason":null}]}
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":" mapped to `time.","role":"assistant"},"finish_reason":null,"native_finish_reason":null}]}
data: {"id":"gen-1792090035-7FlDhTvRt5hCKR2sUR7K","object":"chat.completion.chunk","created":1792090035,"model":"anthropic/claude-haiku-5.5","provider":"Claude Platform on AWS","choices":[{"index":0,"delta":{"content":"Second`","role":"assistant"},"finish_reason":null,"native_finish_reason":null}]}
The pieces don’t respect word boundaries; one chunk ends with “mapped to time." and the next starts "Second”.
Where a complete response has a message, each chunk has a delta instead: only what was added to the message since the previous chunk.
Reading it with an iterator
A bufio.Scanner plus a handful of rules is enough to parse the format.
You use sseData like a slice: for data, err := range sseData(body) gives you one data: line per pass.
The helper hands back each payload through a range-over-func iterator, an iter.Seq2 of bytes and an error, so the code that decodes chunks is an ordinary for loop:
// sseData reads a server-sent event stream and yields the data of each
// "data:" line until "data: [DONE]". It treats each data line as a
// whole event, which is what OpenAI-compatible servers send. Comment
// lines, which start with a
// colon and keep a quiet connection open, and blank lines are skipped.
// A stream that ends without [DONE] yields io.ErrUnexpectedEOF.
func sseData(r io.Reader) iter.Seq2[[]byte, error] {
return func(yield func([]byte, error) bool) {
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 64<<10), maxBody)
for sc.Scan() {
data, ok := bytes.CutPrefix(sc.Bytes(), []byte("data:"))
if !ok {
continue // a comment, a blank line, or another field
}
data = bytes.TrimPrefix(data, []byte(" "))
if string(data) == "[DONE]" {
return
}
if !yield(data, nil) {
return
}
}
err := sc.Err()
if err == nil {
err = io.ErrUnexpectedEOF
}
yield(nil, err)
}
}
Two lines in this function each head off a real failure.
First, the scanner’s buffer is allowed to grow to 16 MB.
Left at its default, a bufio.Scanner refuses any line longer than 64 KB.
Chunks can be long: when a model puts an entire file into a tool call’s arguments, that can come through as a single line.
With the default buffer, the reader passes every test and every ordinary run until the first long tool call breaks it.
The companion code has a test that feeds it a 100 KB line.
Second, if the body ends before [DONE] shows up, the iterator yields io.ErrUnexpectedEOF, and the client decides what that means for the reply.
Three things that don’t fit the pattern
Most of a stream is just more text in each chunk. Three cases break that pattern:
- Usage comes last. One chunk carries the finish reason, the field that says why the model stopped; the usage comes in a chunk after it. Stop reading at the finish reason and you never find out what the call cost, so the client keeps going until
[DONE]. - Errors can arrive mid-stream. A provider that fails after it has started writing sends an error object as an ordinary chunk. The client treats it as a failure, never as a normal end to the reply.
- The connection can just end. If the body stops before any finish reason or
[DONE], the reply is incomplete and the client reports an error. If the finish reason already arrived, the reply itself is complete and accepted; the only thing missing is its usage.
Tool calls arrive in fragments
A tool call is spread over several chunks.
The first one for a call carries its index within the reply, its id, and the tool name, with the arguments still empty.
After that, each chunk for the call holds just the index and another slice of the argument text.
The reader therefore gathers calls by index:
// addCall takes the next piece of one tool call.
func (a *assembler) addCall(c CallDelta) error {
if c.Index < 0 || c.Index >= maxCalls {
return fmt.Errorf("%w: call index %d", ErrBadToolCall, c.Index)
}
for c.Index >= len(a.calls) {
a.calls = append(a.calls, ToolCall{})
a.args = append(a.args, nil)
}
call := &a.calls[c.Index]
if c.ID != "" && call.ID != "" && c.ID != call.ID {
return fmt.Errorf("%w: call %d changed its ID from %q to %q",
ErrBadToolCall, c.Index, call.ID, c.ID)
}
if c.ID != "" {
call.ID = c.ID
}
if c.Name != "" {
call.Name = c.Name
}
a.args[c.Index] = append(a.args[c.Index], c.Arguments...)
return nil
}
Indexes are checked before use: anything negative or 128 and above means the stream is broken, and the assembler rejects it rather than panicking on a bad index or growing a slice without bound. It also rejects a fragment whose ID disagrees with the one already recorded at that index. The argument fragments are appended as raw bytes, and nothing tries to read them yet.
That last choice is the one to copy.
Until the stream is over, the arguments are an unfinished string such as {"path": "duration.g, which isn’t JSON, and a harness that guessed how it ends could run a tool on a path nobody asked for.
Decoding waits until the whole reply has arrived and passed its checks.
A reply that the token limit truncated ends the run with an error; it never turns into a tool call with half its arguments.
Stopping a stream that goes quiet
A fixed deadline works for a whole-reply call, but a healthy stream can run longer than any deadline you would choose.
What a stream needs is a cap on how long it may go without sending anything, an idle timeout.
A time.AfterFunc timer restarts every time bytes come in (comment lines count), and if it ever fires it cancels the context of that stream, recording ErrStreamIdle as the reason.
It defaults to 30 seconds, which is deliberately loose.
Across the twenty timed streams, no gap between pieces after a reply began was longer than 0.64 seconds, but one run spent 10.9 seconds before sending its first piece.
A shorter timeout would trip on providers that hold a request in a queue before starting, and would discard replies that were on their way.
The reason travels with the context, so the resulting error matches context.Canceled and also ErrStreamIdle.
That lets a caller distinguish a stream that went idle, which is worth retrying, from a person pressing Ctrl-C.
Cancellation can hit at any moment without corrupting the conversation: a reply still in flight is thrown away, so the history never contains a partial reply or a tool call missing its result.
The run as an iterator
The loop reports text, tool calls and results as events you read with a for loop.
The rest of this section explains why the loop is built that way, and you can skip it on a first read.
The model’s stream is a detail of the client.
A program running an agent cares about a different set of happenings: text from the model, a finished tool call, a tool result, the end of a turn, the end of a run.
Those happenings are reported as events, and the agent loop itself becomes Events, a function that returns an iter.Seq of them.
Run and the new RunStream both consume Events, so there is still exactly one loop.
Making the run an iterator, rather than a goroutine sending events down a channel, keeps ownership simple.
A channel needs a goroutine to feed it, and then the code has to close the channel, make that goroutine exit if the reader walks away, and carry errors across.
Events runs in the caller’s goroutine, puts the error in the final event, and stops completely when the caller breaks out of its for loop.
TestBreakOutOfEvents in ch06/agent/stream_test.go checks exactly that: it breaks out at the first text event, then asserts that the model’s stream returned and that the context the model was given has been cancelled.
A goroutine is a function running at the same time as the rest of the program, and a channel passes values between goroutines; Goroutines with an owner covers both.
One interface or two?
Streaming adds a second interface, StreamModel, next to Model.
The reasoning for two is below, and you can skip it on a first read.
Here is the new interface:
// A StreamModel produces the next reply as a stream of pieces. The
// stream ends after the last Delta, or with an error.
type StreamModel interface {
Stream(ctx context.Context, req Request) iter.Seq2[Delta, error]
}
A single interface plus a type assertion for streaming support would be shorter, but it fails without telling you.
Wrap the client in a logger that only implements Model, and the Stream method disappears behind it; the loop switches back to whole replies and every test still passes.
Two interfaces put the choice in the type system.
An adapter wraps any plain Model as a StreamModel, which is how all the earlier tests keep running, unchanged, through the streaming loop.
A type assertion, such as m.(StreamModel), asks at run time whether a value also implements another interface; Go by Example and the Tour of Go cover the basics.
Run it
From the code directory of a clone of the companion repository:
$ go run ./ch06 -replay fix-again
$ go run ./ch06 -replay stream-error
The first command replays a saved run named fix-again: a stream recorded from openai/gpt-5.6-luna fixing the failing test in the duration package, the first practice project in the companion code.
Without a key, the replay hands over the whole recorded stream at once, so the finished turns appear together rather than text arriving word by word; seeing each line as the model produces it needs OPENROUTER_API_KEY and makes live calls.
The tools run for real either way, and the output starts like this:
No OPENROUTER_API_KEY: replaying a saved run. The tools run for real.
task: The tests in this project fail. Find out why and fix it.
turn 1
model asks: list_files {}
tool result: duration.go, duration_test.go
The second command replays a provider that fails mid-reply: the partial text is printed, is kept out of the conversation, and the error explains what happened.
It ends with error: run agent: generate: agent: bad reply: provider failed partway: server_error Provider disconnected.
func sseData(r io.Reader) iter.Seq2[[]byte, error]
sseData reads a server-sent event stream and yields the data of each "data:" line until "data: [DONE]".
sseData reads a server-sent event stream and yields the data of each "data:" line until "data: [DONE]". func sseData(r io.Reader) iter.Seq2[[]byte, error]. In ch06/openrouter/sse.go, line 19.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
type Reader interface {
Read(p []byte) (n int, err error)
}
Reader is the interface that wraps the basic Read method.
Reader is the interface that wraps the basic Read method. type Reader interface { Read(p []byte) (n int, err error) }. Documented at pkg.go.dev, io.Reader.
package iter ("iter")
Package iter provides basic definitions and operations related to iterators over sequences.
Package iter provides basic definitions and operations related to iterators over sequences. package iter ("iter"). Documented at pkg.go.dev, iter.
type Seq2[K, V any] func(yield func(K, V) bool)
Seq2 is an iterator over sequences of pairs of values, most commonly key-value pairs.
Seq2 is an iterator over sequences of pairs of values, most commonly key-value pairs. type Seq2[K, V any] func(yield func(K, V) bool). Documented at pkg.go.dev, iter.Seq2.
type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways.
byte is an alias for uint8 and is equivalent to uint8 in all ways. type byte = uint8. Documented at pkg.go.dev, builtin.byte.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
var yield func([]byte, error) bool
var yield func([]byte, error) bool. In ch06/openrouter/sse.go, line 20.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
var sc *bufio.Scanner
var sc *bufio.Scanner. In ch06/openrouter/sse.go, line 21.
package bufio ("bufio")
Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O. package bufio ("bufio"). Documented at pkg.go.dev, bufio.
func NewScanner(r io.Reader) *Scanner
NewScanner returns a new [Scanner] to read from r.
NewScanner returns a new [Scanner] to read from r. func NewScanner(r io.Reader) *Scanner. Documented at pkg.go.dev, bufio.NewScanner.
func (s *Scanner) Buffer(buf []byte, max int)
Buffer controls memory allocation by the Scanner.
Buffer controls memory allocation by the Scanner. func (s *Scanner) Buffer(buf []byte, max int). Documented at pkg.go.dev, bufio.Scanner.Buffer.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
const maxBody = 16 << 20
maxBody is the most of a response the client reads: far more than any reply, but a limit on a broken server.
maxBody is the most of a response the client reads: far more than any reply, but a limit on a broken server. const maxBody = 16 << 20. In ch06/openrouter/client.go, line 35.
func (s *Scanner) Scan() bool
Scan advances the [Scanner] to the next token, which will then be available through the [Scanner.Bytes] or [Scanner.Text] method.
Scan advances the [Scanner] to the next token, which will then be available through the [Scanner.Bytes] or [Scanner.Text] method. func (s *Scanner) Scan() bool. Documented at pkg.go.dev, bufio.Scanner.Scan.
package bytes ("bytes")
Package bytes implements functions for the manipulation of byte slices.
Package bytes implements functions for the manipulation of byte slices. package bytes ("bytes"). Documented at pkg.go.dev, bytes.
func CutPrefix(s, prefix []byte) (after []byte, found bool)
CutPrefix returns s without the provided leading prefix byte slice and reports whether it found the prefix.
CutPrefix returns s without the provided leading prefix byte slice and reports whether it found the prefix. func CutPrefix(s, prefix []byte) (after []byte, found bool). Documented at pkg.go.dev, bytes.CutPrefix.
func (s *Scanner) Bytes() []byte
Bytes returns the most recent token generated by a call to [Scanner.Scan].
Bytes returns the most recent token generated by a call to [Scanner.Scan]. func (s *Scanner) Bytes() []byte. Documented at pkg.go.dev, bufio.Scanner.Bytes.
func TrimPrefix(s, prefix []byte) []byte
TrimPrefix returns s without the provided leading prefix string.
TrimPrefix returns s without the provided leading prefix string. func TrimPrefix(s, prefix []byte) []byte. Documented at pkg.go.dev, bytes.TrimPrefix.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
func (s *Scanner) Err() error
Err returns the first non-EOF error that was encountered by the [Scanner].
Err returns the first non-EOF error that was encountered by the [Scanner]. func (s *Scanner) Err() error. Documented at pkg.go.dev, bufio.Scanner.Err.
var ErrUnexpectedEOF = errors.New("unexpected EOF")
ErrUnexpectedEOF means that EOF was encountered in the middle of reading a fixed-size block or data structure.
ErrUnexpectedEOF means that EOF was encountered in the middle of reading a fixed-size block or data structure. var ErrUnexpectedEOF = errors.New("unexpected EOF"). Documented at pkg.go.dev, io.ErrUnexpectedEOF.
type assembler struct {
text strings.Builder
calls []ToolCall
args [][]byte // each call's arguments so far
reasoning []jsontext.Value // reasoning records, in order
reply Reply
}
An assembler builds a Reply from the pieces of a stream.
An assembler builds a Reply from the pieces of a stream. type assembler struct { text strings.Builder calls []ToolCall args [][]byte // each call's arguments so far reasoning []jsontext.Value // reasoning records, in order reply Reply }. In ch06/agent/stream.go, line 95.
func (a *assembler) addCall(c CallDelta) error
addCall takes the next piece of one tool call.
addCall takes the next piece of one tool call. func (a *assembler) addCall(c CallDelta) error. In ch06/agent/stream.go, line 134.
type CallDelta struct {
Index int // which tool call in the reply this belongs to
ID string // set on the first piece only
Name string // set on the first piece only
Arguments string // the next fragment of the arguments
}
A CallDelta is a piece of one tool call.
A CallDelta is a piece of one tool call. type CallDelta struct { Index int // which tool call in the reply this belongs to ID string // set on the first piece only Name string // set on the first piece only Arguments string // the next fragment of the arguments }. In ch06/agent/stream.go, line 31.
field Index int
which tool call in the reply this belongs to
which tool call in the reply this belongs to field Index int. In ch06/agent/stream.go, line 32.
const maxCalls = 128
maxCalls bounds the tool calls in one reply, so a broken stream can't make the assembler allocate without limit.
maxCalls bounds the tool calls in one reply, so a broken stream can't make the assembler allocate without limit. const maxCalls = 128. In ch06/agent/stream.go, line 92.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
var ErrBadToolCall = fmt.Errorf("%w: bad tool call", ErrBadReply)
var ErrBadToolCall = fmt.Errorf("%w: bad tool call", ErrBadReply). In ch06/agent/errors.go, line 21.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
field calls []ToolCall
field calls []ToolCall. In ch06/agent/stream.go, line 97.
func append(slice []Type, elems ...Type) []Type
The append built-in function appends elements to the end of a slice.
The append built-in function appends elements to the end of a slice. func append(slice []Type, elems ...Type) []Type. Documented at pkg.go.dev, builtin.append.
type ToolCall struct {
ID string
Name string
Arguments jsontext.Value // JSON the model wrote; may be invalid
}
ToolCall is the model asking the harness to run a tool.
ToolCall is the model asking the harness to run a tool. type ToolCall struct { ID string Name string Arguments jsontext.Value // JSON the model wrote; may be invalid }. In ch06/agent/types.go, line 57.
field args [][]byte
each call's arguments so far
each call's arguments so far field args [][]byte. In ch06/agent/stream.go, line 98.
field ID string
set on the first piece only
set on the first piece only field ID string. In ch06/agent/stream.go, line 33.
field Name string
set on the first piece only
set on the first piece only field Name string. In ch06/agent/stream.go, line 34.
field Arguments string
the next fragment of the arguments
the next fragment of the arguments field Arguments string. In ch06/agent/stream.go, line 35.
type StreamModel interface {
Stream(ctx context.Context, req Request) iter.Seq2[Delta, error]
}
A StreamModel produces the next reply as a stream of pieces.
A StreamModel produces the next reply as a stream of pieces. type StreamModel interface { Stream(ctx context.Context, req Request) iter.Seq2[Delta, error] }. In ch06/agent/stream.go, line 44.
func (StreamModel) Stream(ctx context.Context, req Request) iter.Seq2[Delta, error]
func (StreamModel) Stream(ctx context.Context, req Request) iter.Seq2[Delta, error]. In ch06/agent/stream.go, line 45.
var ctx context.Context
var ctx context.Context. In ch06/agent/stream.go, line 45.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
type Request struct {
Messages []Message
Tools []ToolDef
MaxTokens int // longest reply; 0 means the provider's default
}
Request is what the harness sends the model on each turn.
Request is what the harness sends the model on each turn. type Request struct { Messages []Message Tools []ToolDef MaxTokens int // longest reply; 0 means the provider's default }. In ch06/agent/types.go, line 24.
package iter ("iter")
Package iter provides basic definitions and operations related to iterators over sequences.
Package iter provides basic definitions and operations related to iterators over sequences. package iter ("iter"). Documented at pkg.go.dev, iter.
type Delta struct {
Text string // a piece of the reply's text
Call *CallDelta // a piece of one tool call
FinishReason string // why the reply ended, when it has
Usage *Usage // what the call consumed, at the end
// ReasoningDetails holds reasoning records, a JSON array, which the
// assembler joins into the reply's ReasoningDetails.
ReasoningDetails jsontext.Value
}
A Delta is one piece of a streamed reply.
A Delta is one piece of a streamed reply. type Delta struct { Text string // a piece of the reply's text Call *CallDelta // a piece of one tool call FinishReason string // why the reply ended, when it has Usage *Usage // what the call consumed, at the end // ReasoningDetails holds reasoning records, a JSON array, which the // assembler joins into the reply's ReasoningDetails. ReasoningDetails jsontext.Value }. In ch06/agent/stream.go, line 17.
type Scanner struct {
r io.Reader // The reader provided by the client.
split SplitFunc // The function to split the tokens.
maxTokenSize int // Maximum size of a token; modified by tests.
token []byte // Last token returned by split.
buf []byte // Buffer used as argument to split.
start int // First non-processed byte in buf.
end int // End of data in buf.
err error // Sticky error.
empties int // Count of successive empty tokens.
// ...
}
Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text.
Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text. type Scanner struct { r io.Reader // The reader provided by the client. split SplitFunc // The function to split the tokens. maxTokenSize int // Maximum size of a token; modified by tests. token []byte // Last token returned by split. buf []byte // Buffer used as argument to split. start int // First non-processed byte in buf. end int // End of data in buf. err error // Sticky error. empties int // Count of successive empty tokens. // ... }. Documented at pkg.go.dev, bufio.Scanner.
var Canceled = errors.New("context canceled")
Canceled is the error returned by [Context.Err] when the context is canceled for some reason other than its deadline passing.
Canceled is the error returned by [Context.Err] when the context is canceled for some reason other than its deadline passing. var Canceled = errors.New("context canceled"). Documented at pkg.go.dev, context.Canceled.
type Seq[V any] func(yield func(V) bool)
Seq is an iterator over sequences of individual values.
Seq is an iterator over sequences of individual values. type Seq[V any] func(yield func(V) bool). Documented at pkg.go.dev, iter.Seq.

