Browse documentation

Python SDK

The official nRouter Python SDK with automatic metadata extraction, real-time cost tracking, Anthropic messages support, and connection pool management.

The official nRouter Python SDK (nrouter-sdk) provides automated metadata extraction, exact USD cost tracking, and gateway guardrails.

Connect applications to https://api.nrouter.ai/v1 using your virtual NROUTER_API_KEY:

  • Universal wire support: Full compatibility with OpenAI Chat Completions and native Anthropic Messages (/v1/messages).
  • Telemetry & FinOps: Automatic parsing of x-nr-* response headers, exact USD request cost, and cache hit status.

Installation

Install from PyPI:

pip install nrouter-sdk

Setup & Chat Completion

Set your virtual API key in your environment:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"

Initialize the client with automatic environment resolution and response telemetry:

from nroutersdk import nRouter

# Reads NROUTER_API_KEY and targets https://api.nrouter.ai/v1
with nRouter() as client:
    response = client.chat.completions.create(
        model="gpt-5.4-mini",
        messages=[{"role": "user", "content": "Hello, nRouter!"}],
    )
    print(response.choices[0].message.content)

    if client.last_response:
        print(f"Request ID: {client.last_response.request_id}")
        print(f"Cost (USD): ${client.last_response.cost}")

Streaming Responses

Stream tokens via Server-Sent Events (SSE):

from nroutersdk import nRouter

client = nRouter()

stream = client.chat.completions.create(
    model="gpt-5.4-mini",
    messages=[{"role": "user", "content": "Summarize distributed consensus."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
print()

Error Handling

Recover cleanly from network timeouts, quota limits, and guardrail redactions:

from nroutersdk import (
    nRouter,
    nRouterError,
    nRouterAuthenticationError,
    nRouterRateLimitError,
    nRouterGuardrailBlockedError,
)

client = nRouter()

try:
    response = client.chat.completions.create(
        model="claude-sonnet-4-5-20250929",
        messages=[{"role": "user", "content": "Execute task"}],
    )
except nRouterGuardrailBlockedError as e:
    print(f"Request blocked by safety policy: {e}")
except nRouterRateLimitError as e:
    print(f"Rate limited: retry after {e.retry_after}s")
except nRouterAuthenticationError:
    print("Authentication failed: Verify NROUTER_API_KEY.")
except nRouterError as e:
    print(f"Gateway error (HTTP {e.status_code}): {e.message}")
finally:
    client.close()

Next Steps

Was this page helpful?