chatStream

open override fun chatStream(request: ChatRequest): Flow<ChatChunk>

Sends a chat request to the OpenAI API and returns a streaming response.

Return

A Flow of ChatChunk objects, each containing a piece of the streaming response (text, reasoning, or tool call deltas).

Parameters

request

The fully configured ChatRequest containing messages, model parameters, and optional tools.

See also

Throws

if the API returns a provider-specific error.

if the HTTP request fails (timeout, network, JSON parsing, etc.).

Samples

// Send a stream ChatRequest to OpenAI.

// Create a chat using koryChat DSL function.
val chat: Chat = koryChat(model = modelName) {
    user("Ping!")
}

val request: ChatRequest = chat.asChatRequest(
    temperature = 1.4
)

// ChatStream uses a flow to stream chunks
client.chatStream(request).collect { chunk ->
    // Iterate all choices in chunk.
    for (choice in chunk.choices) {
        // Print information about content.
        when (val content = choice.content) { // Content is Content.StreamResponse.
            is Content.Reasoning -> println("Reasoning: ${content.value}")
            is Content.Text -> println("Text: ${content.text}")
            is Content.ToolCallDelta -> println("Tool call: ${content.name} with ${content.argumentsChunk ?: "no arguments"}")
        }
    }
}

open override fun chatStream(model: String, blocks: ChatBuilder.() -> Unit): Flow<ChatChunk>

Sends a chat request and returns a streaming response using DSL message builder.

Return

A Flow of ChatChunk objects.

Parameters

model

The name of the AI model to use.

blocks

DSL builder for constructing chat messages.

See also

Throws

if the API returns a provider-specific error.

if the HTTP request fails (timeout, network, JSON parsing, etc.).

Samples

// Send a stream request to OpenAI using chat() function with chat DSL.

client.chatStream(model = modelName) {
    user("Ping!")
}.collect { chunk ->
    // Iterate all choices in chunk.
    for (choice in chunk.choices) {
        // Print information about content.
        when (val content = choice.content) { // Content is Content.StreamResponse.
            is Content.Reasoning -> println("Reasoning: ${content.value}")
            is Content.Text -> println("Text: ${content.text}")
            is Content.ToolCallDelta -> println("Tool call: ${content.name} with ${content.argumentsChunk ?: "no arguments"}")
        }
    }
}

open override fun chatStream(block: ChatRequestBuilder.() -> Unit): Flow<ChatChunk>

Sends a chat request and returns a streaming response using full DSL configuration.

Return

A Flow of ChatChunk objects.

Parameters

block

DSL builder for configuring messages, temperature, maxTokens, tools, etc.

See also

Throws

if the API returns a provider-specific error.

if the HTTP request fails (timeout, network, JSON parsing, etc.).

Samples

examples.openai.client.sendToChatStreamWithRequestBuilder