Skip to navigation

LLM Responses and Streams

View as Markdown

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.

Protocol field and typeMeaningAnthropic MessagesOpenAI ResponsesChat Completions
AggLlmResponse.id: Option<String>Provider response identifier, if available.ididid
AggLlmResponse.model: Option<String>Provider-reported model name.modelmodelmodel
AggLlmResponse.outputs: Vec<ResponseOutput>Completed output items.Assistant content blocksItems in outputchoices[].message
ResponseOutput.content: Vec<ContentBlock>Ordered text, reasoning, tool, and other output content.text, thinking, tool_use, and other blocksMessage content, reasoning, function calls, and other itemsMessage content, tool_calls, and provider-specific reasoning fields
ResponseOutput.stop_reason: Option<StopReason>Why this output stopped.stop_reasonResponse status and incomplete_detailschoices[].finish_reason
ResponseOutput.url_citations: Vec<UrlCitation>Cited URLs with text offsets.Not normalized by the current codecoutput_text.annotationsMessage annotations when supplied
AggLlmResponse.usage: UsageNormalized usage counts and any provider-reported cost.usageusageusage
AggLlmResponse.extensions: ProviderExtensionsProvider-only response fields.Source fields retained by the codecSource fields retained by the codecSource fields retained by the codec
AggLlmResponse.preservation: PreservationMetadataOriginal JSON for same-format buffered replay.Original parsed bodyOriginal parsed bodyOriginal parsed body

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.

Protocol field and typeMeaningAnthropic MessagesOpenAI ResponsesChat Completions
Usage.input_tokens: Option<u64>Non-cached input tokens.input_tokensinput_tokens minus reported cache detailprompt_tokens minus reported cache detail
InputCacheUsage.cached_input_tokens: Option<u64>Input read from cache.cache_read_input_tokensInput token details, when reportedPrompt token details, when reported
InputCacheUsage.cache_creation_input_tokens: Option<u64>Input written to cache.cache_creation_input_tokensInput token details, when reportedPrompt token details, when reported
Usage.output_tokens: Option<u64>Output tokens, including reasoning when counted by the provider.output_tokensoutput_tokenscompletion_tokens
Usage.reasoning_tokens: Option<u64>Reasoning output reported separately.Provider token details, when reportedoutput_tokens_details.reasoning_tokensCompletion token details, when reported
Usage.total_tokens: Option<u64>Provider-reported or codec-computed total.Computed when neededtotal_tokens or computed totaltotal_tokens or computed total
Usage.provider_cost: Option<f64>Provider-reported monetary charge in USD.Only when reportedOnly when reportedOnly when reported

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.

Protocol variantMeaningAnthropic MessagesOpenAI ResponsesChat Completions
LlmResponseChunk::MessageStartEstablish or update response identity.message_startResponse creation/start eventsInitial model and response fields
LlmResponseChunk::TextDeltaAppend text at an output index.Text content_block_deltaOutput text delta eventschoices[].delta.content
LlmResponseChunk::ReasoningDeltaAppend reasoning text.Thinking deltasReasoning summary deltasProvider-specific reasoning deltas
LlmResponseChunk::ReasoningDetailsDeltaRetain structured or encrypted reasoning detail.Reasoning signatures and related detailEncrypted reasoning itemsProvider-specific structured reasoning fields
LlmResponseChunk::ToolCallDeltaBuild a tool call’s ID, name, and argument string.Tool start and input JSON deltasFunction-call item and argument eventsTool-call deltas
LlmResponseChunk::UsageUpdate available token counts.Message usage and deltasUsage on response eventsUsage chunks
LlmResponseChunk::MessageStopEnd the message.Message stop eventsResponse completion eventsFinish reasons and terminal framing
LlmResponseChunk::DecodeError / LlmResponseChunk::StreamErrorReport decoding or in-band upstream failure.Codec/upstream error eventsCodec/upstream error eventsCodec/upstream error events

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.