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

# Token counting

# Token counting

***

Token counting enables you to determine the number of tokens in a message before sending it to Claude, helping you make informed decisions about your prompts and usage. With token counting, you can

* Proactively manage rate limits and costs
* Make smart model routing decisions
* Optimize prompts to be a specific length

***

## How to count message tokens

The [token counting](/docs/en/api/messages-count-tokens) endpoint accepts the same structured list of inputs for creating a message, including support for system prompts, [tools](/docs/en/agents-and-tools/tool-use/overview), [images](/docs/en/build-with-claude/vision), and [PDFs](/docs/en/build-with-claude/pdf-support). The response contains the total number of input tokens.

<Note>
  The token count should be considered an **estimate**. In some cases, the actual number of input tokens used when creating a message may differ by a small amount.

  Token counts may include tokens added automatically by Anthropic for system optimizations. **You are not billed for system-added tokens**. Billing reflects only your content.
</Note>

### Supported models

All [active models](/docs/en/about-claude/models/overview) support token counting.

### Count tokens in basic messages

<CodeGroup>
  ```python Python theme={null}
  import anthropic

  client = anthropic.Anthropic()

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

  print(response.json())
  ```

  ```typescript TypeScript theme={null}
  import Anthropic from '@anthropic-ai/sdk';

  const client = new Anthropic();

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

  console.log(response);
  ```

  ```bash Shell theme={null}
  curl https://api.anthropic.com/v1/messages/count_tokens \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "content-type: application/json" \
      --header "anthropic-version: 2023-06-01" \
      --data '{
        "model": "claude-sonnet-4-5",
        "system": "You are a scientist",
        "messages": [{
          "role": "user",
          "content": "Hello, Claude"
        }]
      }'
  ```

  ```java Java theme={null}
  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  import com.anthropic.models.messages.Model;

  public class CountTokensExample {

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

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

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

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

### Count tokens in messages with tools

<Note>
  [Server tool](/docs/en/agents-and-tools/tool-use/overview#server-tools) token counts only apply to the first sampling call.
</Note>

<CodeGroup>
  ```python Python theme={null}
  import anthropic

  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-sonnet-4-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 theme={null}
  import Anthropic from '@anthropic-ai/sdk';

  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: 'claude-sonnet-4-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);
  ```

  ```bash Shell theme={null}
  curl https://api.anthropic.com/v1/messages/count_tokens \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "content-type: application/json" \
      --header "anthropic-version: 2023-06-01" \
      --data '{
        "model": "claude-sonnet-4-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?"
          }
        ]
      }'
  ```

  ```java Java theme={null}
  import java.util.List;
  import java.util.Map;

  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  import com.anthropic.models.messages.Model;
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;

  public class CountTokensWithToolsExample {

      public static void main(String[] args) {
          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_SONNET_4_20250514)
                  .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);
      }
  }
  ```
</CodeGroup>

```json JSON theme={null}
{ "input_tokens": 403 }
```

### Count tokens in messages with images

<CodeGroup>
  ```bash Shell theme={null}
  #!/bin/sh

  IMAGE_URL="https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
  IMAGE_MEDIA_TYPE="image/jpeg"
  IMAGE_BASE64=$(curl "$IMAGE_URL" | base64)

  curl https://api.anthropic.com/v1/messages/count_tokens \
       --header "x-api-key: $ANTHROPIC_API_KEY" \
       --header "anthropic-version: 2023-06-01" \
       --header "content-type: application/json" \
       --data \
  '{
      "model": "claude-sonnet-4-5",
      "messages": [
          {"role": "user", "content": [
              {"type": "image", "source": {
                  "type": "base64",
                  "media_type": "'$IMAGE_MEDIA_TYPE'",
                  "data": "'$IMAGE_BASE64'"
              }},
              {"type": "text", "text": "Describe this image"}
          ]}
      ]
  }'
  ```

  ```python Python theme={null}
  import anthropic
  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-sonnet-4-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 theme={null}
  import Anthropic from '@anthropic-ai/sdk';

  const anthropic = new Anthropic();

  const image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
  const image_media_type = "image/jpeg"
  const image_array_buffer = await ((await fetch(image_url)).arrayBuffer());
  const image_data = Buffer.from(image_array_buffer).toString('base64');

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

  ```java Java theme={null}
  import java.util.Base64;
  import java.util.List;

  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.models.messages.Base64ImageSource;
  import com.anthropic.models.messages.ContentBlockParam;
  import com.anthropic.models.messages.ImageBlockParam;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  import com.anthropic.models.messages.Model;
  import com.anthropic.models.messages.TextBlockParam;

  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;

  public class CountTokensImageExample {

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

          String imageUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.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_SONNET_4_20250514)
                  .addUserMessageOfBlockParams(List.of(imageBlock, textBlock))
                  .build();

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

```json JSON theme={null}
{ "input_tokens": 1551 }
```

### Count tokens in messages with extended thinking

<Note>
  See [here](/docs/en/build-with-claude/extended-thinking#how-context-window-is-calculated-with-extended-thinking) for more details about how the context window is calculated with extended thinking

  * Thinking blocks from **previous** assistant turns are ignored and **do not** count toward your input tokens
  * **Current** assistant turn thinking **does** count toward your input tokens
</Note>

<CodeGroup>
  ```bash Shell theme={null}
  curl https://api.anthropic.com/v1/messages/count_tokens \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "content-type: application/json" \
      --header "anthropic-version: 2023-06-01" \
      --data '{
        "model": "claude-sonnet-4-5",
        "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. 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?"
          }
        ]
      }'
  ```

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

  client = anthropic.Anthropic()

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

  ```typescript TypeScript theme={null}
  import Anthropic from '@anthropic-ai/sdk';

  const client = new Anthropic();

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

  console.log(response);
  ```

  ```java Java theme={null}
  import java.util.List;

  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.models.messages.ContentBlockParam;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  import com.anthropic.models.messages.Model;
  import com.anthropic.models.messages.TextBlockParam;
  import com.anthropic.models.messages.ThinkingBlockParam;

  public class CountTokensThinkingExample {

      public static void main(String[] args) {
          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_SONNET_4_20250514)
                  .enabledThinking(16000)
                  .addUserMessage("Are there an infinite number of prime numbers such that n mod 4 == 3?")
                  .addAssistantMessageOfBlockParams(assistantBlocks)
                  .addUserMessage("Can you write a formal proof?")
                  .build();

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

```json JSON theme={null}
{ "input_tokens": 88 }
```

### Count tokens in messages with PDFs

<Note>
  Token counting supports PDFs with the same [limitations](/docs/en/build-with-claude/pdf-support#pdf-support-limitations) as the Messages API.
</Note>

<CodeGroup>
  ```bash Shell theme={null}
  curl https://api.anthropic.com/v1/messages/count_tokens \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "content-type: application/json" \
      --header "anthropic-version: 2023-06-01" \
      --data '{
        "model": "claude-sonnet-4-5",
        "messages": [{
          "role": "user",
          "content": [
            {
              "type": "document",
              "source": {
                "type": "base64",
                "media_type": "application/pdf",
                "data": "'$(base64 -i document.pdf)'"
              }
            },
            {
              "type": "text",
              "text": "Please summarize this document."
            }
          ]
        }]
      }'
  ```

  ```python Python theme={null}
  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-sonnet-4-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 theme={null}
  import Anthropic from '@anthropic-ai/sdk';
  import { readFileSync } from 'fs';

  const client = new Anthropic();

  const pdfBase64 = readFileSync('document.pdf', { encoding: 'base64' });

  const response = await client.messages.countTokens({
    model: 'claude-sonnet-4-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);
  ```

  ```java Java theme={null}
  import java.nio.file.Files;
  import java.nio.file.Path;
  import java.util.Base64;
  import java.util.List;

  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.models.messages.Base64PdfSource;
  import com.anthropic.models.messages.ContentBlockParam;
  import com.anthropic.models.messages.DocumentBlockParam;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  import com.anthropic.models.messages.Model;
  import com.anthropic.models.messages.TextBlockParam;

  public class CountTokensPdfExample {

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

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

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

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

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

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

```json JSON theme={null}
{ "input_tokens": 2188 }
```

***

## Pricing and rate limits

Token counting is **free to use** but subject to requests per minute rate limits based on your [usage tier](/docs/en/api/rate-limits#rate-limits). If you need higher limits, contact sales through the [Claude Console](/settings/limits).

| Usage tier | Requests per minute (RPM) |
| - | - |
| 1 | 100 |
| 2 | 2,000 |
| 3 | 4,000 |
| 4 | 8,000 |

<Note>
  Token counting and message creation have separate and independent rate limits -- usage of one does not count against the limits of the other.
</Note>

***

## FAQ

<section title="Does token counting use prompt caching?">
  No, token counting provides an estimate without using caching logic. While you may provide `cache_control` blocks in your token counting request, prompt caching only occurs during actual message creation.
</section>

## Count Tokens

`client.messages.countTokens(MessageCountTokensParamsbody, RequestOptionsoptions?): MessageTokensCount`

**post** `/v1/messages/count_tokens`

Count the number of tokens in a Message.

The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it.

Learn more about token counting in our [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)

### Parameters

* `body: MessageCountTokensParams`

  * `messages: Array<MessageParam>`

    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.

    Example with a single `user` message:

    ```json theme={null}
    [{"role": "user", "content": "Hello, Claude"}]
    ```

    Example with multiple conversational turns:

    ```json theme={null}
    [
      {"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:

    ```json theme={null}
    [
      {"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:

    ```json theme={null}
    {"role": "user", "content": "Hello, Claude"}
    ```

    ```json theme={null}
    {"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
    ```

    See [input examples](https://docs.claude.com/en/api/messages-examples).

    Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API.

    There is a limit of 100,000 messages in a single request.

    * `content: string | Array<ContentBlockParam>`

      * `string`

      * `Array<ContentBlockParam>`

        * `TextBlockParam`

          * `text: string`

          * `type: "text"`

            * `"text"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

          * `citations?: Array<TextCitationParam> | null`

            * `CitationCharLocationParam`

              * `cited_text: string`

              * `document_index: number`

              * `document_title: string | null`

              * `end_char_index: number`

              * `start_char_index: number`

              * `type: "char_location"`

                * `"char_location"`

            * `CitationPageLocationParam`

              * `cited_text: string`

              * `document_index: number`

              * `document_title: string | null`

              * `end_page_number: number`

              * `start_page_number: number`

              * `type: "page_location"`

                * `"page_location"`

            * `CitationContentBlockLocationParam`

              * `cited_text: string`

              * `document_index: number`

              * `document_title: string | null`

              * `end_block_index: number`

              * `start_block_index: number`

              * `type: "content_block_location"`

                * `"content_block_location"`

            * `CitationWebSearchResultLocationParam`

              * `cited_text: string`

              * `encrypted_index: string`

              * `title: string | null`

              * `type: "web_search_result_location"`

                * `"web_search_result_location"`

              * `url: string`

            * `CitationSearchResultLocationParam`

              * `cited_text: string`

              * `end_block_index: number`

              * `search_result_index: number`

              * `source: string`

              * `start_block_index: number`

              * `title: string | null`

              * `type: "search_result_location"`

                * `"search_result_location"`

        * `ImageBlockParam`

          * `source: Base64ImageSource | URLImageSource`

            * `Base64ImageSource`

              * `data: string`

              * `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`

                * `"image/jpeg"`

                * `"image/png"`

                * `"image/gif"`

                * `"image/webp"`

              * `type: "base64"`

                * `"base64"`

            * `URLImageSource`

              * `type: "url"`

                * `"url"`

              * `url: string`

          * `type: "image"`

            * `"image"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

        * `DocumentBlockParam`

          * `source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource`

            * `Base64PDFSource`

              * `data: string`

              * `media_type: "application/pdf"`

                * `"application/pdf"`

              * `type: "base64"`

                * `"base64"`

            * `PlainTextSource`

              * `data: string`

              * `media_type: "text/plain"`

                * `"text/plain"`

              * `type: "text"`

                * `"text"`

            * `ContentBlockSource`

              * `content: string | Array<ContentBlockSourceContent>`

                * `string`

                * `Array<ContentBlockSourceContent>`

                  * `TextBlockParam`

                    * `text: string`

                    * `type: "text"`

                      * `"text"`

                    * `cache_control?: CacheControlEphemeral | null`

                      Create a cache control breakpoint at this content block.

                      * `type: "ephemeral"`

                        * `"ephemeral"`

                      * `ttl?: "5m" | "1h"`

                        The time-to-live for the cache control breakpoint.

                        This may be one the following values:

                        * `5m`: 5 minutes
                        * `1h`: 1 hour

                        Defaults to `5m`.

                        * `"5m"`

                        * `"1h"`

                    * `citations?: Array<TextCitationParam> | null`

                      * `CitationCharLocationParam`

                        * `cited_text: string`

                        * `document_index: number`

                        * `document_title: string | null`

                        * `end_char_index: number`

                        * `start_char_index: number`

                        * `type: "char_location"`

                          * `"char_location"`

                      * `CitationPageLocationParam`

                        * `cited_text: string`

                        * `document_index: number`

                        * `document_title: string | null`

                        * `end_page_number: number`

                        * `start_page_number: number`

                        * `type: "page_location"`

                          * `"page_location"`

                      * `CitationContentBlockLocationParam`

                        * `cited_text: string`

                        * `document_index: number`

                        * `document_title: string | null`

                        * `end_block_index: number`

                        * `start_block_index: number`

                        * `type: "content_block_location"`

                          * `"content_block_location"`

                      * `CitationWebSearchResultLocationParam`

                        * `cited_text: string`

                        * `encrypted_index: string`

                        * `title: string | null`

                        * `type: "web_search_result_location"`

                          * `"web_search_result_location"`

                        * `url: string`

                      * `CitationSearchResultLocationParam`

                        * `cited_text: string`

                        * `end_block_index: number`

                        * `search_result_index: number`

                        * `source: string`

                        * `start_block_index: number`

                        * `title: string | null`

                        * `type: "search_result_location"`

                          * `"search_result_location"`

                  * `ImageBlockParam`

                    * `source: Base64ImageSource | URLImageSource`

                      * `Base64ImageSource`

                        * `data: string`

                        * `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`

                          * `"image/jpeg"`

                          * `"image/png"`

                          * `"image/gif"`

                          * `"image/webp"`

                        * `type: "base64"`

                          * `"base64"`

                      * `URLImageSource`

                        * `type: "url"`

                          * `"url"`

                        * `url: string`

                    * `type: "image"`

                      * `"image"`

                    * `cache_control?: CacheControlEphemeral | null`

                      Create a cache control breakpoint at this content block.

                      * `type: "ephemeral"`

                        * `"ephemeral"`

                      * `ttl?: "5m" | "1h"`

                        The time-to-live for the cache control breakpoint.

                        This may be one the following values:

                        * `5m`: 5 minutes
                        * `1h`: 1 hour

                        Defaults to `5m`.

                        * `"5m"`

                        * `"1h"`

              * `type: "content"`

                * `"content"`

            * `URLPDFSource`

              * `type: "url"`

                * `"url"`

              * `url: string`

          * `type: "document"`

            * `"document"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

          * `citations?: CitationsConfigParam | null`

            * `enabled?: boolean`

          * `context?: string | null`

          * `title?: string | null`

        * `SearchResultBlockParam`

          * `content: Array<TextBlockParam>`

            * `text: string`

            * `type: "text"`

              * `"text"`

            * `cache_control?: CacheControlEphemeral | null`

              Create a cache control breakpoint at this content block.

              * `type: "ephemeral"`

                * `"ephemeral"`

              * `ttl?: "5m" | "1h"`

                The time-to-live for the cache control breakpoint.

                This may be one the following values:

                * `5m`: 5 minutes
                * `1h`: 1 hour

                Defaults to `5m`.

                * `"5m"`

                * `"1h"`

            * `citations?: Array<TextCitationParam> | null`

              * `CitationCharLocationParam`

                * `cited_text: string`

                * `document_index: number`

                * `document_title: string | null`

                * `end_char_index: number`

                * `start_char_index: number`

                * `type: "char_location"`

                  * `"char_location"`

              * `CitationPageLocationParam`

                * `cited_text: string`

                * `document_index: number`

                * `document_title: string | null`

                * `end_page_number: number`

                * `start_page_number: number`

                * `type: "page_location"`

                  * `"page_location"`

              * `CitationContentBlockLocationParam`

                * `cited_text: string`

                * `document_index: number`

                * `document_title: string | null`

                * `end_block_index: number`

                * `start_block_index: number`

                * `type: "content_block_location"`

                  * `"content_block_location"`

              * `CitationWebSearchResultLocationParam`

                * `cited_text: string`

                * `encrypted_index: string`

                * `title: string | null`

                * `type: "web_search_result_location"`

                  * `"web_search_result_location"`

                * `url: string`

              * `CitationSearchResultLocationParam`

                * `cited_text: string`

                * `end_block_index: number`

                * `search_result_index: number`

                * `source: string`

                * `start_block_index: number`

                * `title: string | null`

                * `type: "search_result_location"`

                  * `"search_result_location"`

          * `source: string`

          * `title: string`

          * `type: "search_result"`

            * `"search_result"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

          * `citations?: CitationsConfigParam`

            * `enabled?: boolean`

        * `ThinkingBlockParam`

          * `signature: string`

          * `thinking: string`

          * `type: "thinking"`

            * `"thinking"`

        * `RedactedThinkingBlockParam`

          * `data: string`

          * `type: "redacted_thinking"`

            * `"redacted_thinking"`

        * `ToolUseBlockParam`

          * `id: string`

          * `input: Record<string, unknown>`

          * `name: string`

          * `type: "tool_use"`

            * `"tool_use"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

        * `ToolResultBlockParam`

          * `tool_use_id: string`

          * `type: "tool_result"`

            * `"tool_result"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

          * `content?: string | Array<TextBlockParam | ImageBlockParam | SearchResultBlockParam | DocumentBlockParam>`

            * `string`

            * `Array<TextBlockParam | ImageBlockParam | SearchResultBlockParam | DocumentBlockParam>`

              * `TextBlockParam`

                * `text: string`

                * `type: "text"`

                  * `"text"`

                * `cache_control?: CacheControlEphemeral | null`

                  Create a cache control breakpoint at this content block.

                  * `type: "ephemeral"`

                    * `"ephemeral"`

                  * `ttl?: "5m" | "1h"`

                    The time-to-live for the cache control breakpoint.

                    This may be one the following values:

                    * `5m`: 5 minutes
                    * `1h`: 1 hour

                    Defaults to `5m`.

                    * `"5m"`

                    * `"1h"`

                * `citations?: Array<TextCitationParam> | null`

                  * `CitationCharLocationParam`

                    * `cited_text: string`

                    * `document_index: number`

                    * `document_title: string | null`

                    * `end_char_index: number`

                    * `start_char_index: number`

                    * `type: "char_location"`

                      * `"char_location"`

                  * `CitationPageLocationParam`

                    * `cited_text: string`

                    * `document_index: number`

                    * `document_title: string | null`

                    * `end_page_number: number`

                    * `start_page_number: number`

                    * `type: "page_location"`

                      * `"page_location"`

                  * `CitationContentBlockLocationParam`

                    * `cited_text: string`

                    * `document_index: number`

                    * `document_title: string | null`

                    * `end_block_index: number`

                    * `start_block_index: number`

                    * `type: "content_block_location"`

                      * `"content_block_location"`

                  * `CitationWebSearchResultLocationParam`

                    * `cited_text: string`

                    * `encrypted_index: string`

                    * `title: string | null`

                    * `type: "web_search_result_location"`

                      * `"web_search_result_location"`

                    * `url: string`

                  * `CitationSearchResultLocationParam`

                    * `cited_text: string`

                    * `end_block_index: number`

                    * `search_result_index: number`

                    * `source: string`

                    * `start_block_index: number`

                    * `title: string | null`

                    * `type: "search_result_location"`

                      * `"search_result_location"`

              * `ImageBlockParam`

                * `source: Base64ImageSource | URLImageSource`

                  * `Base64ImageSource`

                    * `data: string`

                    * `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`

                      * `"image/jpeg"`

                      * `"image/png"`

                      * `"image/gif"`

                      * `"image/webp"`

                    * `type: "base64"`

                      * `"base64"`

                  * `URLImageSource`

                    * `type: "url"`

                      * `"url"`

                    * `url: string`

                * `type: "image"`

                  * `"image"`

                * `cache_control?: CacheControlEphemeral | null`

                  Create a cache control breakpoint at this content block.

                  * `type: "ephemeral"`

                    * `"ephemeral"`

                  * `ttl?: "5m" | "1h"`

                    The time-to-live for the cache control breakpoint.

                    This may be one the following values:

                    * `5m`: 5 minutes
                    * `1h`: 1 hour

                    Defaults to `5m`.

                    * `"5m"`

                    * `"1h"`

              * `SearchResultBlockParam`

                * `content: Array<TextBlockParam>`

                  * `text: string`

                  * `type: "text"`

                    * `"text"`

                  * `cache_control?: CacheControlEphemeral | null`

                    Create a cache control breakpoint at this content block.

                    * `type: "ephemeral"`

                      * `"ephemeral"`

                    * `ttl?: "5m" | "1h"`

                      The time-to-live for the cache control breakpoint.

                      This may be one the following values:

                      * `5m`: 5 minutes
                      * `1h`: 1 hour

                      Defaults to `5m`.

                      * `"5m"`

                      * `"1h"`

                  * `citations?: Array<TextCitationParam> | null`

                    * `CitationCharLocationParam`

                      * `cited_text: string`

                      * `document_index: number`

                      * `document_title: string | null`

                      * `end_char_index: number`

                      * `start_char_index: number`

                      * `type: "char_location"`

                        * `"char_location"`

                    * `CitationPageLocationParam`

                      * `cited_text: string`

                      * `document_index: number`

                      * `document_title: string | null`

                      * `end_page_number: number`

                      * `start_page_number: number`

                      * `type: "page_location"`

                        * `"page_location"`

                    * `CitationContentBlockLocationParam`

                      * `cited_text: string`

                      * `document_index: number`

                      * `document_title: string | null`

                      * `end_block_index: number`

                      * `start_block_index: number`

                      * `type: "content_block_location"`

                        * `"content_block_location"`

                    * `CitationWebSearchResultLocationParam`

                      * `cited_text: string`

                      * `encrypted_index: string`

                      * `title: string | null`

                      * `type: "web_search_result_location"`

                        * `"web_search_result_location"`

                      * `url: string`

                    * `CitationSearchResultLocationParam`

                      * `cited_text: string`

                      * `end_block_index: number`

                      * `search_result_index: number`

                      * `source: string`

                      * `start_block_index: number`

                      * `title: string | null`

                      * `type: "search_result_location"`

                        * `"search_result_location"`

                * `source: string`

                * `title: string`

                * `type: "search_result"`

                  * `"search_result"`

                * `cache_control?: CacheControlEphemeral | null`

                  Create a cache control breakpoint at this content block.

                  * `type: "ephemeral"`

                    * `"ephemeral"`

                  * `ttl?: "5m" | "1h"`

                    The time-to-live for the cache control breakpoint.

                    This may be one the following values:

                    * `5m`: 5 minutes
                    * `1h`: 1 hour

                    Defaults to `5m`.

                    * `"5m"`

                    * `"1h"`

                * `citations?: CitationsConfigParam`

                  * `enabled?: boolean`

              * `DocumentBlockParam`

                * `source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource`

                  * `Base64PDFSource`

                    * `data: string`

                    * `media_type: "application/pdf"`

                      * `"application/pdf"`

                    * `type: "base64"`

                      * `"base64"`

                  * `PlainTextSource`

                    * `data: string`

                    * `media_type: "text/plain"`

                      * `"text/plain"`

                    * `type: "text"`

                      * `"text"`

                  * `ContentBlockSource`

                    * `content: string | Array<ContentBlockSourceContent>`

                      * `string`

                      * `Array<ContentBlockSourceContent>`

                        * `TextBlockParam`

                          * `text: string`

                          * `type: "text"`

                            * `"text"`

                          * `cache_control?: CacheControlEphemeral | null`

                            Create a cache control breakpoint at this content block.

                            * `type: "ephemeral"`

                              * `"ephemeral"`

                            * `ttl?: "5m" | "1h"`

                              The time-to-live for the cache control breakpoint.

                              This may be one the following values:

                              * `5m`: 5 minutes
                              * `1h`: 1 hour

                              Defaults to `5m`.

                              * `"5m"`

                              * `"1h"`

                          * `citations?: Array<TextCitationParam> | null`

                            * `CitationCharLocationParam`

                              * `cited_text: string`

                              * `document_index: number`

                              * `document_title: string | null`

                              * `end_char_index: number`

                              * `start_char_index: number`

                              * `type: "char_location"`

                                * `"char_location"`

                            * `CitationPageLocationParam`

                              * `cited_text: string`

                              * `document_index: number`

                              * `document_title: string | null`

                              * `end_page_number: number`

                              * `start_page_number: number`

                              * `type: "page_location"`

                                * `"page_location"`

                            * `CitationContentBlockLocationParam`

                              * `cited_text: string`

                              * `document_index: number`

                              * `document_title: string | null`

                              * `end_block_index: number`

                              * `start_block_index: number`

                              * `type: "content_block_location"`

                                * `"content_block_location"`

                            * `CitationWebSearchResultLocationParam`

                              * `cited_text: string`

                              * `encrypted_index: string`

                              * `title: string | null`

                              * `type: "web_search_result_location"`

                                * `"web_search_result_location"`

                              * `url: string`

                            * `CitationSearchResultLocationParam`

                              * `cited_text: string`

                              * `end_block_index: number`

                              * `search_result_index: number`

                              * `source: string`

                              * `start_block_index: number`

                              * `title: string | null`

                              * `type: "search_result_location"`

                                * `"search_result_location"`

                        * `ImageBlockParam`

                          * `source: Base64ImageSource | URLImageSource`

                            * `Base64ImageSource`

                              * `data: string`

                              * `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`

                                * `"image/jpeg"`

                                * `"image/png"`

                                * `"image/gif"`

                                * `"image/webp"`

                              * `type: "base64"`

                                * `"base64"`

                            * `URLImageSource`

                              * `type: "url"`

                                * `"url"`

                              * `url: string`

                          * `type: "image"`

                            * `"image"`

                          * `cache_control?: CacheControlEphemeral | null`

                            Create a cache control breakpoint at this content block.

                            * `type: "ephemeral"`

                              * `"ephemeral"`

                            * `ttl?: "5m" | "1h"`

                              The time-to-live for the cache control breakpoint.

                              This may be one the following values:

                              * `5m`: 5 minutes
                              * `1h`: 1 hour

                              Defaults to `5m`.

                              * `"5m"`

                              * `"1h"`

                    * `type: "content"`

                      * `"content"`

                  * `URLPDFSource`

                    * `type: "url"`

                      * `"url"`

                    * `url: string`

                * `type: "document"`

                  * `"document"`

                * `cache_control?: CacheControlEphemeral | null`

                  Create a cache control breakpoint at this content block.

                  * `type: "ephemeral"`

                    * `"ephemeral"`

                  * `ttl?: "5m" | "1h"`

                    The time-to-live for the cache control breakpoint.

                    This may be one the following values:

                    * `5m`: 5 minutes
                    * `1h`: 1 hour

                    Defaults to `5m`.

                    * `"5m"`

                    * `"1h"`

                * `citations?: CitationsConfigParam | null`

                  * `enabled?: boolean`

                * `context?: string | null`

                * `title?: string | null`

          * `is_error?: boolean`

        * `ServerToolUseBlockParam`

          * `id: string`

          * `input: Record<string, unknown>`

          * `name: "web_search"`

            * `"web_search"`

          * `type: "server_tool_use"`

            * `"server_tool_use"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

        * `WebSearchToolResultBlockParam`

          * `content: WebSearchToolResultBlockParamContent`

            * `Array<WebSearchResultBlockParam>`

              * `encrypted_content: string`

              * `title: string`

              * `type: "web_search_result"`

                * `"web_search_result"`

              * `url: string`

              * `page_age?: string | null`

            * `WebSearchToolRequestError`

              * `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 2 more`

                * `"invalid_tool_input"`

                * `"unavailable"`

                * `"max_uses_exceeded"`

                * `"too_many_requests"`

                * `"query_too_long"`

              * `type: "web_search_tool_result_error"`

                * `"web_search_tool_result_error"`

          * `tool_use_id: string`

          * `type: "web_search_tool_result"`

            * `"web_search_tool_result"`

          * `cache_control?: CacheControlEphemeral | null`

            Create a cache control breakpoint at this content block.

            * `type: "ephemeral"`

              * `"ephemeral"`

            * `ttl?: "5m" | "1h"`

              The time-to-live for the cache control breakpoint.

              This may be one the following values:

              * `5m`: 5 minutes
              * `1h`: 1 hour

              Defaults to `5m`.

              * `"5m"`

              * `"1h"`

    * `role: "user" | "assistant"`

      * `"user"`

      * `"assistant"`

  * `model: Model`

    The model that will complete your prompt.

    See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.

    * `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`

      * `"claude-opus-4-5-20251101"`

        Premium model combining maximum intelligence with practical performance

      * `"claude-opus-4-5"`

        Premium model combining maximum intelligence with practical performance

      * `"claude-3-7-sonnet-latest"`

        High-performance model with early extended thinking

      * `"claude-3-7-sonnet-20250219"`

        High-performance model with early extended thinking

      * `"claude-3-5-haiku-latest"`

        Fastest and most compact model for near-instant responsiveness

      * `"claude-3-5-haiku-20241022"`

        Our fastest model

      * `"claude-haiku-4-5"`

        Hybrid model, capable of near-instant responses and extended thinking

      * `"claude-haiku-4-5-20251001"`

        Hybrid model, capable of near-instant responses and extended thinking

      * `"claude-sonnet-4-20250514"`

        High-performance model with extended thinking

      * `"claude-sonnet-4-0"`

        High-performance model with extended thinking

      * `"claude-4-sonnet-20250514"`

        High-performance model with extended thinking

      * `"claude-sonnet-4-5"`

        Our best model for real-world agents and coding

      * `"claude-sonnet-4-5-20250929"`

        Our best model for real-world agents and coding

      * `"claude-opus-4-0"`

        Our most capable model

      * `"claude-opus-4-20250514"`

        Our most capable model

      * `"claude-4-opus-20250514"`

        Our most capable model

      * `"claude-opus-4-1-20250805"`

        Our most capable model

      * `"claude-3-opus-latest"`

        Excels at writing and complex tasks

      * `"claude-3-opus-20240229"`

        Excels at writing and complex tasks

      * `"claude-3-haiku-20240307"`

        Our previous most fast and cost-effective

    * `(string & {})`

  * `system?: string | Array<TextBlockParam>`

    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](https://docs.claude.com/en/docs/system-prompts).

    * `string`

    * `Array<TextBlockParam>`

      * `text: string`

      * `type: "text"`

        * `"text"`

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

      * `citations?: Array<TextCitationParam> | null`

        * `CitationCharLocationParam`

          * `cited_text: string`

          * `document_index: number`

          * `document_title: string | null`

          * `end_char_index: number`

          * `start_char_index: number`

          * `type: "char_location"`

            * `"char_location"`

        * `CitationPageLocationParam`

          * `cited_text: string`

          * `document_index: number`

          * `document_title: string | null`

          * `end_page_number: number`

          * `start_page_number: number`

          * `type: "page_location"`

            * `"page_location"`

        * `CitationContentBlockLocationParam`

          * `cited_text: string`

          * `document_index: number`

          * `document_title: string | null`

          * `end_block_index: number`

          * `start_block_index: number`

          * `type: "content_block_location"`

            * `"content_block_location"`

        * `CitationWebSearchResultLocationParam`

          * `cited_text: string`

          * `encrypted_index: string`

          * `title: string | null`

          * `type: "web_search_result_location"`

            * `"web_search_result_location"`

          * `url: string`

        * `CitationSearchResultLocationParam`

          * `cited_text: string`

          * `end_block_index: number`

          * `search_result_index: number`

          * `source: string`

          * `start_block_index: number`

          * `title: string | null`

          * `type: "search_result_location"`

            * `"search_result_location"`

  * `thinking?: ThinkingConfigParam`

    Configuration for enabling Claude's extended thinking.

    When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.

    See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.

    * `ThinkingConfigEnabled`

      * `budget_tokens: number`

        Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.

        Must be ≥1024 and less than `max_tokens`.

        See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.

      * `type: "enabled"`

        * `"enabled"`

    * `ThinkingConfigDisabled`

      * `type: "disabled"`

        * `"disabled"`

  * `tool_choice?: ToolChoice`

    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.

    * `ToolChoiceAuto`

      The model will automatically decide whether to use tools.

      * `type: "auto"`

        * `"auto"`

      * `disable_parallel_tool_use?: boolean`

        Whether to disable parallel tool use.

        Defaults to `false`. If set to `true`, the model will output at most one tool use.

    * `ToolChoiceAny`

      The model will use any available tools.

      * `type: "any"`

        * `"any"`

      * `disable_parallel_tool_use?: boolean`

        Whether to disable parallel tool use.

        Defaults to `false`. If set to `true`, the model will output exactly one tool use.

    * `ToolChoiceTool`

      The model will use the specified tool with `tool_choice.name`.

      * `name: string`

        The name of the tool to use.

      * `type: "tool"`

        * `"tool"`

      * `disable_parallel_tool_use?: boolean`

        Whether to disable parallel tool use.

        Defaults to `false`. If set to `true`, the model will output exactly one tool use.

    * `ToolChoiceNone`

      The model will not be allowed to use tools.

      * `type: "none"`

        * `"none"`

  * `tools?: Array<MessageCountTokensTool>`

    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](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/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](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.

    For example, if you defined `tools` as:

    ```json theme={null}
    [
      {
        "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:

    ```json theme={null}
    [
      {
        "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:

    ```json theme={null}
    [
      {
        "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](https://docs.claude.com/en/docs/tool-use) for more details.

    * `Tool`

      * `input_schema: InputSchema`

        [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.

        This defines the shape of the `input` that your tool accepts and that the model will produce.

        * `type: "object"`

          * `"object"`

        * `properties?: Record<string, unknown> | null`

        * `required?: Array<string> | null`

      * `name: string`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

      * `description?: string`

        Description of what this tool does.

        Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.

      * `type?: "custom" | null`

        * `"custom"`

    * `ToolBash20250124`

      * `name: "bash"`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

        * `"bash"`

      * `type: "bash_20250124"`

        * `"bash_20250124"`

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

    * `ToolTextEditor20250124`

      * `name: "str_replace_editor"`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

        * `"str_replace_editor"`

      * `type: "text_editor_20250124"`

        * `"text_editor_20250124"`

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

    * `ToolTextEditor20250429`

      * `name: "str_replace_based_edit_tool"`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

        * `"str_replace_based_edit_tool"`

      * `type: "text_editor_20250429"`

        * `"text_editor_20250429"`

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

    * `ToolTextEditor20250728`

      * `name: "str_replace_based_edit_tool"`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

        * `"str_replace_based_edit_tool"`

      * `type: "text_editor_20250728"`

        * `"text_editor_20250728"`

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

      * `max_characters?: number | null`

        Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.

    * `WebSearchTool20250305`

      * `name: "web_search"`

        Name of the tool.

        This is how the tool will be called by the model and in `tool_use` blocks.

        * `"web_search"`

      * `type: "web_search_20250305"`

        * `"web_search_20250305"`

      * `allowed_domains?: Array<string> | null`

        If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.

      * `blocked_domains?: Array<string> | null`

        If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.

      * `cache_control?: CacheControlEphemeral | null`

        Create a cache control breakpoint at this content block.

        * `type: "ephemeral"`

          * `"ephemeral"`

        * `ttl?: "5m" | "1h"`

          The time-to-live for the cache control breakpoint.

          This may be one the following values:

          * `5m`: 5 minutes
          * `1h`: 1 hour

          Defaults to `5m`.

          * `"5m"`

          * `"1h"`

      * `max_uses?: number | null`

        Maximum number of times the tool can be used in the API request.

      * `user_location?: UserLocation | null`

        Parameters for the user's location. Used to provide more relevant search results.

        * `type: "approximate"`

          * `"approximate"`

        * `city?: string | null`

          The city of the user.

        * `country?: string | null`

          The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.

        * `region?: string | null`

          The region of the user.

        * `timezone?: string | null`

          The [IANA timezone](https://nodatime.org/TimeZones) of the user.

### Returns

* `MessageTokensCount`

  * `input_tokens: number`

    The total number of tokens across the provided list of messages, system prompt, and tools.

### Example

```typescript theme={null}
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});

const messageTokensCount = await client.messages.countTokens({
  messages: [{ content: 'string', role: 'user' }],
  model: 'claude-opus-4-5-20251101',
});

console.log(messageTokensCount.input_tokens);
```


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