ChatClient api + model openai stream response not working as expected: client receives full complete response instead of chunk by chunk
Bug description Streaming response not working as expected. Client receives only full complete response (group of chunks) instead of chunks when they are ready one by one.
Environment Spring AI v2.0.0-M6
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
spring:
ai:
openai:
base-url: https://my-company-proxy.com
api-key: ${API_KEY}
microsoft-foundry: true
chat:
model: anthropic.claude-sonnet-4-6
temperature: 0.5
@Configuration
public class ChatConfig {
@Bean
ChatClient chatClient(
ChatClient.Builder chatClientBuilder
) {
return chatClientBuilder.build();
}
}
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/chat")
public class ChatController {
private final ChatService chatService;
@PostMapping(produces = MediaType.APPLICATION_NDJSON_VALUE)
public Flux<ChatResponse> chat() {
return chatService.chat();
}
}
@Service
@RequiredArgsConstructor
public class ChatService {
private final ChatClient chatClient;
public Flux<ChatResponse> chat() {
return chatClient.prompt()
.user("write 30 lines of jokes")
.stream()
.chatResponse();
}
}
it worked correctly on 1.1.0-M3 with
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-azure-openai</artifactId>
</dependency>
spring:
ai:
azure.openai:
endpoint: https://my-company-proxy.com
api-key: ${API_KEY}
chat:
options:
temperature: 0.5
deployment-name: anthropic.claude-sonnet-4-6
Expected behavior Client receives ChatResponse chunks when they are ready chunk by chunk
ai analysis
Spring AI 2.0.0-M6 buffers OpenAI streaming responses until completion
Bug description
When using ChatClient.prompt().stream().chatResponse() with the OpenAI starter in 2.0.0-M6, the HTTP client does not receive chunks as they are produced by the model. Instead, chunks are buffered and delivered together only after the upstream stream completes.
This looks like a regression compared to the Azure OpenAI implementation used in 1.1.0-M3, where streamed responses were forwarded incrementally.
Environment
- Spring AI
2.0.0-M6 spring-ai-starter-model-openaispring-boot-starter-webflux- Microsoft Foundry / OpenAI-compatible proxy setup
Example configuration:
spring:
ai:
openai:
base-url: https://my-company-proxy.com
api-key: ${API_KEY}
microsoft-foundry: true
chat:
model: anthropic.claude-sonnet-4-6
temperature: 0.5
Example usage:
@RestController
@RequestMapping("/api/chat")
class ChatController {
private final ChatClient chatClient;
ChatController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@PostMapping(produces = MediaType.APPLICATION_NDJSON_VALUE)
Flux<ChatResponse> chat() {
return this.chatClient.prompt()
.user("write 30 lines of jokes")
.stream()
.chatResponse();
}
}
Actual behavior
The client receives a group of ChatResponse items only after the model finishes generating the whole response. Streaming is effectively buffered.
Expected behavior
The client should receive ChatResponse chunks incrementally as soon as they are available from the upstream model stream.
Root cause analysis
The regression appears to be in models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatModel.java in 2.0.0-M6.
The current implementation builds a live Flux<ChatResponse> from createStreaming(request), but then materializes the whole stream:
Flux<ChatResponse> flux = chatResponses
.contextWrite(ctx -> ctx.put(ObservationThreadLocalAccessor.KEY, observation));
return flux.collectList().flatMapMany(list -> {
if (list.isEmpty()) {
return Flux.empty();
}
boolean hasToolCalls = list.stream()
.map(this::safeAssistantMessage)
.filter(Objects::nonNull)
.anyMatch(am -> !CollectionUtils.isEmpty(am.getToolCalls()));
if (!hasToolCalls) {
return Flux.fromIterable(list);
}
...
});
collectList() waits for upstream completion before emitting anything, so WebFlux cannot flush chunks to the client in real time. As a result, application/x-ndjson does not help because buffering already happened inside Spring AI.
Comparison with previous implementation
The older Azure implementation in spring-ai-azure-openai-1.1.0-M3 (org.springframework.ai.azure.openai.AzureOpenAiChatModel) does not collect the entire stream before returning it.
Its streaming flow is implemented roughly as:
- Enable streaming on
ChatCompletionsOptions - Consume
openAIAsyncClient.getChatCompletionsStream(...) - Detect tool/function-call chunks
- Use
windowUntil(...)to close logical streamed segments - Merge only each segment
- Map each segment to
ChatResponse - Use
buffer(2, 1)only to propagate the final usage chunk - Return the live stream via
new MessageAggregator().aggregate(...)
Relevant operators from the old implementation:
chatCompletionsStream
.windowUntil(...)
.flatMapSequential(...)
...
return chatResponseFlux.flatMapSequential(chatResponse -> {
...
Flux<ChatResponse> flux = Flux.just(chatResponse)
.doOnError(observation::error)
.doFinally(s -> observation.stop())
.contextWrite(ctx -> ctx.put(ObservationThreadLocalAccessor.KEY, observation));
return new MessageAggregator().aggregate(flux, observationContext::setResponse);
});
The old implementation preserved chunk-by-chunk delivery and only merged the minimum amount of data needed for tool-call handling.
Why this looks like a regression
1.1.0-M3Azure OpenAI streaming preserved incremental delivery2.0.0-M6OpenAI streaming introducescollectList().flatMapMany(...)- the new logic seems intended to reconstruct fragmented tool-call chunks, but it does so by buffering the full stream unconditionally
- non-tool-call responses are affected even though they do not require full-stream materialization
Suggested fix
Avoid unconditional collectList() in OpenAiChatModel.internalStream().
Possible fix direction:
- keep normal text streaming fully incremental
- only aggregate tool-call fragments when necessary
- use a windowed or incremental merging strategy similar to the previous Azure implementation instead of materializing the whole stream first
Impact
This breaks real-time streaming over WebFlux for OpenAI-compatible and Microsoft Foundry-backed configurations using ChatClient.stream().chatResponse(), even when the controller correctly returns Flux<ChatResponse> with MediaType.APPLICATION_NDJSON_VALUE.
Likely a duplicate of #5987.