Response Streaming
note
This page describes response streaming with a low-level LLM API. See AI Services for a high-level LLM API.
LLMs generate text one token at a time, so many LLM providers offer a way to stream the response token-by-token instead of waiting for the entire text to be generated. This significantly improves the user experience, as the user does not need to wait an unknown amount of time and can start reading the response almost immediately.
For the ChatModel and LanguageModel interfaces, there are corresponding
StreamingChatModel and StreamingLanguageModel interfaces.
These have a similar API but can stream the responses.
They accept an implementation of the StreamingChatResponseHandler interface as an argument.
public interface StreamingChatResponseHandler {
default void onPartialResponse(String partialResponse) {}
default void onPartialResponse(PartialResponse partialResponse, PartialResponseContext context) {}
default void onPartialThinking(PartialThinking partialThinking) {}
default void onPartialThinking(PartialThinking partialThinking, PartialThinkingContext context) {}
default void onPartialToolCall(PartialToolCall partialToolCall) {}
default void onPartialToolCall(PartialToolCall partialToolCall, PartialToolCallContext context) {}
default void onCompleteToolCall(CompleteToolCall