---
source: tests/backends_kotlin_android_gen_bindings_test.rs
expression: kt_content
---
// Generated by alef. Do not edit by hand.
@file:Suppress(
    "ktlint:standard:max-line-length",
    "ktlint:standard:trailing-comma-on-declaration-site",
    "ktlint:standard:trailing-comma-on-call-site",
    "ktlint:standard:annotation",
    "MaxLineLength",
    "TooManyFunctions",
    "LongParameterList",
    "LongMethod",
)

package dev.sample_crate.demo.android

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.withContext

@Suppress("TooManyFunctions")
class DefaultClient internal constructor(internal val handle: Long) : AutoCloseable {
    suspend fun chat(): String {
        return withContext(Dispatchers.IO) { DemoBridge.nativeDefaultClientChat(handle) }
    }

    @Suppress("TooGenericExceptionCaught")
    fun chatStream(req: ChatCompletionRequest): kotlinx.coroutines.flow.Flow<ChatCompletionChunk> = kotlinx.coroutines.flow.callbackFlow {
        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) {
            DemoBridge.nativeDefaultClientChatStreamStart(handle, mapper.writeValueAsString(req))
        }
        try {
            while (true) {
                val chunkJson: String? = withContext(Dispatchers.IO) {
                    DemoBridge.nativeDefaultClientChatStreamNext(streamHandle)
                }
                if (chunkJson == null) break
                val chunk = mapper.readValue(chunkJson, ChatCompletionChunk::class.java)
                send(chunk)
            }
            close()
        } catch (e: Throwable) {
            close(e)
        }
        awaitClose {
            DemoBridge.nativeDefaultClientChatStreamFree(streamHandle)
        }
    }
    override fun close() { DemoBridge.nativeFreeDefaultClient(handle) }
}
