TsgcHTTP_API_AnthropicMethods › CountTokens

CountTokens Method

Counts the number of input tokens a request would consume before sending it to Claude

Syntax

function CountTokens(const aRequest: TsgcAnthropicClass_Request_CountTokens) : TsgcAnthropicClass_Response_CountTokens;

Parameters

NameTypeDescription
aRequestconst TsgcAnthropicClass_Request_CountTokensRequest object with the same Model, System and Messages fields you would send to CreateMessage.

Return Value

Response containing the InputTokens count that the request would use (TsgcAnthropicClass_Response_CountTokens)

Remarks

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.

Example

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;

Back to Methods