---
title: 토큰 카운팅
url: https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/token-counting
description: Claude에 메시지를 보내기 전에 메시지의 토큰 수를 계산합니다. 토큰 수를 사용하여 속도 제한과 비용을 관리하고, 모델 라우팅 결정을 내리고, 프롬프트를 목표 길이에 맞추세요.
featureMetadata:
  status: stable
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://code.saschaberens.de/_h/platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). 요청을 보내기 전에 토큰 수를 계산합니다.
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Amazon Bedrock: stable
    Amazon Bedrock (bedrock-runtime): stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

“Token counting”(토큰 카운팅)을 사용하면 Claude에 메시지를 보내기 전에 메시지의 토큰 수를 확인할 수 있습니다. 이를 통해 프롬프트와 사용량에 대해 정보에 기반한 결정을 내릴 수 있습니다. 토큰 카운팅을 사용하면 다음을 수행할 수 있습니다:

* “rate limit”(속도 제한)과 비용을 사전에 관리
* 현명한 모델 라우팅 결정
* 프롬프트를 특정 길이로 최적화

***

## 메시지 토큰을 계산하는 방법

[토큰 카운팅](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/messages/count_tokens) 엔드포인트는 메시지 생성과 동일한 구조화된 입력 목록을 받으며, 시스템 프롬프트, [도구](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/tool-use/overview), [이미지](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/vision), [PDF](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/pdf-support)를 지원합니다. 응답에는 총 [입력 토큰](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/messages/count_tokens#message_tokens_count.input_tokens) 수가 포함됩니다.

(See the `messages/count_tokens` method in [the API reference](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/messages/count_tokens).)

이 엔드포인트는 Messages API가 허용하는 일부 입력에 대해 `invalid_request_error`를 반환합니다:

* 웹 검색, 웹 가져오기, 코드 실행, 도구 검색과 같은 [서버 도구](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/tool-use/server-tools) ([어드바이저 도구](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/tool-use/advisor-tool)를 제외한 모든 서버 도구)
* [MCP 커넥터](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/mcp-connector)
* `url` 또는 `file` 소스를 사용하는 `image` 또는 `document` 블록

이미지와 PDF의 토큰 수를 계산하려면 base64로 전송하세요. 서버 도구 또는 MCP 서버를 사용하는 요청의 경우, Messages API 응답의 [`usage`](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/messages/create#message.usage) 객체에 사용된 토큰이 보고됩니다.

<Note>
  토큰 수는 **추정치**입니다. 경우에 따라 메시지를 생성할 때 실제로 사용되는 입력 토큰 수가 약간 다를 수 있습니다.

  토큰 수에는 시스템 최적화를 위해 Anthropic이 자동으로 추가한 토큰이 포함될 수 있습니다. **시스템이 추가한 토큰에 대해서는 요금이 청구되지 않습니다**. 청구는 사용자의 콘텐츠만 반영합니다.
</Note>

### 지원 모델

모든 [활성 모델](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/models/overview)이 토큰 카운팅을 지원합니다.

<Note>
  Claude 4.7 이상 모델과 Claude Mythos Preview는 새로운 토크나이저를 사용합니다. 동일한 입력 텍스트가 이전 모델보다 약 30퍼센트 더 많은 토큰을 생성합니다. 정확한 증가량은 콘텐츠와 워크로드 형태에 따라 다릅니다. 이전 모델에서 측정한 토큰 수를 재사용하지 말고, 사용하려는 모델을 기준으로 프롬프트를 다시 계산하세요.
</Note>

### 기본 메시지의 토큰 계산

<CodeGroup>
  ```bash cURL
  curl https://code.saschaberens.de/_h/api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "system": "You are a scientist",
      "messages": [{
        "role": "user",
        "content": "Hello, Claude"
      }]
    }'
  ```

  ```bash CLI
  ant messages count-tokens \
    --model claude-opus-5-5 \
    --system "You are a scientist" \
    --message '{role: user, content: "Hello, Claude"}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      system="You are a scientist",
      messages=[{"role": "user", "content": "Hello, Claude"}],
  )

  print(response.json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    system: "You are a scientist",
    messages: [
      {
        role: "user",
        content: "Hello, Claude"
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      System = "You are a scientist",
      Messages = [new UserMessageParam { Content = "Hello, Claude" }]
  };

  var response = await client.Messages.CountTokens(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	System: anthropic.MessageCountTokensParamsSystemUnion{
  		OfString: anthropic.String("You are a scientist"),
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...

  public class CountTokensExample {

      public static void main(String[] args) {
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .system("You are a scientist")
              .addUserMessage("Hello, Claude")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
      }
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          ['role' => 'user', 'content' => 'Hello, Claude']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      system: 'You are a scientist',
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    system: "You are a scientist",
    messages: [
      { role: "user", content: "Hello, Claude" }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 14 }
```

### 도구가 포함된 메시지의 토큰 계산

<Note>
  토큰 카운팅은 클라이언트 도구와 [어드바이저 도구](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/tool-use/advisor-tool)를 지원합니다. 그 외의 [서버 도구](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/agents-and-tools/tool-use/server-tools)를 포함하는 요청은 오류를 반환합니다. 어드바이저 도구의 경우, 토큰 수는 실행자의 첫 번째 샘플링 호출만 포함합니다.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://code.saschaberens.de/_h/api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "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?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  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?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      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())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    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?" }]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Collections.Generic;
  using System.Text.Json;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Tools =
      [
          new MessageCountTokensTool(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                  },
                  Required = ["location"],
              },
          }),
      ],
      Messages = [new UserMessageParam { Content = "What's the weather like in San Francisco?" }]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Tools: []anthropic.MessageCountTokensToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  				},
  				Required: []string{"location"},
  			},
  		}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  jsonData, _ := json.MarshalIndent(response, "", "  ")
  fmt.Println(string(jsonData))
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          InputSchema schema = InputSchema.builder()
              .properties(
                  JsonValue.from(
                      Map.of(
                          "location",
                          Map.of(
                              "type",
                              "string",
                              "description",
                              "The city and state, e.g. San Francisco, CA"
                          )
                      )
                  )
              )
              .putAdditionalProperty("required", JsonValue.from(List.of("location")))
              .build();

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addTool(
                  Tool.builder()
                      .name("get_weather")
                      .description("Get the current weather in a given location")
                      .inputSchema(schema)
                      .build()
              )
              .addUserMessage("What's the weather like in San Francisco?")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: Model::CLAUDE_OPUS_5_5,
      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']
              ]
          ]
      ],
  );

  echo json_encode($response, JSON_PRETTY_PRINT);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    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?" }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 403 }
```

### 이미지가 포함된 메시지의 토큰 계산

<CodeGroup>
  ```bash cURL
  #!/bin/sh

  IMAGE_BASE64=$(curl -s "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg" | base64 | tr -d '\n')

  curl https://code.saschaberens.de/_h/api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d @- <<EOF
  {
    "model": "claude-opus-5-5",
    "messages": [
      {"role": "user", "content": [
        {"type": "image", "source": {
          "type": "base64",
          "media_type": "image/jpeg",
          "data": "$IMAGE_BASE64"
        }},
        {"type": "text", "text": "Describe this image"}
      ]}
    ]
  }
  EOF
  ```

  ```bash CLI
  curl -s "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg" \
    -o ./vision-example.jpg

  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  messages:
    - role: user
      content:
        - type: image
          source:
            type: base64
            media_type: image/jpeg
            data: "@./vision-example.jpg"
        - type: text
          text: Describe this image
  YAML
  ```

  ```python Python
  import base64
  import httpx2

  image_url = "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg"
  image_media_type = "image/jpeg"
  image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")

  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      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())
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const imageUrl = "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg";
  const imageMediaType = "image/jpeg";
  const imageArrayBuffer = await (await fetch(imageUrl)).arrayBuffer();
  const imageData = Buffer.from(imageArrayBuffer).toString("base64");

  const response = await anthropic.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "image",
            source: {
              type: "base64",
              media_type: imageMediaType,
              data: imageData
            }
          },
          {
            type: "text",
            text: "Describe this image"
          }
        ]
      }
    ]
  });
  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Collections.Generic;
  using System.Net.Http;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  string imageUrl = "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg";

  using HttpClient httpClient = new();
  byte[] imageBytes = await httpClient.GetByteArrayAsync(imageUrl);
  string imageData = Convert.ToBase64String(imageBytes);

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Messages =
      [
          new UserMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new ImageBlockParam(
                      new ImageBlockParamSource(new Base64ImageSource()
                      {
                          Data = imageData,
                          MediaType = MediaType.ImageJpeg,
                      })
                  )),
                  new ContentBlockParam(new TextBlockParam("Describe this image")),
              },
          }
      ]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  imageURL := "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg"

  req, err := http.NewRequest("GET", imageURL, nil)
  if err != nil {
  	log.Fatal(err)
  }
  req.Header.Set("User-Agent", "AnthropicDocsBot/1.0")

  resp, err := http.DefaultClient.Do(req)
  if err != nil {
  	log.Fatal(err)
  }
  defer resp.Body.Close()

  imageBytes, err := io.ReadAll(resp.Body)
  if err != nil {
  	log.Fatal(err)
  }
  imageData := base64.StdEncoding.EncodeToString(imageBytes)

  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewImageBlockBase64("image/jpeg", imageData),
  			anthropic.NewTextBlock("Describe this image"),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.Base64ImageSource;
  // ...
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          String imageUrl =
              "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg";
          String imageMediaType = "image/jpeg";

          HttpClient httpClient = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(imageUrl))
              .build();
          byte[] imageBytes = httpClient
              .send(request, HttpResponse.BodyHandlers.ofByteArray())
              .body();
          String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);

          ContentBlockParam imageBlock = ContentBlockParam.ofImage(
              ImageBlockParam.builder()
                  .source(
                      Base64ImageSource.builder()
                          .mediaType(Base64ImageSource.MediaType.IMAGE_JPEG)
                          .data(imageBase64)
                          .build()
                  )
                  .build()
          );

          ContentBlockParam textBlock = ContentBlockParam.ofText(
              TextBlockParam.builder()
                  .text("Describe this image")
                  .build()
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addUserMessageOfContentBlockParams(List.of(imageBlock, textBlock))
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $imageUrl = 'https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg';
  $imageMediaType = 'image/jpeg';
  $imageData = base64_encode(file_get_contents($imageUrl));

  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'image',
                      'source' => [
                          'type' => 'base64',
                          'media_type' => $imageMediaType,
                          'data' => $imageData
                      ]
                  ],
                  ['type' => 'text', 'text' => 'Describe this image']
              ]
          ]
      ],
      model: 'claude-opus-5-5',
  );
  print_r($response);
  ```

  ```ruby Ruby
  require "base64"
  require "net/http"

  image_url = "https://code.saschaberens.de/_h/platform.claude.com/docs/images/vision-example.jpg"
  image_media_type = "image/jpeg"

  uri = URI(image_url)
  image_data = Base64.strict_encode64(Net::HTTP.get(uri))

  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "image",
            source: {
              type: "base64",
              media_type: image_media_type,
              data: image_data
            }
          },
          { type: "text", text: "Describe this image" }
        ]
      }
    ]
  )
  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 1028 }
```

[`"oversized_image": "error"`](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/vision-coordinates#oversized-image-error)를 설정한 임베디드 이미지 블록은 Messages API가 거부하는 것과 정확히 동일하게 카운트 시점에 거부됩니다.

### 사고가 포함된 메시지의 토큰 계산

<Note>
  자세한 내용은 [사고와 컨텍스트 윈도우](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/thinking#thinking-and-the-context-window)를 참조하세요.

  * **이전** 어시스턴트 턴의 사고 블록은 [이전 턴을 모두 유지하는](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/thinking#thinking-block-preservation-by-model) 모델에서는 입력 토큰에 포함됩니다. 마지막 턴만 유지하는 모델에서는 API가 이를 제거하므로 입력 토큰에 포함되지 **않습니다**.
  * **현재** 어시스턴트 턴의 사고는 입력 토큰에 **포함됩니다**.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://code.saschaberens.de/_h/api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "thinking": {
        "type": "adaptive"
      },
      "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. Lets 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?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  thinking:
    type: adaptive
  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. Lets 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?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      thinking={"type": "adaptive"},
      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())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    thinking: { type: "adaptive" },
    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?"
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Threading.Tasks;
  using System.Collections.Generic;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Thinking = new ThinkingConfigAdaptive(),
      Messages =
      [
          new UserMessageParam
          {
              Content = "Are there an infinite number of prime numbers such that n mod 4 == 3?"
          },
          new AssistantMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new ThinkingBlockParam()
                  {
                      Thinking = "This is a nice number theory question. Let's think about it step by step...",
                      Signature = "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
                  }),
                  new ContentBlockParam(new TextBlockParam("Yes, there are infinitely many prime numbers p such that p mod 4 = 3...")),
              },
          },
          new UserMessageParam { Content = "Can you write a formal proof?" }
      ]
  };

  var response = await client.Messages.CountTokens(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  thinkingBlock := anthropic.NewThinkingBlock(
  	"EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
  	"This is a nice number theory question. Let's think about it step by step...",
  )

  textBlock := anthropic.NewTextBlock(
  	"Yes, there are infinitely many prime numbers p such that p mod 4 = 3...",
  )

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Thinking: anthropic.ThinkingConfigParamUnion{
  		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Are there an infinite number of prime numbers such that n mod 4 == 3?")),
  		anthropic.NewAssistantMessage(thinkingBlock, textBlock),
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Can you write a formal proof?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("%+v\n", response)
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
  import com.anthropic.models.messages.ThinkingBlockParam;
  import com.anthropic.models.messages.ThinkingConfigAdaptive;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          List<ContentBlockParam> assistantBlocks = List.of(
              ContentBlockParam.ofThinking(
                  ThinkingBlockParam.builder()
                      .thinking(
                          "This is a nice number theory question. Let's think about it step by step..."
                      )
                      .signature(
                          "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV..."
                      )
                      .build()
              ),
              ContentBlockParam.ofText(
                  TextBlockParam.builder()
                      .text("Yes, there are infinitely many prime numbers p such that p mod 4 = 3...")
                      .build()
              )
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .thinking(ThinkingConfigAdaptive.builder().build())
              .addUserMessage("Are there an infinite number of prime numbers such that n mod 4 == 3?")
              .addAssistantMessageOfContentBlockParams(assistantBlocks)
              .addUserMessage("Can you write a formal proof?")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      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?'
          ]
      ],
      model: 'claude-opus-5-5',
      thinking: ['type' => 'adaptive'],
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: "claude-opus-5-5",
    thinking: {
      type: "adaptive"
    },
    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?"
      }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 88 }
```

### PDF가 포함된 메시지의 토큰 계산

<Note>
  토큰 카운팅은 Messages API와 동일한 [PDF 요구 사항](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/pdf-support#check-pdf-requirements)을 충족하는 base64 인코딩 PDF를 지원합니다. 이 엔드포인트는 `url` 또는 `file` 문서 소스를 지원하지 않습니다.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://code.saschaberens.de/_h/api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d @- <<EOF
  {
    "model": "claude-opus-5-5",
    "messages": [{
      "role": "user",
      "content": [
        {
          "type": "document",
          "source": {
            "type": "base64",
            "media_type": "application/pdf",
            "data": "$PDF_BASE64"
          }
        },
        {
          "type": "text",
          "text": "Please summarize this document."
        }
      ]
    }]
  }
  EOF
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  messages:
    - role: user
      content:
        - type: document
          source:
            type: base64
            media_type: application/pdf
            data: "@./document.pdf"
        - type: text
          text: Please summarize this document.
  YAML
  ```

  ```python Python
  import base64
  import anthropic

  client = anthropic.Anthropic()

  with open("/path/to/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-5-5",
      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())
  ```

  ```typescript TypeScript
  import { readFile } from "node:fs/promises";

  const client = new Anthropic();

  const pdfBase64 = await readFile("/path/to/document.pdf", { encoding: "base64" });

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "document",
            source: {
              type: "base64",
              media_type: "application/pdf",
              data: pdfBase64
            }
          },
          {
            type: "text",
            text: "Please summarize this document."
          }
        ]
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.IO;
  using System.Threading.Tasks;
  using System.Collections.Generic;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  byte[] pdfBytes = await File.ReadAllBytesAsync("/path/to/document.pdf");
  string pdfBase64 = Convert.ToBase64String(pdfBytes);

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Messages =
      [
          new UserMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new DocumentBlockParam(
                      new DocumentBlockParamSource(new Base64PdfSource()
                      {
                          Data = pdfBase64,
                      })
                  )),
                  new ContentBlockParam(new TextBlockParam("Please summarize this document.")),
              },
          }
      ]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  client := anthropic.NewClient()

  pdfBytes, err := os.ReadFile("/path/to/document.pdf")
  if err != nil {
  	log.Fatal(err)
  }
  pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{
  				Data: pdfBase64,
  			}),
  			anthropic.NewTextBlock("Please summarize this document."),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.Base64PdfSource;
  // ...
  import com.anthropic.models.messages.DocumentBlockParam;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          byte[] fileBytes = Files.readAllBytes(Path.of("/path/to/document.pdf"));
          String pdfBase64 = Base64.getEncoder().encodeToString(fileBytes);

          ContentBlockParam documentBlock = ContentBlockParam.ofDocument(
              DocumentBlockParam.builder()
                  .source(Base64PdfSource.builder()
                      .data(pdfBase64)
                      .build())
                  .build()
          );

          ContentBlockParam textBlock = ContentBlockParam.ofText(
              TextBlockParam.builder()
                  .text("Please summarize this document.")
                  .build()
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addUserMessageOfContentBlockParams(List.of(documentBlock, textBlock))
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $pdfBase64 = base64_encode(file_get_contents('/path/to/document.pdf'));

  $response = $client->messages->countTokens(
      messages: [
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'document',
                      'source' => [
                          'type' => 'base64',
                          'media_type' => 'application/pdf',
                          'data' => $pdfBase64
                      ]
                  ],
                  [
                      'type' => 'text',
                      'text' => 'Please summarize this document.'
                  ]
              ]
          ]
      ],
      model: 'claude-opus-5-5',
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  require "base64"

  client = Anthropic::Client.new

  pdf_base64 = Base64.strict_encode64(File.binread("/path/to/document.pdf"))

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "document",
            source: {
              type: "base64",
              media_type: "application/pdf",
              data: pdf_base64
            }
          },
          {
            type: "text",
            text: "Please summarize this document."
          }
        ]
      }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 2188 }
```

***

## Claude Fable 및 Claude Mythos 모델의 토큰 수

Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5는 Claude Opus 4.7과 함께 도입된 토크나이저를 공유합니다. 프롬프트는 여섯 모델 모두에서 동일하게 계산되며, Claude Opus 4.7 이전 모델보다 약 30퍼센트 더 높게 계산됩니다(정확한 증가량은 콘텐츠에 따라 다릅니다). 토큰 카운팅 엔드포인트는 전달한 `model`의 토크나이저를 기준으로 계산합니다. 워크로드에 대한 차이를 측정하려면 동일한 요청을 현재 모델로 한 번, 이동하려는 모델로 한 번 계산하세요. 그런 다음 두 `input_tokens` 값을 비교하세요.

<Note>
  **청구 및 마이그레이션:** 이러한 모델의 사용량과 청구는 이 토크나이저의 토큰 수를 반영합니다. Claude Opus 4.7 이전 모델에서 마이그레이션할 때는 이전 모델에서 측정한 토큰 수를 재사용하여 비용이나 컨텍스트 윈도우 적합성을 추정하지 마세요. 사용하려는 `model` ID(예: `"claude-fable-5-2"`)로 프롬프트를 계산하세요.
</Note>

***

## 가격 및 속도 제한

토큰 카운팅은 **무료로 사용**할 수 있지만, [사용 등급](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/rate-limits#rate-limits)에 따른 분당 요청 수 속도 제한이 적용됩니다. 더 높은 한도가 필요한 경우 Claude Console의 [속도 제한](https://code.saschaberens.de/_h/platform.claude.com/usage/limits) 페이지에서 **티어 상향 요청**을 사용하세요.

| 사용 등급 | 분당 요청 수(RPM) |
| ----- | ----- |
| Start | 5,000 |
| Build | 10,000 |
| Scale | 20,000 |

<Note>
  토큰 카운팅과 메시지 생성은 별도의 독립적인 속도 제한을 가집니다. 한쪽의 사용량은 다른 쪽의 한도에 포함되지 않습니다.
</Note>

***

## FAQ

<AccordionGroup>
  <Accordion title="토큰 카운팅은 프롬프트 캐싱을 사용하나요?">
    아니요, 토큰 카운팅은 캐싱 로직을 사용하지 않고 추정치를 제공합니다. 토큰 카운팅 요청에 `cache_control` 블록을 제공할 수는 있지만, “prompt caching”(프롬프트 캐싱)은 실제 메시지 생성 중에만 발생합니다.
  </Accordion>
</AccordionGroup>

***

## 다음 단계

<CardGroup cols={2}>
  <Card title="메시지 토큰 계산" icon="code" href="https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/messages/count_tokens">
    토큰 카운팅 엔드포인트에 대한 전체 API 레퍼런스를 읽어보세요.
  </Card>

  <Card title="컨텍스트 윈도우" icon="arrows-maximize" href="https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/context-windows">
    토큰 수를 사용하여 프롬프트를 모델의 컨텍스트 윈도우 내로 유지하세요.
  </Card>

  <Card title="속도 제한" icon="gauge" href="https://code.saschaberens.de/_h/platform.claude.com/docs/ko/api/rate-limits">
    요청을 보내기 전에 토큰 수를 확인하여 사용 등급 내로 유지하세요.
  </Card>

  <Card title="프롬프트 캐싱" icon="database" href="https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/prompt-caching">
    프롬프트 접두사를 캐싱하여 반복되는 프롬프트의 비용과 지연 시간을 줄이세요.
  </Card>
</CardGroup>

## 제공 여부

토큰 카운팅은(는) 모든 모델에서 사용 가능 상태이며 제로 데이터 보존 및 HIPAA 대비에 적격합니다.

### API 지원

#### [Messages API](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/build-with-claude/working-with-messages)

* 제공 여부: 사용 가능

| 상태 | 모델 |
| ----- | ----- |
| 사용 가능 | [모든 모델](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/models/overview) |

#### [Managed Agents](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/managed-agents/overview)

* 제공 여부: 사용 불가

### 데이터 처리

[데이터 처리 개요](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/manage-claude/api-and-data-retention#feature-eligibility)

| 항목 | 제로 데이터 보존 | HIPAA |
| ----- | ----- | ----- |
| 상태 | 적격([적용 모델](https://code.saschaberens.de/_h/platform.claude.com/docs/ko/manage-claude/api-and-data-retention#model-specific-data-retention-requirements) 제외) | 적격 |
| 세부 정보 | 요청을 보내기 전에 토큰 수를 계산합니다. | — |

적용 엔드포인트:

* `/v1/messages/count_tokens`
