---
source: tests/backends_kotlin_gen_bindings_test.rs
expression: "&client_file.content"
---
// Generated by alef. Do not edit by hand.
@file:Suppress(
    "ktlint:standard:trailing-comma-on-call-site",
    "ktlint:standard:trailing-comma-on-declaration-site",
    "ktlint:standard:spacing-between-declarations-with-comments",
    "ktlint:standard:spacing-between-declarations-with-annotations",
    "ktlint:standard:when-entry-bracing",
    "ktlint:standard:blank-line-between-when-conditions",
    "ktlint:standard:blank-line-before-declaration",
    "ktlint:standard:chain-method-continuation",
    "ktlint:standard:annotation",
    "ktlint:standard:max-line-length",
    "ktlint:standard:no-semi",
    "ktlint:standard:statement-wrapping",
    "MaxLineLength",
    "TooManyFunctions",
    "FunctionParameterNaming",
    "LongParameterList",
    "CyclomaticComplexMethod",
    "LongMethod",
    "MagicNumber",
)

package dev.sample_crate.kt

import dev.sample_crate.ChatCompletionChunk
import dev.sample_crate.ChatCompletionRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.withContext

/** Coroutine-friendly wrapper around the Java `dev.sample_crate.DefaultClient` facade. */
class DefaultClient internal constructor(internal val inner: dev.sample_crate.DefaultClient) : AutoCloseable {
    suspend fun chat(): String {
        return withContext(Dispatchers.IO) { inner.chat() }
    }
    fun chatStream(req: ChatCompletionRequest): kotlinx.coroutines.flow.Flow<ChatCompletionChunk> = kotlinx.coroutines.flow.callbackFlow {
        val inner: dev.sample_crate.DefaultClient = this@DefaultClient.inner
        val mapper = com.fasterxml.jackson.databind.ObjectMapper()
            .registerModule(com.fasterxml.jackson.datatype.jdk8.Jdk8Module())
            .findAndRegisterModules()
            .setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE)
        val streamHandle: Long = withContext(Dispatchers.IO) {
            Bridge.nativeDefaultClientChatStreamStart(inner, mapper.writeValueAsString(req))
        }
        try {
            while (true) {
                val chunkJson: String? = withContext(Dispatchers.IO) {
                    Bridge.nativeDefaultClientChatStreamNext(streamHandle)
                }
                if (chunkJson == null) break
                val chunk = mapper.readValue(chunkJson, ChatCompletionChunk::class.java)
                send(chunk)
            }
            close()
        } catch (e: Throwable) {
            close(e)
        }
        awaitClose {
            Bridge.nativeDefaultClientChatStreamFree(streamHandle)
        }
    }
    override fun close() { inner.close() }
}
