

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

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

**작은 정보**  
대화형 애플리케이션의 경우 Converse API를 사용하는 것이 좋습니다. Converse API는 메시지를 지원하는 모든 모델에서 작동하는 통합 파라미터 세트를 제공합니다. 자세한 내용은 [Converse API를 사용한 추론](conversation-inference.md) 단원을 참조하십시오.

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

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

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

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

```
{
    "message": string,
    "chat_history": [
        {
            "role":"{{USER or CHATBOT}}",
            "message": string
        }
  
    ],
    "documents": [
        {"title": string, "snippet": string},
    ],
    "search_queries_only" : boolean,
    "preamble" : string,
    "max_tokens": int,
    "temperature": float,
    "p": float,
    "k": float,
    "prompt_truncation" : string,
    "frequency_penalty" : float,
    "presence_penalty" : float,
    "seed" : int,
    "return_prompt" : boolean,
    "tools" : [
        {
            "name": string,
            "description": string,
            "parameter_definitions": {
                "{{parameter name}}": {
                    "description": string,
                    "type": string,
                    "required": boolean
                }
            }
        }
    ],
    "tool_results" : [
        {
            "call": {
                "name": string,
                "parameters": {
                "{{parameter name}}": string
                }
            },
        "outputs": [
                {
                "{{text}}": string
                }
            ]
        }
    ],
    "stop_sequences": [string],
    "raw_prompting" : boolean

}
```

다음은 필수 파라미터입니다.
+ **message** - (필수) 모델이 응답할 텍스트 입력입니다.

다음 파라미터는 선택 사항입니다.
+ **chat\_history** - 사용자와 모델 간의 이전 메시지 목록으로, 모델이 사용자 메시지에 응답할 수 있는 대화적 맥락을 제공합니다.

  필수 필드는 다음과 같습니다.
  + `role` - 메시지의 역할입니다. 유효한 값은 `USER` 또는 `CHATBOT` 토큰입니다.
  + `message` - 메시지의 텍스트 콘텐츠입니다.

  다음은 `chat_history` 필드에 대한 JSON 예제입니다.

  ```
  "chat_history": [
  {"role": "USER", "message": "Who discovered gravity?"},
  {"role": "CHATBOT", "message": "The man who is widely credited with discovering gravity is Sir Isaac Newton"}
  ]
  ```
+ **documents** - 모델이 보다 정확한 응답을 생성하기 위해 인용할 수 있는 텍스트 목록입니다. 각 문서는 문자열-문자열 사전입니다. 결과 생성에는 이러한 문서 중 일부를 참조하는 인용이 포함됩니다. 사전에서 문자열의 총 단어 수를 300단어 미만으로 유지하는 것이 좋습니다. 일부 키-값 페어가 모델에 표시되지 않도록 `_excludes` 필드(문자열 배열)를 선택적으로 제공할 수 있습니다. 자세한 내용은 Cohere 설명서의 [Document Mode guide](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode)를 참조하세요.

  다음은 `documents` 필드에 대한 JSON 예제입니다.

  ```
  "documents": [
  {"title": "Tall penguins", "snippet": "Emperor penguins are the tallest."},
  {"title": "Penguin habitats", "snippet": "Emperor penguins only live in Antarctica."}
  ]
  ```
+ **search\_queries\_only** – 기본값은 `false`입니다. 값이 `true`인 경우, 응답에는 생성된 검색 쿼리 목록만 포함되지만 검색은 수행되지 않으며 모델에서 사용자의 `message`에 대한 응답도 생성되지 않습니다.
+ **preamble** - 검색 쿼리 생성을 위한 기본 프리앰블을 재정의합니다. 도구 사용 생성에는 영향을 미치지 않습니다.
+ **max\_tokens** – 모델이 응답의 일부로 생성해야 하는 최대 토큰 수입니다. 값을 낮게 설정하면 불완전한 생성으로 이어질 수 있습니다. `tools` 또는 `documents` 필드와 함께 사용할 경우 `max_tokens`를 설정하면 생성이 불완전하거나 전혀 이루어지지 않을 수 있습니다.
+ **temperature** - 낮은 값을 사용하면 응답의 무작위성을 줄일 수 있습니다. `p` 파라미터 값을 증가시켜 무작위성을 더욱 극대화할 수 있습니다.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **p** - Top P. 낮은 값을 사용하면 확률이 낮은 옵션을 무시할 수 있습니다.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **k** - Top K. 모델이 다음 토큰을 생성하는 데 사용하는 토큰 선택 항목의 개수를 지정합니다.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+  **prompt\_truncation** – 기본값은 `OFF`입니다. 프롬프트가 구성되는 방법을 지정합니다. `prompt_truncation`을 `AUTO_PRESERVE_ORDER`로 설정하면 `chat_history` 및 `documents`의 일부 요소가 삭제되어 모델의 컨텍스트 길이 제한에 맞는 프롬프트를 구성합니다. 이 프로세스 과정에서 문서 및 채팅 기록의 순서는 보존됩니다. `prompt_truncation`을 `OFF`로 설정하면 아무 요소도 삭제되지 않습니다.
+  **frequency\_penalty** – 생성된 토큰의 반복성을 줄이는 데 사용됩니다. 값이 높을수록 이전에 존재했던 토큰에 적용되는 페널티가 더 강해지고, 이는 프롬프트나 이전 생성에서 해당 토큰이 이미 나타난 횟수에 비례합니다.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+  **presence\_penalty** – 생성된 토큰의 반복성을 줄이는 데 사용됩니다. `frequency_penalty`와 비슷하지만, 이 페널티는 정확한 빈도에 관계없이 이미 등장한 모든 토큰에 동일하게 적용됩니다.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **seed** – 시드가 지정된 경우 백엔드는 토큰을 확정적으로 샘플링하기 위해 최선의 작업을 수행하며, 동일한 시드와 파라미터를 사용하여 반복된 요청은 동일한 결과를 반환해야 합니다. 그러나 확정성을 완전히 보장할 수는 없습니다.
+ **return\_prompt** - 모델에 전송된 전체 프롬프트를 반환하도록 `true`로 지정합니다. 기본값은 `false`입니다. 응답에서 `prompt` 필드의 프롬프트입니다.
+ **tools** - 모델이 텍스트 응답을 생성하기 전에 간접 호출을 제안할 수 있는 사용 가능한 도구(함수) 목록입니다. `tools`가 (`tool_results` 없이) 전달되면 응답의 `text` 필드는 `""`가 되고 응답의 `tool_calls` 필드는 필요한 도구 직접 호출 목록으로 채워집니다. 직접 호출을 수행할 필요가 없는 경우 `tool_calls` 배열이 비어 있습니다.

  자세한 내용은 Cohere 설명서의 [Tool Use](https://docs.cohere.com/docs/tool-use)를 참조하세요.
**작은 정보**  
도구 사용을 애플리케이션에 통합하려면 Converse API를 사용하는 것이 좋습니다. 자세한 내용은 [도구를 사용하여 Amazon Bedrock 모델 응답 완성](tool-use.md) 단원을 참조하십시오.

  다음은 `tools` 필드에 대한 JSON 예제입니다.

  ```
  [
      {
          "name": "top_song",
          "description": "Get the most popular song played on a radio station.",
          "parameter_definitions": {
              "sign": {
                  "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP.",
                  "type": "str",
                  "required": true
              }
          }
      }
  ]
  ```

  자세한 내용은 Cohere 설명서의 [Single-Step Tool Use (Function Calling)](https://docs.cohere.com/docs/tool-use)를 참조하세요.
+ **tools\_results** - 이전 채팅 턴에서 모델이 권장한 간접 호출 도구의 결과 목록입니다. 결과는 텍스트 응답을 생성하는 데 사용되며 인용에서 참조됩니다. `tool_results`를 사용할 때는 `tools`도 전달해야 합니다. 각 `tool_result`에는 간접 호출 방법에 대한 정보와 사전 형식의 출력 목록이 포함되어 있습니다. Cohere의 고유하고 세분화된 인용 로직을 사용하려면 출력이 목록이어야 합니다. 출력이 `{"status": 200}` 같은 하나의 항목인 경우에도 목록 안에 래핑해야 합니다.

  자세한 내용은 Cohere 설명서의 [Tool Use](https://docs.cohere.com/docs/tool-use)를 참조하세요.

  다음은 `tools_results` 필드에 대한 JSON 예제입니다.

  ```
  [
      {
          "call": {
              "name": "top_song",
              "parameters": {
                  "sign": "WZPZ"
              }
          },
          "outputs": [
              {
                  "song": "Elemental Hotel"
              }
          ]
      }
  ]
  ```
+  **stop\_sequences** – 중지 시퀀스 목록입니다. 중지 시퀀스가 감지된 후에는 모델에서 추가 토큰 생성을 중지합니다.
+  **raw\_prompting** - 사전 처리 없이 사용자의 `message`를 모델로 보내려면 `true`를 지정하고, 그렇지 않으면 false를 지정합니다.

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

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

```
{
    "response_id": string,
    "text": string,
    "generation_id": string,
    "citations": [
        {
          "start": int,
          "end": int,
          "text": "string",
          "document_ids": [
              "string"
          ]
        }
      ],    
    "finish_reason": string,
    "tool_calls": [
        {
            "name": string,
            "parameters": {
                "{{parameter name}}": string
            }
        }
    ],
    {
    "meta": {
        "api_version": {
            "version": string
        },
        "billed_units": {
            "input_tokens": int,
            "output_tokens": int
        }
    }
}
```
+ **response\_id** — 채팅 완성을 위한 고유 식별자입니다.
+ **text** - 채팅 메시지 입력에 대한 모델의 응답입니다.
+ **generation\_id** - 채팅 완성을 위한 고유 식별자로, Cohere의 플랫폼에서 Feedback 엔드포인트와 함께 사용됩니다.
+ **citations** - 생성된 답변에 대한 인라인 인용 및 관련 메타데이터 배열입니다. 다음 필드가 포함됩니다.
  + **start** - 인용이 시작되는 인덱스로, 0부터 시작합니다.
  + **end** - 인용이 끝나는 인덱스로, 0부터 시작합니다.
  + **text** - 인용과 관련된 텍스트입니다.
  + **document\_ids** - 텍스트에 대해 인용된 문서에 해당하는 문서 ID 배열입니다.
+ **prompt** - 모델로 전송된 전체 프롬프트입니다. 이 필드를 반환할 `return_prompt` 필드를 지정합니다.
+ **finish\_reason** - 모델이 출력 생성을 중단한 이유입니다. 다음 중 하나일 수 있습니다.
  + **complete** - 생성 토큰의 마지막에 도달했음을 뜻합니다. 최상의 성능을 보장하는 종료 이유인지 확인해야 합니다.
  + **error\_toxic** - 콘텐츠 필터로 인해 생성을 완료할 수 없습니다.
  + **error\_limit** - 모델의 컨텍스트 제한에 도달하여 생성을 완료할 수 없습니다.
  + **error** - 오류로 인해 생성을 완료할 수 없습니다.
  + **user\_cancel** - 사용자가 생성을 중지했기 때문에 생성을 완료할 수 없습니다.
  + **max\_tokens** - 사용자가 요청에 `max_tokens` 제한을 지정했고 이 제한에 도달했기 때문에 생성을 완료할 수 없습니다. 최상의 성능을 얻지 못할 수 있습니다.
+ **tool\_calls** - 직접 호출할 적절한 도구 목록입니다. `tools` 입력 필드를 지정한 경우에만 반환됩니다.

  자세한 내용은 Cohere 설명서의 [Tool Use](https://docs.cohere.com/docs/tool-use)를 참조하세요.
**작은 정보**  
도구 사용을 애플리케이션에 통합하려면 Converse API를 사용하는 것이 좋습니다. 자세한 내용은 [도구를 사용하여 Amazon Bedrock 모델 응답 완성](tool-use.md) 단원을 참조하십시오.

  다음은 `tool_calls` 필드에 대한 JSON 예제입니다.

  ```
  [
          {
              "name": "top_song",
              "parameters": {
                  "sign": "WZPZ"
              }
          }
      ]
  ```
+ **meta** - API 사용 데이터(스트리밍에만 존재)입니다.
  + `api_version` - API 버전입니다. 버전은 `version` 필드에 있습니다.
  + `billed_units` - 청구된 단위입니다. 가능한 값은 다음과 같습니다.
    + `input_tokens` - 청구된 입력 토큰 수입니다.
    + `output_tokens` - 청구된 출력 토큰 수입니다.

------

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

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

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the  Cohere Command R 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 Command R 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)

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

    response = bedrock.invoke_model(
        body=body,
        modelId=model_id
    )

    logger.info(
        "Successfully generated text with Cohere Command R 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-r-v1:0'
    chat_history = [
        {"role": "USER", "message": "What is an interesting new role in AI if I don't have an ML background?"},
        {"role": "CHATBOT", "message": "You could explore being a prompt engineer!"}
    ]
    message = "What are some skills I should have?"

    try:
        body = json.dumps({
            "message": message,
            "chat_history": chat_history,
            "max_tokens": 2000,
            "temperature": 0.6,
            "p": 0.5,
            "k": 250
        })
        response = generate_text(model_id=model_id,
                                 body=body)

        response_body = json.loads(response.get('body').read())
        response_chat_history = response_body.get('chat_history')
        print('Chat history\n------------')
        for response_message in response_chat_history:
            if 'message' in response_message:
                print(f"Role: {response_message['role']}")
                print(f"Message: {response_message['message']}\n")
        print("Generated text\n--------------")
        print(f"Stop reason: {response_body['finish_reason']}")
        print(f"Response text: \n{response_body['text']}")

    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()
```