

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

# Anthropic Claude Text Completions API
<a name="model-parameters-anthropic-claude-text-completion"></a>

이 섹션에서는 Text Completions API와 함께 Anthropic Claude 모델을 사용하기 위한 추론 파라미터와 코드 예제를 제공합니다.

**Topics**
+ [Anthropic Claude Text Completions API 개요](#model-parameters-anthropic-claude-text-completion-overview)
+ [지원되는 모델](#claude-messages-supported-models)
+ [요청 및 응답](#model-parameters-anthropic-claude-text-completion-request-response)
+ [코드 예제](#api-inference-examples-claude-text-completion)

## Anthropic Claude Text Completions API 개요
<a name="model-parameters-anthropic-claude-text-completion-overview"></a>

사용자 제공 프롬프트에서 단일 턴으로 텍스트를 생성하려면 Text Completions API를 사용합니다. 예를 들어, Text Completions API를 사용하여 블로그 게시물을 위한 텍스트를 생성하거나 사용자의 텍스트 입력을 요약할 수 있습니다.

Anthropic Claude 모델에 대한 프롬프트 생성에 관한 자세한 내용은 [프롬프트 엔지니어링 개요](https://docs.anthropic.com/claude/docs/introduction-to-prompt-design)를 참조하세요. 기존 Text Completions 프롬프트를 [Anthropic Claude Messages API](model-parameters-anthropic-claude-messages.md)와 함께 사용하려면 [텍스트 완성에서 마이그레이션하기](https://docs.anthropic.com/claude/reference/migrating-from-text-completions-to-messages)를 참조하세요.

## 지원되는 모델
<a name="claude-messages-supported-models"></a>

Text Completions API를 다음 Anthropic Claude 모델과 함께 사용할 수 있습니다.
+ Anthropic Claude Instant v1.2
+ Anthropic Claude v2
+ Anthropic Claude v2.1 

## 요청 및 응답
<a name="model-parameters-anthropic-claude-text-completion-request-response"></a>

요청 본문이 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 또는 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)에 대한 요청의 `body` 필드에 전달됩니다.

자세한 내용은 Anthropic Claude 설명서의 [https://docs.anthropic.com/claude/reference/complete\$1post](https://docs.anthropic.com/claude/reference/complete_post)를 참조하세요.

------
#### [ Request ]

Anthropic Claude에는 Text Completions 추론 직접 호출에 대한 다음 추론 파라미터가 있습니다.

```
{
    "prompt": "\n\nHuman:<prompt>\n\nAssistant:",
    "temperature": float,
    "top_p": float,
    "top_k": int,
    "max_tokens_to_sample": int,
    "stop_sequences": [string]
}
```

다음은 필수 파라미터입니다.
+  **prompt** – (필수) Claude가 완성하도록 하려는 프롬프트입니다. 적절한 응답 생성을 위해 대체 `\n\nHuman:` 및 `\n\nAssistant:` 대화형 턴을 사용하여 프롬프트 형식을 지정해야 합니다. 예:

  ```
  "\n\nHuman: {userQuestion}\n\nAssistant:"
  ```

  자세한 내용은 Anthropic Claude 설명서의 [프롬프트 검증](https://docs.anthropic.com/claude/reference/prompt-validation)을 참조하세요.
+  **max\$1tokens\$1to\$1sample** – (필수) 중지하기 전에 생성할 최대 토큰 수입니다. 최적의 성능을 위해 토큰을 4,000개로 제한하는 것이 좋습니다.

  참고로 Anthropic Claude 모델은 `max_tokens_to_sample` 값에 도달하기 전에 토큰 생성을 중지할 수 있습니다. Anthropic Claude 모델마다 이 파라미터의 최대값이 다릅니다. 자세한 내용은 Anthropic Claude 설명서에서 [모델 비교](https://docs.anthropic.com/claude/docs/models-overview#model-comparison)를 참조하세요.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)

다음 파라미터는 선택 사항입니다.
+  **stop\$1sequences** – (선택 사항) 모델의 생성을 중지하는 시퀀스입니다.

  Anthropic Claude 모델은 `"\n\nHuman:"`에 중지되며, 향후 기본 제공 중지 시퀀스가 더 포함될 수 있습니다. `stop_sequences` 추론 파라미터를 사용하여 모델이 텍스트 생성을 중지하도록 신호를 보내는 추가 문자열을 포함합니다.
+  **temperature** – (선택 사항) 응답에 주입되는 무작위성의 양입니다. 분석/다중 선택의 경우 0에 가까운 값을 사용하고, 창의적이고 생성적인 작업의 경우 1에 가까운 값을 사용합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)
+  **top\$1p** – (선택 사항) Nucleus 샘플링을 사용합니다.

  Nucleus 샘플링에서 Anthropic Claude는 각 후속 토큰의 모든 옵션에 대한 누적 분포를 확률 내림차순으로 계산하고 `top_p`에서 지정한 특정 확률에 도달하면 이를 차단합니다. `temperature` 또는 `top_p`를 변경해야 하지만, 둘 다 변경해서는 안 됩니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)
+  **top\$1k** – (선택 사항) 각 후속 토큰에 대해 상위 K개 옵션에서만 샘플을 추출합니다.

  `top_k`를 사용하여 롱 테일 낮은 확률 응답을 제거합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)

------
#### [ Response ]

Anthropic Claude 모델은 Text Completion 추론 직접 호출에 대해 다음 필드를 반환합니다.

```
{
    "completion": string,
    "stop_reason": string,
    "stop": string
}
```
+ **completion** - 중지 시퀀스까지의 결과 및 중지 시퀀스를 제외한 결과 완성입니다.
+ **stop\$1reason** – 모델이 응답 생성을 중지한 이유입니다.
  + **"stop\$1sequence"** – 모델이 `stop_sequences` 추론 파라미터와 함께 제공한 중지 시퀀스 또는 모델에 내장된 중지 시퀀스에 도달했습니다.
  + **"max\$1tokens"** – 모델이 `max_tokens_to_sample` 값을 초과한 경우, 또는 모델의 최대 토큰 수입니다.
+ **stop** - `stop_sequences` 추론 파라미터를 지정하는 경우, `stop`에는 모델이 텍스트 생성을 중지하도록 신호를 보내는 중지 시퀀스가 포함됩니다. 예를 들어, 다음 응답의 `holes`가 여기에 해당합니다.

  ```
  {
      "completion": " Here is a simple explanation of black ",
      "stop_reason": "stop_sequence",
      "stop": "holes"
  }
  ```

  `stop_sequences`를 지정하지 않으면 `stop` 값은 비어 있습니다.

------

## 코드 예제
<a name="api-inference-examples-claude-text-completion"></a>

이 예제는 온디맨드 처리량으로 *Anthropic Claude V2* 모델을 직접 호출하는 방법을 보여 줍니다. Anthropic Claude 버전 2.1을 사용하려면 `modelId`의 값을 `anthropic.claude-v2:1`로 변경합니다.

```
import boto3
import json
brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    "prompt": "\n\nHuman: explain black holes to 8th graders\n\nAssistant:",
    "max_tokens_to_sample": 300,
    "temperature": 0.1,
    "top_p": 0.9,
})

modelId = 'anthropic.claude-v2'
accept = 'application/json'
contentType = 'application/json'

response = brt.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)

response_body = json.loads(response.get('body').read())

# text
print(response_body.get('completion'))
```

다음 예제는 *화성에서 살기에 대한 1000단어 에세이 쓰기* 프롬프트와 Anthropic Claude V2 모델을 사용하여 Python으로 스트리밍 텍스트를 생성하는 방법을 보여줍니다.

```
import boto3
import json

brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    'prompt': '\n\nHuman: write an essay for living on mars in 1000 words\n\nAssistant:',
    'max_tokens_to_sample': 4000
})
                   
response = brt.invoke_model_with_response_stream(
    modelId='anthropic.claude-v2', 
    body=body
)
    
stream = response.get('body')
if stream:
    for event in stream:
        chunk = event.get('chunk')
        if chunk:
            print(json.loads(chunk.get('bytes').decode()))
```