计算消息中的令牌数
POST/v1/messages/count_tokens
Parameters
Returns
计算消息中的令牌数
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
$client = new Client(apiKey: 'my-anthropic-api-key');
$betaMessageTokensCount = $client->beta->messages->countTokens(
messages: [
[
'content' => 'Hello, world',
'role' => 'user',
'clearAt' => 'next_user_message',
'outputConfig' => ['effort' => 'low'],
],
],
model: Model::CLAUDE_OPUS_5,
cacheControl: ['type' => 'ephemeral', 'ttl' => '5m'],
compaction: ['type' => 'summarize', 'instructions' => 'instructions'],
contextManagement: [
'edits' => [
[
'type' => 'clear_tool_uses_20250919',
'clearAtLeast' => ['type' => 'input_tokens', 'value' => 0],
'clearToolInputs' => true,
'excludeTools' => ['string'],
'keep' => ['type' => 'tool_uses', 'value' => 0],
'trigger' => ['type' => 'input_tokens', 'value' => 1],
],
],
],
mcpServers: [
[
'name' => 'name',
'type' => 'url',
'url' => 'url',
'authorizationToken' => 'authorization_token',
'toolConfiguration' => ['allowedTools' => ['string'], 'enabled' => true],
],
],
outputConfig: [
'effort' => 'low',
'format' => ['schema' => ['foo' => 'bar'], 'type' => 'json_schema'],
'taskBudget' => ['total' => 1024, 'type' => 'tokens', 'remaining' => 0],
],
outputFormat: ['schema' => ['foo' => 'bar'], 'type' => 'json_schema'],
speed: 'standard',
system: [
[
'text' => 'Today\'s date is 2024-06-01.',
'type' => 'text',
'cacheControl' => ['type' => 'ephemeral', 'ttl' => '5m'],
'citations' => [
[
'citedText' => 'The grass is green. The sky is blue.',
'documentIndex' => 0,
'documentTitle' => 'x',
'endCharIndex' => 0,
'startCharIndex' => 0,
'type' => 'char_location',
],
],
],
],
thinking: [
'type' => 'adaptive',
'blockBinding' => [
'prefixMismatchBehavior' => BetaThinkingPrefixMismatchBehavior::ERROR
],
'display' => 'summarized',
],
toolChoice: ['type' => 'auto', 'disableParallelToolUse' => true],
tools: [
[
'inputSchema' => [
'type' => 'object',
'properties' => ['location' => 'bar', 'unit' => 'bar'],
'required' => ['location'],
],
'name' => 'name',
'allowedCallers' => ['direct'],
'cacheControl' => ['type' => 'ephemeral', 'ttl' => '5m'],
'deferLoading' => true,
'description' => 'Get the current weather in a given location',
'eagerInputStreaming' => true,
'inputExamples' => [['foo' => 'bar']],
'strict' => true,
'type' => 'custom',
],
],
betas: [AnthropicBeta::MESSAGE_BATCHES_2024_09_24],
userProfileID: 'anthropic-user-profile-id',
workspaceID: 'wrkspc_011CZkZaBF1tNoB5wlCeusgy',
);
var_dump($betaMessageTokensCount);Response 200
{
"context_management": {
"original_input_tokens": 0
},
"input_tokens": 2095
}Returns Examples
Response 200
{
"context_management": {
"original_input_tokens": 0
},
"input_tokens": 2095
}