Skip to main content

Kotlin Support

Kotlin is a statically-typed language targeting the JVM (and other platforms), enabling concise and elegant code with seamless interoperability with Java libraries. LangChain4j utilizes Kotlin extensions to enhance Java APIs with Kotlin-specific conveniences. This allows users to extend existing Java classes with additional functionality tailored for Kotlin.

For instance, Kotlin extensions can convert a ChatLanguageModel response into Kotlin Suspending Function response into a Kotlin Suspending Function:

val model = OpenAiChatModel.builder()
.apiKey("your-api-key")
// more configuration parameters here ...
.build()

CoroutineScope(Dispatchers.IO).launch {
val response = model.chatAsync(
ChatRequest.builder()
.messages(
listOf(
SystemMessage.from("You are a helpful assistant"),
UserMessage.from("Hello!")
)
)
)
println(response.aiMessage().text())
}

LangChain4j does not require Kotlin libraries as runtime dependencies but allows users to leverage Kotlin's coroutine capabilities for non-blocking execution, enhancing performance and efficiency.