In this categoryTroubleshooting · 27
- How to Fix an OpenAI 401 'Invalid API Key' ErrorStart
- How to Fix OpenAI 429 Rate Limit Errors With Backoff
- How to Fix Anthropic Claude API 401 Authentication Errors
- How to Fix Google Gemini 'API Key Not Valid' Errors
- How to Fix an API Key That Loads as Undefined
- How to Handle Anthropic 529 'Overloaded' Errors
- How to Fix Rate Limit Errors from an AI API
- How to Fix CORS Errors When Calling an AI API From the Browser
- How to Fix 'Model Not Found' and Deprecated Model Errors
- How to Rotate a Leaked API Key Without Downtime
- How to Fix SSL Certificate Errors When Calling AI APIs
- How to count tokens before sending a prompt to Claude
- How to Fix 'Context Length Exceeded' Token Limit Errors
- How to fix a context length exceeded error in the Claude API
- How to fix a Claude response that gets cut off mid-sentence
- How to reduce Claude hallucinations by grounding answers in your documents
- How to keep a long Claude conversation under the context limit
- How to stop Claude from calling tools when it should not
- How to handle a Claude Fable 5 refusal with a fallback model
- How to choose the right Claude model for cost and quality
- How to cut Claude API costs with prompt caching
- How to halve Claude costs for bulk jobs with the Batch API
- How to cap spend on a Claude agent with a task budget
- How to Debug an MCP Server That Will Not Connect
- How to Ask an Agent to Explain a Bug Before Fixing It
- How to Roll Back a Bad Deploy Quickly
- How to Fix Cursor Not Indexing Your Codebase
How to count tokens before sending a prompt to Claude
Use the count_tokens endpoint to measure a prompt accurately so you never guess at size or cost.
Guessing token counts leads to surprise overflows and surprise bills. The Anthropic API has a dedicated count_tokens endpoint that returns the exact input token count for a given model. It costs nothing to call and takes one request. This guide shows how to count a string, a file, and the difference between two versions of a file.
- The Anthropic SDK for Python or Node, or the ant CLI
- An ANTHROPIC_API_KEY in your environment
- The text, file, or messages you want to measure
Step 1: Count a single string
Pass the text as a user message and read input_tokens off the response. Always pass the same model id you intend to call, because counts are model specific.
from anthropic import Anthropic
client = Anthropic()
resp = client.messages.count_tokens(
model="claude-opus-4-8",
messages=[{"role": "user", "content": "How many tokens is this sentence?"}],
)
print(resp.input_tokens)Step 2: Count a whole file
Read the file into the content field. This is the standard way to check whether a document will fit before you commit to a full generation call.
resp = client.messages.count_tokens(
model="claude-opus-4-8",
messages=[{"role": "user", "content": open("CLAUDE.md").read()}],
)
print(resp.input_tokens)Step 3: Count from the command line
If you prefer the terminal, the ant CLI exposes the same endpoint. The @ prefix inlines a file into the content field, and --transform pulls out just the number.
Step 4: Turn tokens into a cost estimate
Once you have the input count, multiply by the model's input rate. Opus 4.8 is 5 dollars per million input tokens. So 18,432 input tokens costs about 0.09 dollars on the way in, before you add the output you will generate.
input_tokens = 18432
cost = input_tokens / 1_000_000 * 5.00 # Opus 4.8 input rate
print(f"about ${cost:.4f} for input")Result: the file measured 18,432 tokens against Opus 4.8, comfortably inside the 1M window, at roughly nine cents of input cost. You now know the request will fit and what it will cost before sending a single generation call.
Watch related tutorials
1:42:18
28:14
41:09
9:47
8:23
52:31New guides in your inbox
Fresh step-by-step how-to guides as we publish them. One email a week, no more.