計算 Claude 模型的權杖數

count-tokens 端點可讓您在將訊息傳送至 Claude 前,先判斷訊息中的權杖數量,協助您根據提示和用量做出明智決策。

使用 count-tokens 端點不需付費。

支援的 Claude 模型

下列模型支援計算權杖:

支援的地區

下列地區支援計數符記:

  • global
  • us
  • eu
  • asia-southeast1

計算基本訊息中的權杖

如要計算符記,請向 count-tokens 端點發出 rawPredict 要求。要求主體必須包含要計算符記的模型的模型 ID。

REST

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION:支援 Anthropic Claude 模型的區域。如要使用全域端點,請參閱「指定全域端點」。
  • MODEL:用來計算權杖的模型。
  • ROLE:與訊息相關聯的角色。您可以指定 user 或 assistant。 第一則訊息必須使用 user 角色。Claude 模型會以交替的user和assistant回合運作。如果最後一則訊息使用 assistant 角色,回應內容會立即接續該訊息的內容。您可以使用這項功能限制模型回覆的部分內容。
  • CONTENT:user 或 assistant 訊息的內容,例如文字。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/count-tokens:rawPredict

JSON 要求內文:

{
  "model": "MODEL",
  "messages": [
    {
      "role": "user",
      "content":"how many tokens are in this request?"
    }
  ],
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/count-tokens:rawPredict"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/count-tokens:rawPredict" | Select-Object -Expand Content

您應該會收到如下的 JSON 回覆。

如要瞭解如何使用工具、圖片和 PDF 計算訊息中的權杖,請參閱 Anthropic 說明文件。

配額

count-tokens 端點的預設配額為每分鐘 2, 000 項要求。