

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 추론을 실행하기 전에 토큰을 계산하여 토큰 사용량 모니터링
<a name="count-tokens"></a>

모델 추론을 실행하면 입력에서 전송하는 토큰 수가 요청 비용과 분당 및 하루에 사용할 수 있는 토큰 할당량에 영향을 미칩니다. [CountTokens](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_CountTokens.html) API를 사용하면 추론 요청에서 동일한 입력이 모델에 전송된 경우 사용할 토큰 수를 반환하여 파운데이션 모델에 요청을 보내기 전에 토큰 사용량을 추정할 수 있습니다.

**참고**  
[CountTokens](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_CountTokens.html) API를 사용해도 요금이 발생하지 않습니다.

토큰 계산은 모델별로 다릅니다. 모델마다 토큰화 전략이 다르기 때문입니다. 이 작업에서 반환되는 토큰 수는 추론을 실행하기 위해 동일한 입력이 모델에 전송된 경우 청구되는 토큰 수와 일치합니다.

`CountTokens` API를 사용하여 다음을 수행할 수 있습니다.
+ 추론 요청을 보내기 전에 비용을 추정합니다.
+ 토큰 제한에 맞게 프롬프트를 최적화합니다.
+ 애플리케이션에서 토큰 사용을 계획합니다.

**Topics**
+ [토큰 계산에 지원되는 모델 및 리전](#count-tokens-supported)
+ [요청의 토큰 수 계산](#count-tokens-use)
+ [예제 시도](#count-tokens-example)

## 토큰 계산에 지원되는 모델 및 리전
<a name="count-tokens-supported"></a>

다음 표에는 토큰 계산에 대한 파운데이션 모델 지원이 나와 있습니다.


| 제공업체 | 모델 | 모델 ID | 단일 리전 모델 지원 | 
| --- | --- | --- | --- | 
| Anthropic | Claude 3.5 Haiku | anthropic.claude-3-5-haiku-20241022-v1:0 |  us-west-2  | 
| Anthropic | claude-3.5-sonnet | anthropic.claude-3-5-sonnet-20240620-v1:0 |  ap-northeast-1 ap-southeast-1 eu-central-1 eu-central-2 us-east-1 us-west-2  | 
| Anthropic | Claude 3.5 Sonnet v2 | anthropic.claude-3-5-sonnet-20241022-v2:0 |  ap-southeast-2 us-west-2  | 
| Anthropic | Claude 3.7 Sonnet | anthropic.claude-3-7-sonnet-20250219-v1:0 |  eu-west-2  | 
| Anthropic | Claude Opus 4 | anthropic.claude-opus-4-20250514-v1:0 |  | 
| Anthropic | Claude Sonnet 4 | anthropic.claude-sonnet-4-20250514-v1:0 |  | 

## 요청의 토큰 수 계산
<a name="count-tokens-use"></a>

추론 요청의 입력 토큰 수를 계산하려면 [Amazon Bedrock 런타임 엔드포인트](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)를 사용하여 [CountTokens](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_CountTokens.html) 요청을 보냅니다. 헤더에 모델을 지정하고 `body` 필드에 대한 토큰을 계산할 입력을 지정합니다. `body` 필드 값은 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 또는 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 요청에 대한 입력 토큰을 계산하는지 여부에 따라 달라집니다.
+ `InvokeModel` 요청의 경우 `body`의 형식은 지정한 모델에 따라 형식이 달라지는 JSON 객체를 나타내는 문자열입니다.
+ `Converse` 요청의 경우 `body`의 형식은 대화에 포함된 `messages` 및 `system` 프롬프트를 지정하는 JSON 객체입니다.

## 예제 시도
<a name="count-tokens-example"></a>

이 섹션의 예제는 Anthropic Claude 3 Haiku를 사용하여 `InvokeModel` 및 `Converse` 요청에 대한 토큰을 계산할 수 있도록 합니다.

**사전 조건**
+ 를 다운로드했으며 자격 증명AWS SDK for Python (Boto3)과 기본 AWS리전이 자동으로 인식되도록 구성이 설정되어 있습니다.
+ IAM 자격 증명에는 다음 작업에 대한 권한이 있습니다(자세한 내용은 [Amazon Bedrock에 사용되는 작업, 리소스 및 조건 키](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html) 참조).
  + bedrock:CountTokens – `CountTokens` 사용을 허용합니다.
  + bedrock:InvokeModel – `InvokeModel` 및 `Converse` 사용을 허용합니다. 최소한 *arn:\$1\$1Partition\$1:bedrock:\$1\$1Region\$1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0*으로 범위를 지정해야 합니다.

[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 요청에 대한 토큰 수 계산을 시도하려면 다음 Python 코드를 실행합니다.

```
import boto3
import json

bedrock_runtime = boto3.client("bedrock-runtime")

input_to_count = json.dumps({
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 500,
    "messages": [
        {
            "role": "user",
            "content": "What is the capital of France?"
        }
    ]
})

response = bedrock_runtime.count_tokens(
    modelId="anthropic.claude-3-5-haiku-20241022-v1:0",
    input={
        "invokeModel": {
            "body": input_to_count
        }
    }
)

print(response["inputTokens"])
```

[Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 요청에 대한 토큰 수 계산을 시도하려면 다음 Python 코드를 실행합니다.

```
import boto3
import json 

bedrock_runtime = boto3.client("bedrock-runtime")

input_to_count = {
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "text": "What is the capital of France?"
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "text": "The capital of France is Paris."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "What is its population?"
                }
            ]
        }
    ],
    "system": [
        {
            "text": "You're an expert in geography."
        }
    ]
}

response = bedrock_runtime.count_tokens(
    modelId="anthropic.claude-3-5-haiku-20241022-v1:0",
    input={
        "converse": input_to_count
    }
)

print(response["inputTokens"])
```