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.

Last updated

The official nRouter R SDK (nrouter) provides an idiomatic, high-performance interface for data scientists, statisticians, and researchers using R. Because there is no official OpenAI client for the R ecosystem, this package communicates directly with the nRouter edge gateway at https://api.nrouter.ai/v1 via httr and curl, delivering full support for chat completions, Server-Sent Events (SSE) streaming, and real-time cost attribution.

By standardizing R pipelines on nRouter, enterprise data science teams benefit from centralized API governance: server-side guardrails block sensitive data and prompt injections before inference, virtual keys enforce hard monthly spend limits per lab or researcher, and multi-cloud fallbacks eliminate script failures during provider downtime.

Prerequisites & Installation

The package requires R 4.1 or higher.

Installing from R-universe

Install the pre-built binaries directly from R-universe:

install.packages(
  "nrouter",
  repos = c(
    nroutergateway = "https://nroutergateway.r-universe.dev",
    CRAN = "https://cloud.r-project.org"
  )
)

Installing from GitHub

For bleeding-edge development builds, install using remotes:

if (!requireNamespace("remotes", quietly = TRUE)) {
  install.packages("remotes")
}
remotes::install_github("nRouterGateway/nrouter-sdk", subdir = "sdks/r")

Setup & Configuration

Configure authentication by saving your nRouter virtual key in your user or project .Renviron file:

NROUTER_API_KEY=sk-nrouter-your-virtual-key

Or set the key dynamically in your R session:

Sys.setenv(NROUTER_API_KEY = "sk-nrouter-your-virtual-key")

Initializing the Client

Initialize the client with automatic environment resolution:

library(nrouter)

# Automatically reads NROUTER_API_KEY and targets https://api.nrouter.ai/v1
client <- nrouter_client()

Configuration Parameters

Configure custom connection options, timeouts, and routing headers:

ParameterTypeDefaultDescription
api_keycharacterSys.getenvYour nRouter virtual key (sk-nrouter-...).
base_urlcharacterhttps://api.nrouter.ai/v1Unified gateway base URL. Must include /v1.
timeoutnumeric60Request timeout in seconds.
headerslistlist()Custom HTTP headers sent on every request (e.g. x-nr-routing).
library(nrouter)

# Production client configuration with latency optimization
client <- nrouter_client(
  api_key = Sys.getenv("NROUTER_API_KEY"),
  base_url = "https://api.nrouter.ai/v1",
  timeout = 45,
  headers = list("x-nr-routing" = "latency")
)

Implementation Patterns

1. Synchronous Chat Completion

Send structured messages and parse the completion object:

library(nrouter)

client <- nrouter_client()

result <- nrouter_chat_completions(client, list(
  model = "gpt-5.4-mini",
  messages = list(
    list(role = "system", content = "You are a senior statistical programmer."),
    list(role = "user", content = "Explain linear mixed-effects models in three sentences.")
  )
))

# Print completion text
cat(result$body$choices[[1]]$message$content, "\n")

# Inspect real-time gateway spend
if (nrouter_is_priced(result$meta)) {
  cat(sprintf("Cost: $%f (%s)\n", result$meta$cost, result$meta$cost_status))
  cat("Request ID:", result$meta$request_id, "\n")
  cat("Model:", result$meta$model, "\n")
}

2. Server-Sent Events (SSE) Streaming

Stream token chunks in real-time using a callback function:

library(nrouter)

client <- nrouter_client()

nrouter_messages_stream(
  client,
  list(
    model = "claude-haiku-4-5-20251001",
    max_tokens = 256,
    messages = list(list(role = "user", content = "Write a short poem about reproducibility."))
  ),
  callback = function(chunk) {
    cat(chunk$delta)
    # Return FALSE if you wish to terminate streaming early
    return(TRUE)
  }
)
cat("\n")

3. Per-Request Gateway Overrides

Attach prompt template parameters or bypass cache in the request list:

result <- nrouter_chat_completions(client, list(
  model = "gpt-5.5",
  messages = list(list(role = "user", content = "Summarize clinical trial metrics.")),
  nrouter_prompt_template_id = "tmpl_clinical_summary_v1",
  nrouter_prompt_variables = list(phase = "Phase III"),
  nrouter_cache = TRUE
))

Production Best Practices

Deterministic Routing & Fallbacks

Ensure uninterruptible data processing jobs by specifying fallback models:

result <- nrouter_chat_completions(client, list(
  # Primary model with automatic fallback
  model = "gpt-5.4-mini,claude-haiku-4-5-20251001",
  messages = list(list(role = "user", content = "Analyze regression residuals."))
))
  • x-nr-routing: latency: Directs traffic to the lowest-latency active provider deployment.
  • x-nr-routing: cost: Prioritizes the most cost-effective deployment matching the model specification.
  • Model Fallback Chain: If the primary provider reports capacity limits or elevated 5xx errors, nRouter fails over instantly to the fallback model.

Response Telemetry & FinOps Tracking

Every call through nRouter produces metadata headers accessible via result$meta:

  • request_id: Edge UUID for correlating client-side logs with nRouter spend ledgers.
  • model: Canonical identifier of the physical model that served the response.
  • cost: Exact USD cost charged for the call.
  • cost_status: Status indicator (exact or unpriced).

Troubleshooting & Error Handling

Errors are raised as classed R conditions, enabling precise handling with tryCatch:

library(nrouter)

client <- nrouter_client()

tryCatch(
  nrouter_chat_completions(client, list(
    model = "gpt-5.4-mini",
    messages = list(list(role = "user", content = "Process dataset."))
  )),
  nrouter_guardrail_blocked_error = function(e) {
    message("Request blocked by nRouter guardrails: ", conditionMessage(e))
  },
  nrouter_credit_error = function(e) {
    message("Account balance exhausted or key ceiling hit: ", conditionMessage(e))
  },
  nrouter_rate_limit_error = function(e) {
    if (nrouter_is_retryable(e)) {
      message("Rate limit exceeded; retryable after exponential backoff.")
    }
  },
  nrouter_error = function(e) {
    message("nRouter general error: ", conditionMessage(e))
  }
)

Common Error Codes

ClassHTTP StatusDescriptionRecommended Action
nrouter_request_error400Invalid request formatVerify parameters and model bounds.
nrouter_guardrail_blocked_error400Blocked by server-side guardrail checkInspect prompt content; adjust guardrail rules in dashboard.
nrouter_authentication_error401Invalid or missing API keyVerify NROUTER_API_KEY in .Renviron.
nrouter_credit_error402Out of credits or budget exceededRefill organization credits or increase key budget ceiling.
nrouter_not_found_error404Model not foundCheck model catalog for available model IDs.
nrouter_rate_limit_error429Rate limit or TPM quota exceededImplement exponential backoff; check retry headers.
nrouter_service_error503Gateway or upstream service unavailableSpecify fallback models in the request.
nrouter_transport_error—Connection errorCheck local network connectivity.

Source & Repository

The source code, unit tests, and runnable demonstrations are maintained in the official SDK repository:

Next Steps

Was this page helpful?