Count tokens
/google/v1beta/models/{modelsId}:countTokens◐ PartialRequest parameters
modelstringrequiredpath: Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the
ListModelsmethod. Format:models/{model}contentsarrayoptional◐ Partially supportedOptional. The input given to the model as a prompt. This field is ignored when
generate_content_requestis set.Forwarded natively or estimated locally. Sending both contents and generateContentRequest returns 400.
Expand sub-fields (2)
partsarrayoptionalOrdered
Partsthat constitute a single message. Parts may have different MIME types.Expand sub-fields (16)
audioTranscriptionobjectoptionalOptional. Audio (input or output) transcription. This is only set when this Part contains audio data.
codeExecutionResultobjectoptionalResult of executing the
ExecutableCode.executableCodeobjectoptionalCode generated by the model that is meant to be executed.
fileDataobjectoptionalURI based data.
functionCallobjectoptionalA predicted
FunctionCallreturned from the model that contains a string representing theFunctionDeclaration.namewith the arguments and their values.functionResponseobjectoptionalThe result output of a
FunctionCallthat contains a string representing theFunctionDeclaration.nameand a structured JSON object containing any output from the function is used as context to the model.inlineDataobjectoptional◐ Partially supportedInline media bytes.
Forwarded natively. Local estimates inspect PNG/JPEG/GIF headers without treating base64 as text; other media uses approximate allowances.
mediaProcessingstringoptionalOptional. How the model processes this part's media for understanding. Only meaningful for video parts (
inline_dataorfile_datawith video mime). Non-video parts ignore this field.mediaResolutionobjectoptionalOptional. Media resolution for the input media.
partMetadataobjectoptionalCustom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams.
textstringoptionalInline text.
thoughtbooleanoptionalOptional. Indicates if the part is thought from the model.
thoughtSignaturestringoptionalOptional. An opaque signature for the thought so it can be reused in subsequent requests.
toolCallobjectoptionalServer-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.
toolResponseobjectoptionalThe output from a server-side
ToolCallexecution. This field is populated by the client with the results of executing the correspondingToolCall.videoMetadataobjectoptionalOptional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.
rolestringoptionalOptional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset.
generateContentRequestobjectoptional◐ Partially supportedOptional. The overall input given to the
Model. This includes the prompt as well as other model steering information like system instructions, and/or function declarations for function calling.Models/Contents andgenerate_content_requests are mutually exclusive. You can either sendModel+Contents or agenerate_content_request, but never both.Native counting preserves systemInstruction and tools and maps the model; local counting includes them in estimates.
Expand sub-fields (11)
cachedContentstringoptional○ UnsupportedOptional. The name of the content cached to use as context to serve the prediction. Format:
cachedContents/{cachedContent}contentsarrayoptionalRequired. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries like chat, this is a repeated field that contains the conversation history and the latest request.
generationConfigobjectoptionalOptional. Configuration options for model generation and outputs.
labelsobjectoptionalOptional. Labels with user-defined metadata for the request. Optional. Labels must follow standard unified Cloud label requirements: - Label keys must start with a letter. - Label keys and values can be no longer than 63 characters (Unicode codepoints) and can only contain lowercase letters, numeric characters, underscores, and dashes. - International characters are allowed. Usage: - Safety identifiers from aggregators: Use the key
safety_identifier(e.g.{"safety_identifier": "user_session_123"})modelstringoptionalRequired. The name of the
Modelto use for generating the completion. Format:models/{model}.safetySettingsarrayoptionalOptional. A list of unique
SafetySettinginstances for blocking unsafe content. This will be enforced on theGenerateContentRequest.contentsandGenerateContentResponse.candidates. There should not be more than one setting for eachSafetyCategorytype. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for eachSafetyCategoryspecified in the safety_settings. If there is noSafetySettingfor a givenSafetyCategoryprovided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY, HARM_CATEGORY_JAILBREAK are supported. Refer to the guide for detailed information on available safety settings. Also refer to the Safety guidance to learn how to incorporate safety considerations in your AI applications.serviceTierstringoptionalOptional. The service tier of the request.
storebooleanoptionalOptional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.
systemInstructionobjectoptionalOptional. Developer set system instruction(s). Currently, text only.
toolConfigobjectoptionalOptional. Tool configuration for any
Toolspecified in the request. Refer to the Function calling guide for a usage example.toolsarrayoptionalOptional. A list of
ToolstheModelmay use to generate the next response. AToolis a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of theModel. SupportedTools areFunctionandcode_execution. Refer to the Function calling and the Code execution guides to learn more.
Returns
200
Returns a model-family-calibrated estimate, including Chinese text and tool definitions, with the response header x-praxis-token-count: estimated. Do not use it as an exact usage or billing count.
Errors follow the Gemini API format — see error codes
Request
curl
curl https://api.deepraxis.com/google/v1beta/models/gemini-2.5-flash:countTokens \
-H "x-goog-api-key: $PRAXIS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"contents":[{"role":"user","parts":[{"text":"你好"}]}]}'Python
from google import genai
from google.genai import types
client = genai.Client(
api_key="$PRAXIS_API_KEY",
http_options=types.HttpOptions(base_url="https://api.deepraxis.com/google"),
)
resp = client.models.count_tokens(
model="gemini-2.5-flash",
contents="你好",
)
print(resp.total_tokens)TypeScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "$PRAXIS_API_KEY",
httpOptions: { baseUrl: "https://api.deepraxis.com/google" },
});
const resp = await ai.models.countTokens({
model: "gemini-2.5-flash",
contents: "你好",
});
console.log(resp.totalTokens);Response 200
{
"totalTokens": 2
}Response
HTTP 200
Successful response
application/json
| Name | Type | Description |
|---|---|---|
| cacheTokensDetails | array<object> | Output only. List of modalities that were processed in the cached content. |
| cacheTokensDetails[].modality | string | The modality associated with this token count. |
| cacheTokensDetails[].tokenCount | integer | Number of tokens. |
| cachedContentTokenCount | integer | Number of tokens in the cached part of the prompt (the cached content). |
| promptTokensDetails | array<object> | Output only. List of modalities that were processed in the request input. |
| promptTokensDetails[].modality | string | The modality associated with this token count. |
| promptTokensDetails[].tokenCount | integer | Number of tokens. |
| totalTokens | integer | The number of tokens that the Model tokenizes the prompt into. Always non-negative. |