Skip to content

fix: avoid IndexOutOfBoundsException when stream choice index is non-contiguous#6056

Open
suryateja-g13 wants to merge 1 commit into
spring-projects:mainfrom
suryateja-g13:gh-6023-stream-choice-index-oob
Open

fix: avoid IndexOutOfBoundsException when stream choice index is non-contiguous#6056
suryateja-g13 wants to merge 1 commit into
spring-projects:mainfrom
suryateja-g13:gh-6023-stream-choice-index-oob

Conversation

@suryateja-g13
Copy link
Copy Markdown
Contributor

@suryateja-g13 suryateja-g13 commented May 16, 2026

Summary

Fixes #6023

  • Replaced direct list access chunk.choices().get((int) choice.index()) with a Map<Long, ChatCompletionChunk.Choice> lookup keyed by API index
  • The map is built from chunk.choices() before the stream mapping loop in internalStream()
  • Added a unit test that exercises a chunk where the single choice carries index=1

Background

OpenAiChatModel.internalStream() used choice.index() as a list position to look up the raw chunk choice. This works when choices are zero-based and contiguous, but some OpenAI-compatible gateways (especially when stream_options.include_usage: true is set) emit chunks where a single choice carries a non-zero index. In that case, choices.get(1) on a one-element list throws IndexOutOfBoundsException.

Test plan

  • OpenAiChatModelTests#streamingDoesNotThrowWhenChoiceIndexIsNonZero — new test with mocked async client that emits a single chunk with choice.index()=1
  • All existing OpenAiChatModelTests pass

When processing streaming responses, each ChatCompletionChunk.Choice
carries an index field that represents its API-level choice index.
The previous code used this value directly as a position in the
choices list (chunk.choices().get((int) choice.index())), which
throws IndexOutOfBoundsException when the choice index is non-zero
but only one choice is present in the chunk.

This happens with OpenAI-compatible gateways that emit chunks where
a single choice carries index=1 (e.g. when include_usage is enabled).

Fix: build a Map<Long, ChatCompletionChunk.Choice> keyed by the API
index before the stream map, then look up by index instead of using
list position.

Closes spring-projects#6023

Signed-off-by: Gorre Surya <suryateja.g13@gmail.com>
@suryateja-g13 suryateja-g13 force-pushed the gh-6023-stream-choice-index-oob branch from 904f8af to 181a53f Compare May 17, 2026 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IndexOutOfBoundsException in OpenAiChatModel.internalStream when choice.index() != list position

1 participant