Google

统计 token

统计一段内容会消耗多少 token。

POST /google/v1beta/models/{modelsId}:countTokens◐ 部分支持

Gemini API 官方文档 ↗

请求参数

  • modelstring必填

    path: 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 `ListModels` method. Format: `models/{model}`

  • contentsarray可选◐ 部分支持

    Optional. The input given to the model as a prompt. This field is ignored when `generate_content_request` is set.

    原生透传;本地估算。与 generateContentRequest 同传返回 400。

    ▸ 展开子字段(2)
    • partsarray可选

      Ordered `Parts` that constitute a single message. Parts may have different MIME types.

      ▸ 展开子字段(16)
      • audioTranscriptionobject可选

        Optional. Audio (input or output) transcription. This is only set when this Part contains audio data.

      • codeExecutionResultobject可选

        Result of executing the `ExecutableCode`.

      • executableCodeobject可选

        Code generated by the model that is meant to be executed.

      • fileDataobject可选

        URI based data.

      • functionCallobject可选

        A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values.

      • functionResponseobject可选

        The result output of a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model.

      • inlineDataobject可选◐ 部分支持

        Inline media bytes.

        原生透传;本地读取 PNG/JPEG/GIF 头估算图片 token,不把 base64 当文本;其他媒体使用近似额度。

      • mediaProcessingstring可选

        Optional. How the model processes this part's media for understanding. Only meaningful for video parts (`inline_data` or `file_data` with video mime). Non-video parts ignore this field.

        取值 AGENTICMEDIA_PROCESSING_UNSPECIFIEDSTATIC
      • mediaResolutionobject可选

        Optional. Media resolution for the input media.

      • partMetadataobject可选

        Custom 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.

      • textstring可选

        Inline text.

      • thoughtboolean可选

        Optional. Indicates if the part is thought from the model.

      • thoughtSignaturestring可选

        Optional. An opaque signature for the thought so it can be reused in subsequent requests.

      • toolCallobject可选

        Server-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.

      • toolResponseobject可选

        The output from a server-side `ToolCall` execution. This field is populated by the client with the results of executing the corresponding `ToolCall`.

      • videoMetadataobject可选

        Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.

    • rolestring可选

      Optional. 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.

  • generateContentRequestobject可选◐ 部分支持

    Optional. The overall input given to the `Model`. This includes the prompt as well as other model steering information like [system instructions](https://ai.google.dev/gemini-api/docs/system-instructions), and/or function declarations for [function calling](https://ai.google.dev/gemini-api/docs/function-calling). `Model`s/`Content`s and `generate_content_request`s are mutually exclusive. You can either send `Model` + `Content`s or a `generate_content_request`, but never both.

    原生路径保留 systemInstruction 和 tools 并映射模型;本地计入估算。

    ▸ 展开子字段(11)
    • cachedContentstring可选○ 未支持

      Optional. The name of the content [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context to serve the prediction. Format: `cachedContents/{cachedContent}`

    • contentsarray可选

      Required. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), this is a repeated field that contains the conversation history and the latest request.

    • generationConfigobject可选

      Optional. Configuration options for model generation and outputs.

    • labelsobject可选

      Optional. 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"}`)

    • modelstring可选

      Required. The name of the `Model` to use for generating the completion. Format: `models/{model}`.

    • safetySettingsarray可选

      Optional. A list of unique `SafetySetting` instances for blocking unsafe content. This will be enforced on the `GenerateContentRequest.contents` and `GenerateContentResponse.candidates`. There should not be more than one setting for each `SafetyCategory` type. 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 each `SafetyCategory` specified in the safety_settings. If there is no `SafetySetting` for a given `SafetyCategory` provided 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](https://ai.google.dev/gemini-api/docs/safety-settings) for detailed information on available safety settings. Also refer to the [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to learn how to incorporate safety considerations in your AI applications.

    • serviceTierstring可选

      Optional. The service tier of the request.

      取值 flexprioritystandardunspecified
    • storeboolean可选

      Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.

    • systemInstructionobject可选

      Optional. Developer set [system instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). Currently, text only.

    • toolConfigobject可选

      Optional. Tool configuration for any `Tool` specified in the request. Refer to the [Function calling guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) for a usage example.

    • toolsarray可选

      Optional. A list of `Tools` the `Model` may use to generate the next response. A `Tool` is 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 the `Model`. Supported `Tool`s are `Function` and `code_execution`. Refer to the [Function calling](https://ai.google.dev/gemini-api/docs/function-calling) and the [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) guides to learn more.

返回

200

按模型族校准的估算值(包括中文和工具定义),响应头为 x-praxis-token-count: estimated;不能用作精确用量或计费依据。

错误按 Gemini API 格式返回,参见 错误码

响应

HTTP 200

Successful response

application/json

名称类型说明
cacheTokensDetailsarray<object>Output only. List of modalities that were processed in the cached content.
cacheTokensDetails[].modalitystringThe modality associated with this token count.
cacheTokensDetails[].tokenCountintegerNumber of tokens.
cachedContentTokenCountintegerNumber of tokens in the cached part of the prompt (the cached content).
promptTokensDetailsarray<object>Output only. List of modalities that were processed in the request input.
promptTokensDetails[].modalitystringThe modality associated with this token count.
promptTokensDetails[].tokenCountintegerNumber of tokens.
totalTokensintegerThe number of tokens that the `Model` tokenizes the `prompt` into. Always non-negative.