count_tokens¶
Operation¶
count_tokens
async
¶
count_tokens(input: CountTokensOperationInput, plugins: list[Plugin] | None = None) -> CountTokensOutput
Returns the token count for a given inference request. This operation helps you estimate token usage before sending requests to foundation models by returning the token count that would be used if the same input were sent to the model in an inference request.
Token counting is model-specific because different models use different
tokenization strategies. The token count returned by this operation will
match the token count that would be charged if the same input were sent
to the model in an InvokeModel or Converse request.
You can use this operation to:
-
Estimate costs before sending inference requests.
-
Optimize prompts to fit within token limits.
-
Plan for token usage in your applications.
This operation accepts the same input formats as InvokeModel and
Converse, allowing you to count tokens for both raw text inputs and
structured conversation formats.
The following operations are related to CountTokens:
-
InvokeModel - Sends inference requests to foundation models
-
Converse - Sends conversation-based inference requests to foundation models
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
CountTokensOperationInput
|
An instance of |
required |
plugins
|
list[Plugin] | None
|
A list of callables that modify the configuration dynamically. Changes made by these plugins only apply for the duration of the operation execution and will not affect any other operation invocations. |
None
|
Returns:
| Type | Description |
|---|---|
CountTokensOutput
|
An instance of |
Input¶
CountTokensOperationInput
dataclass
¶
Dataclass for CountTokensOperationInput structure.
Attributes¶
input
class-attribute
instance-attribute
¶
input: CountTokensInput | None = None
The input for which to count tokens. The structure of this parameter
depends on whether you're counting tokens for an InvokeModel or
Converse request:
-
For
InvokeModelrequests, provide the request body in theinvokeModelfield -
For
Converserequests, provide the messages and system content in theconversefield
The input format must be compatible with the model specified in the
modelId parameter.
model_id
class-attribute
instance-attribute
¶
model_id: str | None = None
The unique identifier or ARN of the foundation model to use for token counting. Each model processes tokens differently, so the token count is specific to the model you specify.
Output¶
CountTokensOutput
dataclass
¶
Dataclass for CountTokensOutput structure.
Attributes¶
input_tokens
instance-attribute
¶
input_tokens: int
The number of tokens in the provided input according to the specified model's tokenization rules. This count represents the number of input tokens that would be processed if the same input were sent to the model in an inference request. Use this value to estimate costs and ensure your inputs stay within model token limits.