

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# 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** – モデルが引用してさらに精度の高い返信を生成するテキストのリスト。各ドキュメントは string-string ディクショナリです。結果の生成には、これらのドキュメントの一部を参照する引用が含まれています。ディクショナリの文字列の合計単語数は 300 語未満にすることが推奨されます。`_excludes` フィールド (文字列の配列) の指定はオプションで、モデルに表示されないように一部のキーと値のペアを省略できます。詳細については、「Cohere ドキュメント」の「[ドキュメントモードガイド](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** – 検索クエリ生成のデフォルトの preamble をオーバーライドします。ツールの使用世代には影響しません。
+ **max\_tokens** – レスポンスの一部としてモデルが生成するトークンの最大数。値を低く設定すると、生成が不完全になる場合がありますのでご注意ください。`tools` または `documents` フィールドで使用する際に、`max_tokens` を設定すると、生成が不完全になったり、生成自体がされない場合があります。
+ **temperature** – 低い値を指定するとレスポンスのランダム性を減らすことができます。ランダム性は、`p` パラメータの値を増やすことでさらに最大化できます。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **p** – 低い値を指定すると、可能性の低い選択肢を無視することができます。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/ja_jp/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/ja_jp/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/ja_jp/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/ja_jp/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 ドキュメント」の「[ツールの使用](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 ドキュメント」の「[シングルステップツールの使用 (関数呼び出し)](https://docs.cohere.com/docs/tool-use)」を参照してください。
+ **tools\_results** – 前のチャットターンでモデルが推奨するツールを呼び出す結果のリスト。結果はテキストレスポンスの生成に使用され、引用で参照されます。`tool_results` を使用する場合、`tools` も渡す必要があります。各 `tool_result` には、呼び出し方法に関する情報と、ディクショナリ形式の出力のリストが含まれています。Cohere 独自のきめ細かな引用ロジックでは、出力を一覧化する必要があります。出力が `{"status": 200}` など 1 つのみの場合でも、リスト内で囲う必要があります。

  詳細については、「Cohere ドキュメント」の「[ツールの使用](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** – `true` を指定して、事前処理を行う前に、ユーザーの `message` をモデルに送信します。送信しない場合は、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 のプラットフォームのフィードバックエンドポイントで使用されるチャット完了の一意の識別子。
+ **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 ドキュメント」の「[ツールの使用](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()
```