spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

ChatClient api + model openai stream response not working as expected: client receives full complete response instead of chunk by chunk

Open ilyakastsenevich opened this issue 6 months ago • 1 comments

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-openai
  • spring-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:

  1. Enable streaming on ChatCompletionsOptions
  2. Consume openAIAsyncClient.getChatCompletionsStream(...)
  3. Detect tool/function-call chunks
  4. Use windowUntil(...) to close logical streamed segments
  5. Merge only each segment
  6. Map each segment to ChatResponse
  7. Use buffer(2, 1) only to propagate the final usage chunk
  8. 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-M3 Azure OpenAI streaming preserved incremental delivery
  • 2.0.0-M6 OpenAI streaming introduces collectList().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.

ilyakastsenevich avatar May 27 '26 09:05 ilyakastsenevich

Likely a duplicate of #5987.

sdeleuze avatar May 27 '26 13:05 sdeleuze