SDKsR SDK
R SDK
Official nRouter R SDK featuring R-universe installation, Server-Sent Events streaming callbacks, metadata extraction, and real-time spend attribution.
The official nRouter R SDK (nrouter) provides an idiomatic, high-performance interface for connecting to https://api.nrouter.ai/v1. Configure NROUTER_API_KEY authentication, execute chat completions, stream tokens via callbacks, and inspect exact USD costs with result$meta.
Installation
Install pre-built binaries from R-universe:
install.packages("nrouter", repos = c(
nrouterai = "https://nrouterai.r-universe.dev",
CRAN = "https://cloud.r-project.org"
))Or install from GitHub with remotes::install_github("nRouterGateway/nrouter-sdk", subdir = "sdks/r").
Chat Completion
Set your key in .Renviron or export it in the shell:
NROUTER_API_KEY=sk-nrouter-xxxxxxxxxxxxlibrary(nrouter)
client <- nrouter_client(
api_key = Sys.getenv("NROUTER_API_KEY"),
base_url = "https://api.nrouter.ai/v1"
)
result <- nrouter_chat_completions(client, list(
model = "gpt-5.4-mini",
messages = list(list(role = "user", content = "Explain linear mixed-effects models."))
))
cat(result$body$choices[[1]]$message$content, "\n")
if (nrouter_is_priced(result$meta)) {
cat("Cost: $", result$meta$cost, " | ID: ", result$meta$request_id, "\n")
}SSE Streaming
Stream token chunks using a callback function:
nrouter_messages_stream(
client,
list(
model = "claude-haiku-4-5-20251001",
max_tokens = 256,
messages = list(list(role = "user", content = "Write a haiku."))
),
callback = function(chunk) {
cat(chunk$delta)
return(TRUE)
}
)
cat("\n")Error Handling
Gateway refusals map to classed conditions caught with tryCatch:
| Class | HTTP Status | Description |
|---|---|---|
nrouter_guardrail_blocked_error | 400 | Blocked by configured guardrail |
nrouter_authentication_error | 401 | Invalid or missing NROUTER_API_KEY |
nrouter_credit_error | 402 | Account balance or key budget ceiling reached |
nrouter_rate_limit_error | 429 | RPM or TPM rate limit exceeded |
nrouter_service_error | 503 | Gateway or upstream provider unavailable |
Next Steps
- R SDK Source & Examples
- Python SDK Guide — Official Python SDK
- cURL Examples — Direct HTTP request inspection
- Chat Completions API — HTTP endpoint specifications
Was this page helpful?