forEachChoice

inline suspend fun ChatChunk.forEachChoice(crossinline onChoice: suspend (choiceIndex: Int, choice: ChatChunkChoice) -> Unit)

Iterates over each choice in a ChatChunk.

Useful when dealing with multiple choices (e.g., from parallel tool calling) to avoid flattening issues.

Parameters

onChoice

Suspending function invoked for each choice with its index.

Samples

// forEachChoice iterates over each Choice, eliminating the effects of FlatMap
// (when more Choices were being generated due to parallel ToolCalling)
chunk.forEachChoice { choiceIndex, choice ->
    val output = when (val content = choice.content) {
        is Content.Reasoning -> "reasoning: ${content.value}"
        is Content.Text -> "output: ${content.text}"
        is Content.ToolCallDelta -> "tool call: ${content.name}"
    }

    println("Choice: $choiceIndex: $output")
}