> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixroute.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# トークン数の計算（Claude）

> リクエスト送信前のコスト見積もりのため、Claudeメッセージのトークン数を計算

## はじめに

Claudeメッセージのトークン数を計算し、リクエスト送信前のコスト見積もりに使用します。このエンドポイントは**クォータを消費せず**、ローカルでの計算のみを行います。

## 認証

Bearerトークン。例: `Bearer sk-xxxxxxxxxx`

## リクエストパラメーター

<ParamField body="model" type="string" required>
  Claudeのモデル識別子。対応するモデルは以下のとおりです。

  * `claude-opus-4-8`
  * `claude-sonnet-5`
  * `claude-haiku-4-5`
  * その他のClaudeシリーズのモデル
</ParamField>

<ParamField body="messages" type="array" required>
  会話メッセージのリスト。各要素には`role`（user/assistant）と`content`が含まれます。`content`には文字列またはメディアコンテンツの配列を指定できます。

  対応するコンテンツの種類:

  * プレーンテキストのメッセージ
  * マルチモーダルメッセージ（画像を含む）
  * ツール呼び出しの結果
</ParamField>

<ParamField body="system" type="string">
  システムプロンプト（任意）。文字列またはメディアコンテンツの配列を指定でき、モデルの動作や役割を設定するために使用します。
</ParamField>

<ParamField body="tools" type="array">
  ツール定義のリスト（任意）。ツール呼び出しに関連するトークン数の計算に使用します。
</ParamField>

## レスポンスパラメーター

<ResponseField name="input_tokens" type="integer">
  次を含む、入力メッセージの合計トークン数：

  * 全メッセージのトークン数
  * システムプロンプトのトークン数
  * ツール定義のトークン数（ある場合）
</ResponseField>

## 基本的な例

<Tabs>
  <Tab title="シンプルなテキストメッセージ">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages/count_tokens" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "claude-opus-4-8",
        "messages": [
          {
            "role": "user",
            "content": "Hello, how are you?"
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="システムプロンプトあり">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages/count_tokens" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "claude-opus-4-8",
        "system": "You are a helpful AI assistant.",
        "messages": [
          {
            "role": "user",
            "content": "What is artificial intelligence?"
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="複数ターンの会話">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages/count_tokens" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "claude-opus-4-8",
        "messages": [
          {
            "role": "user",
            "content": "Hello"
          },
          {
            "role": "assistant",
            "content": "Hello! How can I help you?"
          },
          {
            "role": "user",
            "content": "Tell me about the history of artificial intelligence"
          }
        ]
      }'
    ```
  </Tab>
</Tabs>

## Pythonの例

```python theme={null}
from anthropic import Anthropic

client = Anthropic(
    api_key="sk-xxxxxxxxxx",
    base_url="https://api.mixroute.ai"
)

# Count tokens
response = client.messages.count_tokens(
    model="claude-opus-4-8",
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)

print(f"Input tokens: {response.input_tokens}")
```

## レスポンス例

```json theme={null}
{
  "input_tokens": 14
}
```

## 高度な使用例

<Tabs>
  <Tab title="ツール定義を含む場合">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages/count_tokens" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "claude-opus-4-8",
        "messages": [
          {
            "role": "user",
            "content": "What is the weather in San Francisco?"
          }
        ],
        "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"]
            }
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="マルチモーダルコンテンツ">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages/count_tokens" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "claude-opus-4-8",
        "messages": [
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": "What is in this image?"
              },
              {
                "type": "image",
                "source": {
                  "type": "url",
                  "url": "https://example.com/image.jpg"
                }
              }
            ]
          }
        ]
      }'
    ```
  </Tab>
</Tabs>

## 使用例

### 1. コストの見積もり

大量のリクエストを送信する前にトークン数を計算して、コストを見積もります。

```python theme={null}
# Batch cost calculation
messages_batch = [...]  # Batch messages
total_tokens = 0

for messages in messages_batch:
    response = client.messages.count_tokens(
        model="claude-opus-4-8",
        messages=messages
    )
    total_tokens += response.input_tokens

# Calculate total cost based on pricing
cost = total_tokens * price_per_token
print(f"Estimated cost: ${cost:.4f}")
```

### 2. コンテキストウィンドウの管理

メッセージがモデルのコンテキストウィンドウの上限を超えていないか確認します。

```python theme={null}
MAX_CONTEXT_WINDOW = 1000000  # Claude Sonnet 5 context window

response = client.messages.count_tokens(
    model="claude-opus-4-8",
    messages=long_conversation
)

if response.input_tokens > MAX_CONTEXT_WINDOW:
    print(f"Warning: Message token count ({response.input_tokens}) exceeds context window limit")
    # Execute message truncation or summarization
```

### 3. プロンプトの最適化

異なるプロンプトのトークン消費量を比較します。

```python theme={null}
prompts = [
    "Concise prompt...",
    "Detailed prompt...",
    "Very detailed prompt..."
]

for prompt in prompts:
    response = client.messages.count_tokens(
        model="claude-opus-4-8",
        system=prompt,
        messages=[{"role": "user", "content": "Test"}]
    )
    print(f"{len(prompt)} characters -> {response.input_tokens} tokens")
```

## 注意事項

* このエンドポイントは実際のAIリクエストを行わず、クォータを消費しません
* `max_tokens`などの出力関連パラメータは含まれず、入力トークン数のみを計算します
* 画像トークンには固定の推定値（約1000トークン）を使用します。実際の値は解像度によって異なる場合があります

## エラー処理

### 必須パラメーターの不足

```json theme={null}
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "Key: 'ClaudeCountTokensRequest.Model' Error:Field validation for 'Model' failed on the 'required' tag"
  }
}
```

### 無効なAPIキー

```json theme={null}
{
  "error": {
    "message": "Invalid token",
    "type": "invalid_request_error"
  }
}
```

## 関連リソース

* 料金 - トークンの課金基準を確認する
* [モデル一覧](https://console.mixroute.ai/models) - 対応するClaudeモデルを確認
* [メッセージリクエストの作成（Claude）](/ja/api-reference/endpoint/messages) - 実際のClaudeリクエストを送信します

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.mixroute.ai/v1/messages/count_tokens \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "claude-opus-4-8",
      "messages": [
        {"role": "user", "content": "Hello, how are you?"}
      ]
    }'
  ```

  ```python Python theme={null}
  from anthropic import Anthropic

  client = Anthropic(
      api_key="sk-xxxxxxxxxx",
      base_url="https://api.mixroute.ai"
  )

  response = client.messages.count_tokens(
      model="claude-opus-4-8",
      messages=[
          {"role": "user", "content": "Hello, how are you?"}
      ]
  )
  print(f"Input tokens: {response.input_tokens}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.mixroute.ai/v1/messages/count_tokens', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-xxxxxxxxxx',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'claude-opus-4-8',
      messages: [
        { role: 'user', content: 'Hello, how are you?' }
      ]
    })
  });
  const data = await response.json();
  console.log(data);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1/messages/count_tokens', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
      ],
      'json' => [
          'model' => 'claude-opus-4-8',
          'messages' => [
              ['role' => 'user', 'content' => 'Hello, how are you?']
          ]
      ]
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "model": "claude-opus-4-8",
          "messages": []map[string]string{
              {"role": "user", "content": "Hello, how are you?"},
          },
      }
      body, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", "https://api.mixroute.ai/v1/messages/count_tokens", bytes.NewBuffer(body))
      req.Header.Set("Authorization", "Bearer sk-xxxxxxxxxx")
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  String json = """
      {
        "model": "claude-opus-4-8",
        "messages": [
          {"role": "user", "content": "Hello, how are you?"}
        ]
      }
      """;
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1/messages/count_tokens"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(json))
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1/messages/count_tokens')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'
  request['Content-Type'] = 'application/json'
  request.body = {
    model: 'claude-opus-4-8',
    messages: [
      { role: 'user', content: 'Hello, how are you?' }
    ]
  }.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "input_tokens": 14
  }
  ```
</ResponseExample>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.