Browse documentation
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-xxxxxxxxxxxx
library(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:

ClassHTTP StatusDescription
nrouter_guardrail_blocked_error400Blocked by configured guardrail
nrouter_authentication_error401Invalid or missing NROUTER_API_KEY
nrouter_credit_error402Account balance or key budget ceiling reached
nrouter_rate_limit_error429RPM or TPM rate limit exceeded
nrouter_service_error503Gateway or upstream provider unavailable

Next Steps

Was this page helpful?