Kotlin SDK
The official nRouter Kotlin SDK with coroutines support, reactive cold Flow streaming, typed errors, and automatic response metadata header extraction.
The official nRouter Kotlin SDK provides coroutines-first JVM bindings for the unified AI gateway at https://api.nrouter.ai/v1. Configure authentication with NROUTER_API_KEY, execute non-blocking suspend functions, consume reactive cold Flow streams, and extract x-nr-* response metadata. For Android apps, see nrouter-sdk-android.
Installation
Publish the artifact to your local Maven cache (./gradlew clean check publishToMavenLocal), then add it to build.gradle.kts:
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation("ai.nrouter:nrouter-sdk-kotlin:3.1.2")
}Set your environment variable:
export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"Chat Completion
The client targets https://api.nrouter.ai/v1 and dispatches on Dispatchers.IO:
import ai.nrouter.sdk.NRouter
import org.json.JSONObject
suspend fun main() {
val client = NRouter()
val result = client.chatCompletions(
JSONObject()
.put("model", "gpt-5.4-mini")
.put("messages", listOf(mapOf("role" to "user", "content" to "Hello!")))
)
val content = result.body.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content")
println(content)
if (result.meta.isPriced) {
println("Cost: $${result.meta.cost} | Request ID: ${result.meta.requestId}")
}
}Flow Streaming
import ai.nrouter.sdk.NRouter
import kotlinx.coroutines.flow.collect
import org.json.JSONObject
suspend fun streamTokens(client: NRouter) {
client.messagesStream(
JSONObject()
.put("model", "claude-haiku-4-5-20251001")
.put("max_tokens", 256)
.put("messages", listOf(mapOf("role" to "user", "content" to "Hello!")))
).collect { chunk ->
print(chunk.delta)
}
}Error Handling
Gateway refusals map to typed subclasses of NRouterError:
| Class | HTTP Status | Description |
|---|---|---|
NRouterError.GuardrailBlocked | 400 | Request blocked by guardrail policy |
NRouterError.Authentication | 401 | Invalid or revoked NROUTER_API_KEY |
NRouterError.Credit | 402 | Account balance or budget ceiling exhausted |
NRouterError.RateLimit | 429 | RPM or TPM rate limit exceeded |
NRouterError.Service | 503 | Upstream provider or gateway error |
isRetryable returns true for RateLimit, Service, and Transport.