计算消息中的令牌数
Parameters
messages: Iterable[BetaMessageParam]Input messages.
Input messages.
Our models are trained to operate on alternating user and assistant conversational turns. When creating a new Message, you specify the prior conversational turns with the messages parameter, and the model then generates the next Message in the conversation. Consecutive user or assistant turns in your request will be combined into a single turn.
Each input message must be an object with a role and content. You can specify a single user-role message, or you can include multiple user and assistant messages.
If the final message uses the assistant role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response. This is called prefill. On models that don't support prefill, creating a message that ends with a partial assistant response returns a 400 error. See Prefill not supported.
Example with a single user message:
[{"role": "user", "content": "Hello, Claude"}]Example with multiple conversational turns:
[
{"role": "user", "content": "Hello there."},
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{"role": "user", "content": "Can you explain LLMs in plain English?"},
]Example with a partially-filled response from Claude, for models that support prefill:
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("},
]Each input message content may be either a single string or an array of content blocks, where each block has a specific type. Using a string for content is shorthand for an array of one content block of type "text". The following input messages are equivalent:
{"role": "user", "content": "Hello, Claude"}{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}See input examples.
Note that if you want to include a system prompt, you can use the top-level system parameter.
There is a limit of 100,000 messages in a single request.
class BetaUserMessageParam: content; role
content: BetaMessageContentParam
class BetaAssistantMessageParam: content; role
content: BetaMessageContentParam
class BetaSystemMessageParam: role; clear_at; content; output_config
model: ModelParamThe model that will complete your prompt.
The model that will complete your prompt.
See models for additional details and options.
billing_policy: Optional[BetaBillingPolicyParam]Declares which organization is billed when this body is sent to /v1/messages. Accepted here so that you can count the tokens of the exact body you will send, and otherwise ignored: counting tokens bills nobody, so no user profile is required.
Declares which organization is billed when this body is sent to /v1/messages. Accepted here so that you can count the tokens of the exact body you will send, and otherwise ignored: counting tokens bills nobody, so no user profile is required.
bill_to: Optional[BetaBillTo]Who is billed. self, the default, bills your organization, as if billing_policy were omitted. user_profile bills the customer behind the user profile the request names; if that customer has not linked an Anthropic organization to the profile, or has not allowed your organization to bill it, the request is rejected rather than billed to you.
Who is billed. self, the default, bills your organization, as if billing_policy were omitted. user_profile bills the customer behind the user profile the request names; if that customer has not linked an Anthropic organization to the profile, or has not allowed your organization to bill it, the request is rejected rather than billed to you.
cache_control: Optional[BetaCacheControlEphemeralParam]Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request.
Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request.
ttl: Optional[Literal["5m", "1h"]]The time-to-live for the cache control breakpoint.
The time-to-live for the cache control breakpoint.
This may be one the following values:
5m: 5 minutes1h: 1 hour
Defaults to 5m. See prompt caching pricing for details.
compaction: Optional[BetaCompactionConfigParam]Compaction configuration.
Compaction configuration.
When set on POST /v1/messages, the request is a compaction request: the conversation in messages is summarized and the response holds only the resulting compaction block (stop_reason "compaction"), which later requests send first in messages in place of the messages it summarizes. POST /v1/messages/count_tokens accepts this parameter and ignores it: the count it returns is for the conversation in messages as sent. Cannot be combined with context_management.
instructions: Optional[str]Replaces the server's default summarization prompt for this request. An empty or whitespace-only value counts as absent.
Replaces the server's default summarization prompt for this request. An empty or whitespace-only value counts as absent.
context_management: Optional[BetaContextManagementConfigParam]Context management configuration.
Context management configuration.
This allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not.
mcp_servers: Optional[Iterable[BetaRequestMCPServerURLDefinitionParam]]MCP servers to be utilized in this request
MCP servers to be utilized in this request
tool_configuration: Optional[BetaRequestMCPServerToolConfigurationParam]
output_config: Optional[BetaOutputConfigParam]Configuration options for the model's output, such as the output format.
Configuration options for the model's output, such as the output format.
speed: Optional[Literal["standard", "fast"]]The inference speed mode for this request. "fast" enables high output-tokens-per-second inference.
The inference speed mode for this request. "fast" enables high output-tokens-per-second inference.
Some models require the fast-mode-2026-02-01 beta header for any speed value. See fast mode for which models.
system: Optional[Union[str, Iterable[BetaTextBlockParam]]]System prompt.
System prompt.
A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our guide to system prompts.
Iterable[BetaTextBlockParam]
text: str
cache_control: Optional[BetaCacheControlEphemeralParam]Create a cache control breakpoint at this content block.
Create a cache control breakpoint at this content block.
ttl: Optional[Literal["5m", "1h"]]The time-to-live for the cache control breakpoint.
The time-to-live for the cache control breakpoint.
This may be one the following values:
5m: 5 minutes1h: 1 hour
Defaults to 5m. See prompt caching pricing for details.
citations: Optional[Iterable[BetaTextCitationParam]]
class BetaCitationCharLocationParam: type: "char_location"; cited_text; document_index; ... # 3 more
document_index: int
document_title: Optional[str]
start_char_index: int
class BetaCitationPageLocationParam: type: "page_location"; cited_text; document_index; ... # 3 more
document_index: int
document_title: Optional[str]
start_page_number: int
class BetaCitationContentBlockLocationParam: type: "content_block_location"; cited_text; document_index; ... # 3 more
cited_text: strThe full text of the cited block range, concatenated.
The full text of the cited block range, concatenated.
Always equals the contents of content[start_block_index:end_block_index] joined together. The text block is the minimal citable unit; this field is never a substring of a single block. Not counted toward output tokens, and not counted toward input tokens when sent back in subsequent turns.
document_index: int
document_title: Optional[str]
end_block_index: intExclusive 0-based end index of the cited block range in the source's content array.
Exclusive 0-based end index of the cited block range in the source's content array.
Always greater than start_block_index; a single-block citation has end_block_index = start_block_index + 1.
start_block_index: int0-based index of the first cited block in the source's content array.
0-based index of the first cited block in the source's content array.
class BetaCitationWebSearchResultLocationParam: type: "web_search_result_location"; cited_text; encrypted_index; ... # 2 more
title: Optional[str]
url: str
class BetaCitationSearchResultLocationParam: type: "search_result_location"; cited_text; end_block_index; ... # 4 more
cited_text: strThe full text of the cited block range, concatenated.
The full text of the cited block range, concatenated.
Always equals the contents of content[start_block_index:end_block_index] joined together. The text block is the minimal citable unit; this field is never a substring of a single block. Not counted toward output tokens, and not counted toward input tokens when sent back in subsequent turns.
end_block_index: intExclusive 0-based end index of the cited block range in the source's content array.
Exclusive 0-based end index of the cited block range in the source's content array.
Always greater than start_block_index; a single-block citation has end_block_index = start_block_index + 1.
search_result_index: int0-based index of the cited search result among all search_result content blocks in the request, in the order they appear across messages and tool results.
0-based index of the cited search result among all search_result content blocks in the request, in the order they appear across messages and tool results.
Counted separately from document_index; server-side web search results are not included in this count.
start_block_index: int0-based index of the first cited block in the source's content array.
0-based index of the first cited block in the source's content array.
thinking: Optional[BetaThinkingConfigParam]Configuration for Claude's thinking.
Configuration for Claude's thinking.
With {"type": "adaptive"}, Claude decides when and how much to think. With {"type": "enabled"} (manual extended thinking), you set a budget_tokens of at least 1,024. Thinking tokens count toward your max_tokens limit.
Which type values are accepted, and what happens when you omit thinking, depend on the model. See thinking for each model's behavior.
tool_choice: Optional[BetaToolChoiceParam]How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
tools: Optional[Iterable[Tool]]Definitions of tools that the model may use.
Definitions of tools that the model may use.
If you include tools in your API request, the model may return tool_use content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using tool_result content blocks.
There are two types of tools: client tools and server tools. The behavior described below applies to client tools. For server tools, see their individual documentation as each has its own behavior (e.g., the web search tool).
Each tool definition includes:
name: Name of the tool.description: Optional, but strongly-recommended description of the tool.input_schema: JSON schema for the toolinputshape that the model will produce intool_useoutput content blocks.
For example, if you defined tools as:
[
{
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}
]And then asked the model "What's the S&P 500 at today?", the model might produce tool_use content blocks in the response like this:
[
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_stock_price",
"input": { "ticker": "^GSPC" }
}
]You might then run your get_stock_price tool with {"ticker": "^GSPC"} as an input, and return the following back to the model in a subsequent user message:
[
{
"type": "tool_result",
"tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"content": "259.75 USD"
}
]Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.
See our guide for more details.
class BetaToolParam: type; input_schema; name; ... # 7 more
class BetaToolBash20241022: type: "bash_20241022"; name; allowed_callers; ... # 4 more
class BetaToolBash20250124: type: "bash_20250124"; name; allowed_callers; ... # 4 more
class BetaCodeExecutionTool20250522: type: "code_execution_20250522"; name; allowed_callers; ... # 3 more
class BetaCodeExecutionTool20250825: type: "code_execution_20250825"; name; allowed_callers; ... # 3 more
class BetaCodeExecutionTool20260120: type: "code_execution_20260120"; name; allowed_callers; ... # 3 moreA tools entry for the code execution tool, version code_execution_20260120. It adds REPL state persistence to version code_execution_20250825.
A tools entry for the code execution tool, version code_execution_20260120. It adds REPL state persistence to version code_execution_20250825.
REPL state persistence applies with programmatic tool calling. With it, the Python interpreter state, such as variable bindings, persists across requests that reuse the container.
See the code execution tool guide to learn what each tool version adds.
class BetaCodeExecutionTool20260521: type: "code_execution_20260521"; name; allowed_callers; ... # 3 moreCode execution tool with REPL state persistence.
Code execution tool with REPL state persistence.
class BetaBrowserToolset20260801: type: "browser_toolset_20260801"; cache_control; configsThe browser toolset: a single tools[] entry (carrying no
name) that declares the browser tool family. The model is served
the family's tool with any members disabled via configs removed
from its schema.
The browser toolset: a single tools[] entry (carrying no
name) that declares the browser tool family. The model is served
the family's tool with any members disabled via configs removed
from its schema.
cache_control: Optional[BetaCacheControlEphemeral]Create a cache control breakpoint at this content block.
Create a cache control breakpoint at this content block.
ttl: Optional[Literal["5m", "1h"]]The time-to-live for the cache control breakpoint.
The time-to-live for the cache control breakpoint.
This may be one the following values:
5m: 5 minutes1h: 1 hour
Defaults to 5m. See prompt caching pricing for details.
configs: Optional[BetaBrowserToolsetConfigs]Sparse per-member overrides, keyed by member name. Absent, null, and {} are equivalent; a member's defaults apply wherever its key is absent.
Sparse per-member overrides, keyed by member name. Absent, null, and {} are equivalent; a member's defaults apply wherever its key is absent.
class BetaToolComputerUse20241022: type: "computer_20241022"; display_height_px; display_width_px; ... # 7 more
class BetaMemoryTool20250818: type: "memory_20250818"; name; allowed_callers; ... # 4 more
class BetaToolComputerUse20250124: type: "computer_20250124"; display_height_px; display_width_px; ... # 7 more
class BetaToolTextEditor20241022: type: "text_editor_20241022"; name; allowed_callers; ... # 4 more
class BetaToolComputerUse20251124: type: "computer_20251124"; display_height_px; display_width_px; ... # 8 more
class BetaComputerToolset20260801: type: "computer_toolset_20260801"; cache_control; configsThe computer toolset: a single tools[] entry (carrying no
name) that declares the computer tool family. The model is
served the family's tool with any members disabled via configs
removed from its schema. Every member is enabled by default, zoom
included. The single-tool options display_number and
enable_zoom are not fields of a toolset entry — it carries only
type, configs, and cache_control; zoom is controlled
via configs.zoom.enabled.
The computer toolset: a single tools[] entry (carrying no
name) that declares the computer tool family. The model is
served the family's tool with any members disabled via configs
removed from its schema. Every member is enabled by default, zoom
included. The single-tool options display_number and
enable_zoom are not fields of a toolset entry — it carries only
type, configs, and cache_control; zoom is controlled
via configs.zoom.enabled.
cache_control: Optional[BetaCacheControlEphemeral]Create a cache control breakpoint at this content block.
Create a cache control breakpoint at this content block.
ttl: Optional[Literal["5m", "1h"]]The time-to-live for the cache control breakpoint.
The time-to-live for the cache control breakpoint.
This may be one the following values:
5m: 5 minutes1h: 1 hour
Defaults to 5m. See prompt caching pricing for details.
configs: Optional[BetaComputerToolsetConfigs]Sparse per-member overrides, keyed by member name. Absent, null, and {} are equivalent; a member's defaults apply wherever its key is absent.
Sparse per-member overrides, keyed by member name. Absent, null, and {} are equivalent; a member's defaults apply wherever its key is absent.
class BetaToolTextEditor20250124: type: "text_editor_20250124"; name; allowed_callers; ... # 4 more
class BetaToolTextEditor20250429: type: "text_editor_20250429"; name; allowed_callers; ... # 4 more
class BetaToolTextEditor20250728: type: "text_editor_20250728"; name; allowed_callers; ... # 5 more
class BetaWebSearchTool20250305: type: "web_search_20250305"; name; allowed_callers; ... # 7 more
class BetaWebFetchTool20250910: type: "web_fetch_20250910"; name; allowed_callers; ... # 9 more
class BetaWebSearchTool20260209: type: "web_search_20260209"; name; allowed_callers; ... # 7 more
class BetaWebFetchTool20260209: type: "web_fetch_20260209"; name; allowed_callers; ... # 9 more
class BetaWebFetchTool20260309: type: "web_fetch_20260309"; name; allowed_callers; ... # 10 moreWeb fetch tool with use_cache parameter for bypassing cached content.
Web fetch tool with use_cache parameter for bypassing cached content.
class BetaWebSearchTool20260318: type: "web_search_20260318"; name; allowed_callers; ... # 8 more
class BetaWebFetchTool20260318: type: "web_fetch_20260318"; name; allowed_callers; ... # 11 more
class BetaAdvisorTool20260301: type: "advisor_20260301"; model; name; ... # 7 more
class BetaToolSearchToolBm25_20251119: type; name; allowed_callers; ... # 3 more
class BetaToolSearchToolRegex20251119: type; name; allowed_callers; ... # 3 more
class BetaMCPToolset: type: "mcp_toolset"; mcp_server_name; cache_control; ... # 3 moreConfiguration for a group of tools from an MCP server.
Configuration for a group of tools from an MCP server.
Allows configuring enabled status and defer_loading for all tools from an MCP server, with optional per-tool overrides.
betas: Optional[List[AnthropicBetaParam]]Header parameterOptional header to specify the beta version(s) you want to use.
Optional header to specify the beta version(s) you want to use.
"message-batches-2024-09-24"Deprecated
"prompt-caching-2024-07-31"Deprecated
"pdfs-2024-09-25"Deprecated
"token-counting-2024-11-01"Deprecated
"token-efficient-tools-2025-02-19"Deprecated
"files-api-2025-04-14"Deprecated
"extended-cache-ttl-2025-04-11"Deprecated
"skills-2025-10-02"Deprecated
"cache-diagnosis-2026-04-07"Deprecated
"ce-user-management-2026-07-13"Deprecated
The user profile ID to attribute this request to. Use when acting on behalf of a party other than your organization.
workspace_id: Optional[str]Header parameterOptional header to select the Workspace for this request. The value is a Workspace ID (for example, wrkspc_011CZkZaBF1tNoB5wlCeusgy).
Optional header to select the Workspace for this request. The value is a Workspace ID (for example, wrkspc_011CZkZaBF1tNoB5wlCeusgy).
Only needed for credentials that can act on more than one Workspace. A credential that belongs to a specific Workspace may omit it; if sent, it must match that Workspace.
Returns
class BetaMessageTokensCount: context_management; input_tokens
context_management: Optional[BetaCountTokensContextManagementResponse]Information about context management applied to the message.
Information about context management applied to the message.
The original token count before context management was applied
The total number of tokens across the provided list of messages, system prompt, and tools.
Errors
Any method can also return the general HTTP errors.
The tools available after a message exceed a limit on their number or their size.
The API key belongs to the Claude Code workspace, and the user who created it is no longer a member of the organization or of that workspace.
messages holds more than one compaction block with content. Send only the block the conversation returned last.
The compaction block is not the first block of the conversation, or is in a system message.
The compaction block's content differs from the text its signature recorded.
messages holds no user or assistant content to summarize or adopt.
The compaction block's signature does not verify.
The compaction block's tool_changes differs from what was returned with the block.
Anthropic has disabled the organization for trust and safety reasons. An organization disabled for any other reason, such as billing, does not get this code. appeal_url, when present, is where the organization can appeal.
The request body is not valid for its Content-Encoding.
The request's Content-Encoding is not supported.
A tool made available in messages takes a name that an available tool of another kind, or of another MCP server, already holds.
A tool change or MCP tool listing references a tool or MCP server that is not defined at that position in the conversation.
The compressed request body exceeds the request size limit once decoded.
The organization has crossed the monthly API usage threshold of its API tier.
The compaction could not be completed for a transient server reason. Retry the request.
import os
from anthropic import Anthropic
client = Anthropic(
api_key=os.environ.get(
"ANTHROPIC_API_KEY"
), # This is the default and can be omitted
)
beta_message_tokens_count = client.beta.messages.count_tokens(
messages=[
{
"content": "Hello, world",
"role": "user",
}
],
model="claude-opus-5-5",
)
print(beta_message_tokens_count.context_management){
"context_management": {
"original_input_tokens": 0
},
"input_tokens": 2095
}Returns Examples
{
"context_management": {
"original_input_tokens": 0
},
"input_tokens": 2095
}