Claude Code API Usage Billing: Track Tokens and Cost
For claude code api usage billing in a coding workflow, the useful data is already in every response: token counts in the body, a request ID and your balance in the headers. This guide shows how to log it per request, reconcile it with your balance and keep agent loops from running away with the bill.
Last updated

What the API gives you to track
You do not need a separate analytics service to see usage. A normal chat completion response carries a usage object with prompt_tokens, completion_tokens and total_tokens. Those are the numbers billing is based on: input tokens at $0.15 per 1M and output tokens at $0.50 per 1M. The response headers add X-Request-Id, which identifies the request, and X-Balance-USD, which shows your balance. For streamed responses, usage arrives at the end of the stream.
A note on scope. Anthropic's Claude Code tool has its own usage reporting from Anthropic, which you should read in their documentation. This article is about tracking calls made to this site's OpenAI-compatible API, for example from your own scripts, agents and editor integrations that accept a custom endpoint and the model ID uncensored.
Log every request in one place
The simplest durable log is a table with one row per request. Wrap the SDK call once and use the wrapper everywhere. The example below stores a timestamp, a task label, the request ID, token counts, an estimated cost and the balance reported in the header.
import os, sqlite3, time
from openai import OpenAI
client = OpenAI(
base_url="https://api.claudecodeapi.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
db = sqlite3.connect("usage.db")
db.execute('''create table if not exists usage (
ts real, task text, request_id text,
prompt_tokens int, completion_tokens int,
est_cost real, balance real)''')
def cost(p: int, c: int) -> float:
return p * 0.15 / 1e6 + c * 0.50 / 1e6
def call(task: str, messages: list, **kw):
raw = client.chat.completions.with_raw_response.create(
model="uncensored", messages=messages, **kw
)
resp = raw.parse()
u = resp.usage
bal = raw.headers.get("X-Balance-USD")
db.execute(
"insert into usage values (?,?,?,?,?,?,?)",
(time.time(), task, raw.headers.get("X-Request-Id"),
u.prompt_tokens, u.completion_tokens,
cost(u.prompt_tokens, u.completion_tokens),
float(bal) if bal else None),
)
db.commit()
return resp
Pass a label that means something to you, such as refactor-auth, unit-tests or code-review. Then ask the table where the money goes:
sqlite3 usage.db "select task, count(*), sum(prompt_tokens), sum(completion_tokens), round(sum(est_cost), 4) from usage group by task order by 5 desc;"
Keep the request ID. When a response looks wrong, or you need support to look at one call, that ID is what identifies it.
Streaming responses
Editor and terminal integrations usually stream, so tokens appear as they are produced. Usage is delivered at the end of the stream, in the last chunk. Read it there:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a docstring for a retry decorator."}],
stream=True,
)
usage = None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
if getattr(chunk, "usage", None):
usage = chunk.usage
print()
print(usage)
If your tool hides the last chunk, you can read the balance from GET /v1/balance after the stream ends. Remember also that a streamed request keeps its concurrency slot until the stream finishes. With 8 slots on a full key, a few editors streaming long answers at once can crowd out a batch job, and the API answers 429 with the error code concurrency.
Why agent loops cost more than you expect
Coding agents work in a loop: the model proposes an action, a tool runs, and the result is added to the conversation. Each pass sends the full history again as input. The input grows with every step, and the cost of a task grows faster than the number of steps.
Take a 12-step task. The first call carries 3,000 tokens (instructions plus the files read), and each step adds 1,500 tokens of tool output and the model's reply. Output is 400 tokens per step.
- Input for step k is 3,000 + 1,500 x (k - 1). Step 1 has 3,000 tokens and step 12 has 19,500.
- Total input over 12 steps: 12 x 3,000 + 1,500 x (0 + 1 + ... + 11) = 36,000 + 99,000 = 135,000 tokens.
- Total output: 12 x 400 = 4,800 tokens.
- Cost: 135,000 x $0.00000015 = $0.02025, plus 4,800 x $0.0000005 = $0.0024. The task costs $0.02265.
Twelve independent calls with the opening 3,000-token prompt would have cost 12 x $0.00065 = $0.0078. The difference is history. At 50 such tasks a day, the agent costs about $1.13 a day.
The cheapest lever is the tool output. If you truncate each tool result so that each step adds 750 tokens instead of 1,500, input drops to 12 x 3,000 + 750 x 66 = 85,500 tokens. The task then costs $0.012825 + $0.0024 = $0.015225, about a third less. Return only the lines of a file the model needs, trim long logs, and do not paste the same file twice.
Cap spend per task
A loop that does not converge is the main source of surprise bills in coding workflows. Put a budget in the loop itself, using the same cost function:
BUDGET = 0.05 # dollars per task
spent = 0.0
messages = [{"role": "user", "content": "Find and fix the failing test."}]
for step in range(30):
resp = call("fix-failing-test", messages, max_tokens=800)
u = resp.usage
spent += cost(u.prompt_tokens, u.completion_tokens)
if spent > BUDGET:
print(f"Stopped at step {step + 1}: ${spent:.4f} spent")
break
# run tools here, append the results to messages, continue
Two more guards help. Set max_tokens so one verbose answer cannot take a large share of the budget, and limit the number of steps. Also watch for retry storms: if a tool fails and the model retries the same action, the history keeps growing while the work does not.
Reconcile your log with the balance
A log is only useful if it matches reality. Check it against the balance in a way that tolerates noise.
- Pick a quiet window, with one process using the key, so other jobs do not move the balance.
- Note the balance from
X-Balance-USDat the start and the end. - Sum
est_costfor the same window. - Compare the two totals. They should agree closely over a few hundred requests.
Single requests are a poor test. Rounding and the exact precision of the balance can hide the difference in one call, and concurrent requests return the balance header in any order. A large and persistent gap points to a real cause: a second process on the same key, a retry loop you did not log, or streamed calls that you did not record. Failed or refused requests are not charged, so they should not appear as spending.
Once the log and the balance agree, extend it with a daily summary that you read or send to chat. The pricing page has the rates behind the cost function, the docs describe the usage fields and endpoints, and the API key page offers a $0.50 trial to test the logger on real calls. Give each tool its own labelled key once your account has topped up, and billing questions become much easier to answer. For the cost side of the picture, the production checklist article is a useful companion.
More guides
Support queries
Where do I find token usage for a request?
In the usage object of the response body: prompt_tokens, completion_tokens and total_tokens. For streamed responses, usage arrives at the end of the stream.
How do I see my balance after each call?
Read the X-Balance-USD response header, or call GET /v1/balance. The OpenAI-style GET /v1/dashboard/billing/credit_grants also works.
Why does an agent task cost more than the sum of its steps?
Every step sends the full history again as input, so later steps are larger. Truncating tool output and ending loops early are the best ways to cut the cost.
Does this track Anthropic's Claude Code usage?
No. It tracks calls to this independent OpenAI-compatible API. Claude Code usage is reported by Anthropic.
Access key via sign-up
Register, copy the token, update the base URL. That covers the entire configuration.