

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

# Cohere Command 모델
<a name="model-parameters-cohere-command"></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)(스트리밍)을 사용하여 Cohere Command 모델에 대한 추론 요청을 수행합니다. 사용하려는 모델의 모델 ID가 필요합니다. 모델 ID를 가져오려면 [Amazon Bedrock에서 지원되는 파운데이션 모델](models-supported.md) 섹션을 참조하세요.

**Topics**
+ [요청 및 응답](#model-parameters-cohere-command-request-response)
+ [코드 예제](#api-inference-examples-cohere-command)

## 요청 및 응답
<a name="model-parameters-cohere-command-request-response"></a>

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

Cohere Command 모델에는 다음과 같은 추론 파라미터가 있습니다.

```
{
    "prompt": string,
    "temperature": float,
    "p": float,
    "k": float,
    "max_tokens": int,
    "stop_sequences": [string],
    "return_likelihoods": "GENERATION|ALL|NONE",
    "stream": boolean,
    "num_generations": int,
    "logit_bias": {token_id: bias},
    "truncate": "NONE|START|END"
}
```

다음은 필수 파라미터입니다.
+ **prompt** – (필수) 응답을 생성하기 위한 시작점 역할을 하는 입력 텍스트입니다.

  다음은 직접 호출당 텍스트 및 글자 수 제한입니다.

**직접 호출당 텍스트**  
    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)

**글자 수**  
    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)

다음 파라미터는 선택 사항입니다.
+ **return\$1likelihoods** - 토큰 가능도가 응답과 함께 반환되는 방법 및 반환 여부를 지정합니다. 다음과 같은 옵션을 지정할 수 있습니다.
  + `GENERATION` - 생성된 토큰에 대한 가능도만 반환합니다.
  + `ALL` - 모든 토큰에 대한 가능도를 반환합니다.
  + `NONE` - (기본값) 가능도를 반환하지 않습니다.
+ **stream** - (스트리밍을 지원하는 데 필요) `true`로 지정하면 응답을 실시간으로 하나씩 반환하고, `false`로 지정하면 프로세스가 끝난 후 전체 응답을 반환합니다.
+ **logit\$1bias** - 모델에서 원치 않는 토큰이 생성되는 일을 방지하거나, 원하는 토큰을 포함하도록 모델을 장려합니다. 형식은 `{token_id: bias}`이며, 여기서 편향은 -10에서 10 사이의 부동 소수입니다. Cohere의 Tokenize 엔드포인트 같은 토큰화 서비스를 사용하여 텍스트에서 토큰을 얻을 수 있습니다. 자세한 내용은 [Cohere 설명서](https://docs.cohere.com/docs)를 참조하세요.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+  **num\$1generations** - 모델이 반환해야 하는 최대 생성 수입니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+  **truncate** - API가 최대 토큰 길이보다 긴 입력을 처리하는 방법을 지정합니다. 다음 중 하나를 사용하세요.
  + `NONE` - 입력이 최대 입력 토큰 길이를 초과하면 오류가 반환됩니다.
  + `START` - 입력의 시작을 취소합니다.
  + `END` - (기본값) 입력의 종료를 취소합니다.

  `START` 또는 `END` 를 지정할 경우, 모델은 나머지 입력값이 모델의 최대 입력 토큰 길이와 정확히 일치할 때까지 입력값을 취소합니다.
+ **temperature** - 낮은 값을 사용하면 응답의 무작위성을 줄일 수 있습니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **p** - Top P. 낮은 값을 사용하면 확률이 낮은 옵션을 무시할 수 있습니다. 비활성화하려면 0 또는 1.0으로 설정합니다. `p` 및 `k`가 둘 다 활성화된 경우, `p`는 `k` 이후에 작동합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **k** - Top K. 모델이 다음 토큰을 생성하는 데 사용하는 토큰 선택 항목의 개수를 지정합니다. `p` 및 `k`가 둘 다 활성화된 경우, `p`는 `k` 이후에 작동합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **max\$1tokens** - 생성된 응답에서 사용할 최대 토큰 수를 지정합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **stop\$1sequences** - 모델이 인식하는 시퀀스를 최대 4개까지 구성합니다. 중지 시퀀스가 발생한 후에는 모델에서 추가 토큰 생성을 중지합니다. 반환된 텍스트에는 중지 시퀀스가 포함되지 않습니다.

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

응답에는 다음과 같은 필드가 포함될 수 있습니다.

```
{
    "generations": [
        {
            "finish_reason": "COMPLETE | MAX_TOKENS | ERROR | ERROR_TOXIC",
            "id": string,
            "text": string,
            "likelihood" : float,
            "token_likelihoods" : [{"token" : string, "likelihood": float}],
            "is_finished" : true | false,
            "index" : integer
           
        }
    ],
    "id": string,
    "prompt": string
}
```
+ `generations` - 요청한 토큰의 가능도와 함께 생성된 결과 목록. (항상 반환됨). 목록의 각 세대 객체에는 다음 필드가 포함됩니다.
  + `id` - 세대에 대한 식별자입니다. (항상 반환됨).
  + `likelihood` - 출력의 가능도입니다. `token_likelihoods`의 값은 평균 토큰 가능성입니다. `return_likelihoods` 입력 파라미터를 지정하면 반환됩니다.
  + `token_likelihoods` - 토큰별 가능도의 배열입니다. `return_likelihoods` 입력 파라미터를 지정하면 반환됩니다.
  + `finish_reason` - 모델이 토큰 생성을 완료한 이유입니다. `COMPLETE` - 모델이 완료된 응답을 다시 보냈습니다. `MAX_TOKENS` - 모델이 컨텍스트 길이에 대한 최대 토큰 수에 도달하여 응답이 중단되었습니다. `ERROR ` - 응답을 생성할 때 문제가 발생했습니다. `ERROR_TOXIC` - 모델이 유해하다고 간주되는 응답을 생성했습니다. `finish_reason`은 `is_finished`=`true`인 경우에만 반환됩니다. (항상 반환되는 것은 아님).
  + `is_finished` - `stream`이 `true`인 경우에만 사용되는 부울 필드로, 스트리밍 응답의 일부로 생성되는 추가 토큰이 있는지 여부를 나타냅니다. (항상 반환되는 것은 아님).
  + `text` - 생성된 텍스트입니다.
  + `index` - 스트리밍 응답에서 주어진 토큰이 어느 세대에 속하는지 결정하는 데 사용합니다. 응답이 하나만 스트리밍되는 경우, 모든 토큰은 같은 세대에 속하며 인덱스는 반환되지 않습니다. 따라서 `num_generations`에 대한 값이 1보다 큰 스트리밍 요청에서만 `index`가 반환됩니다.
+ `prompt` - 입력 요청의 프롬프트입니다(항상 반환됨).
+ `id` - 요청의 식별자입니다(항상 반환됨).

자세한 내용은 Cohere 설명서의 [Generate](https://docs.cohere.com/reference/generate-1)를 참조하세요.

------

## 코드 예제
<a name="api-inference-examples-cohere-command"></a>

이 예제는 *Cohere Command* 모델을 직접 호출하는 방법을 보여줍니다.

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate text using a Cohere model.
"""
import json
import logging
import boto3


from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_text(model_id, body):
    """
    Generate text using a Cohere model.
    Args:
        model_id (str): The model ID to use.
        body (str) : The reqest body to use.
    Returns:
        dict: The response from the model.
    """

    logger.info("Generating text with Cohere model %s", model_id)

    accept = 'application/json'
    content_type = 'application/json'

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

    response = bedrock.invoke_model(
        body=body,
        modelId=model_id,
        accept=accept,
        contentType=content_type
    )

    logger.info("Successfully generated text with Cohere model %s", model_id)

    return response


def main():
    """
    Entrypoint for Cohere example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = 'cohere.command-text-v14'
    prompt = """Summarize this dialogue: 
"Customer: Please connect me with a support agent.
AI: Hi there, how can I assist you today?
Customer: I forgot my password and lost access to the email affiliated to my account. Can you please help me?
AI: Yes of course. First I'll need to confirm your identity and then I can connect you with one of our support agents.
"""
    try:
        body = json.dumps({
            "prompt": prompt,
            "max_tokens": 200,
            "temperature": 0.6,
            "p": 1,
            "k": 0,
            "num_generations": 2,
            "return_likelihoods": "GENERATION"
        })
        response = generate_text(model_id=model_id,
                                 body=body)

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

        for index, generation in enumerate(generations):

            print(f"Generation {index + 1}\n------------")
            print(f"Text:\n {generation['text']}\n")
            if 'likelihood' in generation:
                print(f"Likelihood:\n {generation['likelihood']}\n")
            
            print(f"Reason: {generation['finish_reason']}\n\n")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    else:
        print(f"Finished generating text with Cohere model {model_id}.")


if __name__ == "__main__":
    main()
```