Gemini 原生

统计 Token 数

统计 Gemini 请求的输入 token 数,不生成内容也不计费。

POST
/v1beta/models/{model}:countTokens

在发送前统计 Gemini 请求的输入 token 数。该调用不计费,也不要求账户有余额,但需要 API 密钥。适用于获取模型响应的 supportedGenerationMethods 中列出 countTokens 的模型。

发送 contents 或完整的 generateContentRequest 之一。计数用于请求规划;生成请求的费用以该响应的 usageMetadata 为准。

身份验证

与生成内容相同:?key=、x-goog-api-key 或 Authorization: Bearer。

请求体

contentsarray

对话内容,格式与生成内容相同。

generateContentRequestobject

要统计的完整 Gemini 生成请求,可替代 contents。也接受 generate_content_request。

错误

  • 400 INVALID_ARGUMENT:请求体无效,或模型不接受 Gemini 请求。
  • 401 UNAUTHENTICATED:API 密钥缺失或无效。
  • 503 UNAVAILABLE:该模型暂时没有可用线路,请稍后重试。

请求

cURL
curl -X POST "https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:countTokens" \
  -H "x-goog-api-key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [{"text": "Hello, Gemini!"}]
      }
    ]
  }'

响应

200 OK
{
  "totalTokens": 7
}
totalTokensinteger
请求中的输入 token 数。

授权

AuthorizationBearer <token>

API Key 身份验证。在 Dashboard > API > API Keys 中创建或管理 API Key。

位置: header

路径参数

model*string

模型名称 (例如 gemini-2.5-pro)

查询参数

key?string

API 密钥 (请求头身份验证的替代方案)

请求体

application/json

响应

application/json

application/json

application/json

application/json