Browse documentation

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_tokens

Request Parameters

ParameterTypeRequiredDefaultDescription
modelstringYes—Target Claude model (e.g. claude-sonnet-4-5-20250929).
messagesarrayYes—Conversational messages array containing role and content.
systemstring or arrayNo—System context string or content block array.
toolsarrayNo—Tool definitions whose schemas are parsed for token counts.
thinkingobjectNo—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 StatusError CodeReason
400 Bad Requestinvalid_requestMissing required model or messages field.
401 Unauthorizedinvalid_api_keyVirtual key missing, expired, or invalid.
404 Not Foundmodel_not_foundTarget model not recognized in catalog.
429 Too Many Requestsrate_limit_exceededAccount RPM ceiling exceeded for token counting operations.
500 / 503 Gateway Errorservice_unavailableUpstream tokenizer service unavailable ($0 inference spend).
POST
/v1/messages/count_tokens

Authorization

NRouterApiKey
AuthorizationBearer <token>

Your nRouter virtual key (sk-nrouter-…). Sent as Authorization: Bearer sk-nrouter-….

In: header

Header Parameters

x-nr-tags?string

Custom spend and attribution tags (comma-separated key=value pairs)

x-nr-mcp-server?string

Target MCP server ID when routing MCP tool calls or prompts through the gateway

x-nr-client-language?string

Caller SDK runtime language identification (e.g. typescript, python, rust, go)

x-nr-session-id?string

Caller session identifier allowed at edge for grouping related client turns

x-nr-trace?string

Inbound trace detail level override for request lifecycle spans

Value in

  • "off"
  • "stages"
  • "verbose"
x-nr-trace-stages?string

Inbound stage-level trace emission override

Value in

  • "off"
  • "stages"
  • "verbose"
x-nr-trace-id?string

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}
Was this page helpful?