Count Tokens
Calculate token count for an Anthropic Messages payload without an inference call. Essential for preflight budget verification and context window packing.
The /v1/messages/count_tokens endpoint delegates directly to the upstream Anthropic count_tokens endpoint with $0 inference spend. It calculates the exact input token count an Anthropic Messages payload will consume when sent to Claude models, without generating tokens or reserving credits.
nRouter validates key permissions and proxies the payload (system, messages, multimodal data, and tools) to the authoritative upstream tokenizer. The integer count is returned with no inference charges.
POST https://api.nrouter.ai/v1/messages/count_tokensRequest Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | Yes | — | Target Claude model (e.g. claude-sonnet-4-5-20250929). |
messages | array | Yes | — | Conversational messages array containing role and content. |
system | string or array | No | — | System context string or content block array. |
tools | array | No | — | Tool definitions whose schemas are parsed for token counts. |
thinking | object | No | — | Extended thinking configuration object. |
Examples
import { nRouter } from "@nrouter_ai/sdk";
const client = new nRouter({ apiKey: process.env.NROUTER_API_KEY });
const count = await client.messages.countTokens({
model: "claude-sonnet-4-5-20250929",
messages: [{ role: "user", content: "Count tokens for this sentence." }],
});
console.log("Tokens:", count.input_tokens);Headers & Errors
Inbound: Authorization: Bearer sk-nrouter-... and Content-Type: application/json. Outbound: x-nr-request-id, x-nr-latency-ms, x-nr-model, x-nr-guardrails. See Chat Completions.
| HTTP Status | Error Code | Reason |
|---|---|---|
| 400 Bad Request | invalid_request | Missing required model or messages field. |
| 401 Unauthorized | invalid_api_key | Virtual key missing, expired, or invalid. |
| 404 Not Found | model_not_found | Target model not recognized in catalog. |
| 429 Too Many Requests | rate_limit_exceeded | Account RPM ceiling exceeded for token counting operations. |
| 500 / 503 Gateway Error | service_unavailable | Upstream tokenizer service unavailable ($0 inference spend). |
Authorization
NRouterApiKey Your nRouter virtual key (sk-nrouter-…). Sent as Authorization: Bearer sk-nrouter-….
In: header
Header Parameters
Target MCP server ID when routing MCP tool calls or prompts through the gateway
Caller SDK runtime language identification (e.g. typescript, python, rust, go)
Caller session identifier allowed at edge for grouping related client turns
Inbound trace detail level override for request lifecycle spans
Value in
- "off"
- "stages"
- "verbose"
Inbound stage-level trace emission override
Value in
- "off"
- "stages"
- "verbose"
Accepted so a client sending it is not refused; the value is not recorded and not propagated. Every response carries the gateway's own trace ID in this header, never the one sent.
Request Body
application/json
TypeScript Definitions
Use the request body type in TypeScript.
Response Body
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
curl -X POST "https://example.com/v1/messages/count_tokens" \ -H "Content-Type: application/json" \ -d '{ "model": "string", "messages": [ {} ] }'{ "input_tokens": 9}