Android SDK
The official nRouter Android SDK packaged as an AAR with coroutines support, main-thread safety, lifecycle dispatching, and response metadata extraction.
The official nRouter Android SDK (ai.nrouter:nrouter-sdk-android) delivers main-thread-safe Kotlin coroutine bindings and response metadata extraction for https://api.nrouter.ai/v1. Pass your NROUTER_API_KEY to the factory method, execute non-blocking chat completions, and stream tokens via cold Flow streams. See nrouter-sdk-android for package details.
Installation
Build the AAR to your local Maven cache, then add the dependency to app/build.gradle.kts (minSdk = 21):
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation("ai.nrouter:nrouter-sdk-android:3.1.2")
}Setup & Quickstart
Initialize NRouterAndroid with your API key. In production, pass short-lived virtual keys minted by your backend rather than embedding static keys in APK binaries:
import ai.nrouter.sdk.android.NRouterAndroid
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.json.JSONObject
class ChatViewModel(app: Application) : AndroidViewModel(app) {
private val client = NRouterAndroid.create(app.applicationContext, "sk-nrouter-xxxxxxxxxxxx")
fun sendMessage(prompt: String) = viewModelScope.launch {
val result = client.chatCompletions(
JSONObject()
.put("model", "gpt-5.4-mini")
.put("messages", listOf(mapOf("role" to "user", "content" to prompt)))
)
val text = result.body.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content")
println("Response: $text (Cost: $${result.meta.cost})")
}
}For unit tests and local CLI development, the client falls back to NROUTER_API_KEY and connects to https://api.nrouter.ai.
Streaming
viewModelScope.launch {
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 NRouterError exceptions:
| Class | HTTP Status | Description |
|---|---|---|
NRouterError.GuardrailBlocked | 400 | Blocked by guardrail policies |
NRouterError.Authentication | 401 | Invalid or revoked NROUTER_API_KEY |
NRouterError.Credit | 402 | Balance exhausted or budget ceiling hit |
NRouterError.RateLimit | 429 | RPM or TPM rate limit exceeded |
NRouterError.Service | 503 | Upstream service or gateway error |