Skip to main content

Set up

Wrap an instance of Anthropic from @anthropic-ai/sdk. The SDK recognizes it automatically.
  • Both ways of calling the Messages API are metered: messages.create for a regular call, and messages.stream for a streamed call, where the response arrives piece by piece. A streamed call is reported once, when the stream finishes, not once per piece.
  • A stream you stop early is still metered. Anthropic reports a streamed call’s final output count only at the end of the stream. If your code stops reading before then, for example when a user clicks “Stop”, the SDK estimates the output from the text received so far, at about four characters per token, and marks the measurement as estimated. To bill only counts Anthropic reported, see Your own mapper.
  • Optional: deny calls the balance cannot fully cover. By default, the check before each call uses a requested usage of 1, which only asks whether anything is left. The real usage is reported after the call, so a small balance can go over by about one call. If a single call can be expensive, use estimateFromMaxTokens(tokensPerUnit): the requested usage is then estimated from the call’s max_tokens, the longest response it could produce, and access is denied if the balance cannot cover it. tokensPerUnit is how many tokens make one unit of the credits or feature you enforce. See Gating calls for how to set it up.

What is reported

Every response from the Anthropic Messages API includes a usage object: the number of tokens the call consumed, split into input, output, and prompt cache reads and writes. Prompt caching lets Anthropic reuse the start of a prompt from an earlier call at a lower price. The wrapper reads these counts and reports them to Stigg as the metrics below. For details on each field, see Anthropic’s Messages API reference and prompt caching guide. Anthropic counts cache reads and cache writes separately from input_tokens, and the SDK reports each one as its own metric, plus total_tokens. Price the total, or the parts, but never both. If you want to charge for all of them together, for example by converting them into one credit balance with weighted credits, you can add them without counting any token twice. OpenAI is different: its input count already includes cached tokens. Every usage field the vendor returns is also included, with a raw. prefix. See How usage is reported.