Подсчет токенов позволяет вам определить количество токенов в сообщении перед отправкой его Claude, помогая вам принимать обоснованные решения о ваших подсказках и использовании. С помощью подсчета токенов вы можете
This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.
Конечная точка подсчета токенов принимает тот же структурированный список входных данных для создания сообщения, включая поддержку системных подсказок, инструментов, изображений и PDF-файлов. Ответ содержит общее количество входных токенов.
Подсчет токенов следует рассматривать как оценку. В некоторых случаях фактическое количество входных токенов, используемых при создании сообщения, может отличаться на небольшую величину.
Подсчеты токенов могут включать токены, добавленные автоматически Anthropic для оптимизации системы. Вам не выставляется счет за добавленные системой токены. Выставление счетов отражает только ваше содержимое.
Все активные модели поддерживают подсчет токенов.
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-4-7",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(response.json()){ "input_tokens": 14 }Подсчет токенов серверного инструмента применяется только к первому вызову выборки.
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-4-7",
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"],
},
}
],
messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
)
print(response.json()){ "input_tokens": 403 }import base64
import httpx
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-opus-4-7",
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "Describe this image"},
],
}
],
)
print(response.json()){ "input_tokens": 1551 }Смотрите как рассчитывается контекстное окно с расширенным мышлением для получения дополнительной информации
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-sonnet-4-6",
thinking={"type": "enabled", "budget_tokens": 16000},
messages=[
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
},
{
"role": "assistant",
"content": [
{
"type": "thinking",
"thinking": "This is a nice number theory question. Let's think about it step by step...",
"signature": "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
},
{
"type": "text",
"text": "Yes, there are infinitely many prime numbers p such that p mod 4 = 3...",
},
],
},
{"role": "user", "content": "Can you write a formal proof?"},
],
)
print(response.json()){ "input_tokens": 88 }Подсчёт токенов поддерживает PDF с теми же ограничениями, что и API Messages.
import base64
import anthropic
client = anthropic.Anthropic()
with open("document.pdf", "rb") as pdf_file:
pdf_base64 = base64.standard_b64encode(pdf_file.read()).decode("utf-8")
response = client.messages.count_tokens(
model="claude-opus-4-7",
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": pdf_base64,
},
},
{"type": "text", "text": "Please summarize this document."},
],
}
],
)
print(response.json()){ "input_tokens": 2188 }Подсчёт токенов бесплатен, но подлежит ограничениям на количество запросов в минуту в зависимости от вашего уровня использования. Если вам нужны более высокие ограничения, свяжитесь с отделом продаж через Claude Console.
| Уровень использования | Запросов в минуту (RPM) |
|---|---|
| 1 | 100 |
| 2 | 2,000 |
| 3 | 4,000 |
| 4 | 8,000 |
Подсчёт токенов и создание сообщений имеют отдельные и независимые ограничения частоты запросов. Использование одного не учитывается в отношении ограничений другого.
Was this page helpful?