TsgcHTTP_API_Anthropic › Methods › CountTokens
Counts the number of input tokens a request would consume before sending it to Claude
function CountTokens(const aRequest: TsgcAnthropicClass_Request_CountTokens) : TsgcAnthropicClass_Response_CountTokens;
| Name | Type | Description |
|---|---|---|
aRequest | const TsgcAnthropicClass_Request_CountTokens | Request object with the same Model, System and Messages fields you would send to CreateMessage. |
Response containing the InputTokens count that the request would use (TsgcAnthropicClass_Response_CountTokens)
Sends a POST /v1/messages/count_tokens call to the Anthropic API to calculate how many input tokens a prompt would consume without actually generating a completion. This is useful for cost estimation, request pre-validation and for staying under the context window of the target model. The anthropic-version header from AnthropicOptions is included automatically. The returned object must be freed by the caller.
oRequest := TsgcAnthropicClass_Request_CountTokens.Create;
oRequest.Model := 'claude-sonnet-4-5';
oRequest.Messages.Add('user', 'How many tokens is this sentence?');
oResponse := oAPI.CountTokens(oRequest);
try ShowMessage(IntToStr(oResponse.InputTokens)); finally oResponse.Free; end;