Token count
POST /api/token-countCount exact LLM tokens for a string using the real OpenAI BPE (o200k_base for gpt-4o/o-series, cl100k_base for gpt-4/gpt-3.5). Send POST /api/token-count with the required field text and pay $0.001 per call over x402 or MPP, or call it free by solving a proof-of-work challenge. It returns a JSON object with tokens, characters, model and encoding.
Deterministic, offline - budget context windows without calling a model.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
text | string | yes | Also accepted as content, str, string, input, body, data. |
model | string | no | gpt-4o (default, o200k) | gpt-4 / gpt-3.5 (cl100k) |
Example request
curl -i -X POST https://agent402.tools/api/token-count \
-H "Content-Type: application/json" \
-d '{"text":"hello world","model":"gpt-4o"}'
Without payment this returns HTTP 402 Payment Required with the exact price for token-count; any x402 v2 or MPP client pays it and retries.
Example response
{
"tokens": 2,
"characters": 11,
"model": "gpt-4o",
"encoding": "o200k_base"
}
| Field | Type | Always present | In the example |
|---|---|---|---|
tokens | number | yes | 2 |
characters | number | yes | 11 |
model | string | yes | gpt-4o |
encoding | string | yes | o200k_base |
From an MCP client
catalog.call {
"slug": "token-count",
"params": {
"text": "hello world",
"model": "gpt-4o"
}
}
On the hosted connector at https://agent402.tools/mcp, catalog.call runs token-count free (rate-limited, no wallet). Local install: npx -y agent402-mcp.
Errors and behavior
textis required. An input the tool rejects returns an HTTP 4xx whose body carrieserror,tool,expected,requiredandexample, so the caller can correct it.- A paid call that ends in any status of 400 or above is not charged over x402, MPP or a prepaid credits key: settlement is cancelled when the tool fails. The exception is a Tempo push credential, a transfer the buyer sent before the call: it settles before the tool runs, so if the tool then fails the payment is recorded as a refund owed to the paying wallet.
- Free tier: no outbound network call leaves the server for this tool, so proof-of-work (16 leading zero bits of sha256) pays for it.
- A
GETorHEADto /api/token-count returns the same 402 quote, so the price can be read without a body. - An
Idempotency-Keyheader makes a retried paid call replay the first 200 instead of charging again (an answer larger than 1 MB is not replayed).
Paid call (JavaScript agent)
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const client = new x402Client();
client.setSpendControls?.(false); // keep your own spending ceiling in code
registerExactEvmScheme(client, { signer: privateKeyToAccount(KEY) });
const payFetch = wrapFetchWithPayment(fetch, client);
const res = await payFetch("https://agent402.tools/api/token-count", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
"text": "hello world",
"model": "gpt-4o"
}),
});
No wallet? Pay with compute
Fetch a challenge, solve the sha256 puzzle (16 leading zero bits, a fraction of a second of CPU), and resend with the X-Pow-Solution header:
import { createHash } from "node:crypto";
const lz = (b) => { let t = 0; for (const x of b) { if (!x) { t += 8; continue; } t += Math.clz32(x) - 24; break; } return t; };
const c = await (await fetch("https://agent402.tools/api/pow/challenge?slug=token-count")).json();
let n = 0;
while (lz(createHash("sha256").update(c.challenge + ":" + n).digest()) < c.difficulty) n++;
await fetch("https://agent402.tools/api/token-count", { method: "POST", headers: { "X-Pow-Solution": c.token + ":" + n, "Content-Type": "application/json" }, body: JSON.stringify({"text":"hello world","model":"gpt-4o"}) });
Part of these workflows
Token count is one step in this skill pack, each sold as a single call:
- Text analysis - Full text analysis - word/sentence stats, keyword extraction, and token count in one pass.
Related tools
Text chunk (RAG)
POST /api/text-chunkSplit text into overlapping chunks for RAG ingestion - by characters (default) or by exact LLM tokens. Returns the chunk…
Text statistics
POST /api/text-statsCounts for any text in one call: characters (Unicode code points), words, sentences, paragraphs, avgWordLength, readingT…
Case convert
POST /api/caseConvert text between camelCase, PascalCase, snake_case, kebab-case, CONSTANT_CASE, Title Case, lower, UPPER.
Count
POST /api/countCount characters, words, lines, and (optionally) occurrences of a substring in text.
Dedupe lines
POST /api/dedupe-linesRemove duplicate lines, preserving first-seen order. Returns the deduped text and how many were removed.
Extract entities
POST /api/extract-entitiesPull emails, URLs, IPv4s, @mentions, and #hashtags out of free text. Returns deduped lists.