collectHandler

inline suspend fun <T : AIChunk> Flow<T>.collectHandler(block: CollectHandler<T>.() -> Unit)

Collects a Flow of ChatChunk using a handler DSL.

Parameters

block

DSL builder for registering callbacks.

Samples

// Create a list for full model output.
val modelOutput = mutableListOf<String>()

// Collect and handle flow events.
chunksFlow.collectHandler {
    onChunk { chunk ->
        val firstChoice = chunk.choices.first()

        when (val content = firstChoice.content) {
            is Content.Reasoning -> println("Reasoning: ${content.value}")
            is Content.Text -> {
                modelOutput.add(content.text)
                println(content.text)
            }
            is Content.ToolCallDelta -> println("ToolCall: ${content.name} with args: ${content.argumentsChunk}")
        }
    }
    onError { error ->
        // Error handling.
        println("Error in ${error::class.simpleName}: ${error.message}")
    }
    onCompleted {
        // Print full output.
        println("Completed! Full output:\n${modelOutput.joinToString("")}")
    }
}
// Collecting all chunks using Collect Handler.
chunks.collectHandler {
    // onChunk is called for each chunk.
    onChunk { chunk ->
        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")
        }
    }
    // onError is called if an error occurred during collect.
    onError { throwable ->
        println("Error on collecting chunk: ${throwable.message}")
    }
    // onComplete is called when collect is complete.
    onCompleted {
        println("Collect ended!")
    }
}