LLM Responses and Streams
For the integration flow, read LLM-Related Protocols. For the input side, use LLM Requests.
Response forms
Response is the host-facing envelope. Its llm_response is either
LlmResponse::Agg, containing an AggLlmResponse, or LlmResponse::Stream,
containing a live LlmResponseStream. The stream has one consumer.
The envelope also carries Response.metadata and Response.upstream_headers.
Response.served_model() reads the Switchyard target recorded in metadata.
Response.selected_model() reads the provider model from a buffered result and
returns no model for a live stream, since inspecting its events would consume it.
Usage
Usage.input_tokens counts non-cached input. When an OpenAI-style provider
reports aggregate input counts, the codecs subtract reported cache-read and
cache-write counts. The cache details remain separate.
Missing counts remain unknown. Do not turn an absent count into a measured zero
when adapting a response. Usage.cache holds optional InputCacheUsage details.
Stream events
Each item of LlmResponseStream is a result containing LlmResponseStreamEvent.
An event contains zero or more neutral LlmResponseChunk values and may retain
one parsed provider event for same-format replay.
These are semantic mappings. One provider event can produce several chunks,
and some events have no normalized chunks. Raw replay can still retain those
events. Algorithms read neutral chunks through normalized().
Stream lifetime and preservation
Pass original LlmResponseStreamEvent values through when exact same-format
parsed-JSON replay matters. replace_normalized() returns an event with the new
chunks and clears its stale raw replay data.
LlmResponse::into_agg().await consumes the stream and folds its normalized
chunks into an AggLlmResponse. Stream item failures, decode failures, and
in-band upstream errors become errors. Aggregation does not preserve the original
provider event sequence, MCP activity, unknown blocks, or all response extensions.
The current accumulator also folds output indices into one assistant output.
Dropping a stream stops local consumption. It cannot guarantee that the provider stops generation or billing. See concurrency and cancellation for host-owned work, and Translation for decoding, encoding, and finishing provider streams.