

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

# 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/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command.html)

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

オプションのパラメータを以下に示します。
+ **return\$1likelihoods** – トークンの可能性をレスポンスとともに返すかどうかと、返す場合の返し方を指定します。以下のオプションを指定できます。
  + `GENERATION` - 生成されたトークンの可能性のみを返します。
  + `ALL` - すべてのトークンの可能性を返します。
  + `NONE` - (デフォルト値) 可能性を一切返しません。
+ **stream** – (ストリーミングをサポートする場合は必須) `true` を指定するとレスポンスが項目ごとにリアルタイムで返され、`false` を指定すると、プロセス終了後に、レスポンス全体が返されます。
+ **logit\$1bias** – モデルによる不要なトークンのが生成が行われないようにしたり、希望するトークンを含むようにモデルにインセンティブを付与したりします。形式は `{token_id: bias}` です。ここで、bias は -10 から 10 までの間にある浮動小数値です。トークンは、Cohere の Tokenize エンドポイントなど、どのトークン化サービスを使用した場合でも、テキストから取得できます。詳細については、「[Cohere ドキュメント](https://docs.cohere.com/docs)」を参照してください。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command.html)
+  **num\$1generations** – モデルが返す最大世代数。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/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/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **p** – 低い値を指定すると、可能性の低い選択肢を無視することができます。0 または 1.0 に設定すると、このオプションは無効になります。`p` と `k` を両方とも有効にした場合は、`k` が動作した後に `p` が動作します。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **k** – Top K。モデルが次のテキストを生成するために使用するトークン選択数を指定します。`p` と `k` を両方とも有効にした場合は、`k` が動作した後に `p` が動作します。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-cohere-command.html)
+ **max\$1tokens** – 生成されたレスポンスで使用するトークンの最大数を指定します。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/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` - 生成された結果と、リクエストされたトークンの可能性から成るリスト。(常に返されます)。リストの各世代 (generation) オブジェクトには、以下のフィールドを指定します。
  + `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` - ストリーミングレスポンスにおいて、特定のトークンがどの世代に属しているかを判断するのに使用されます。1 つのレスポンスのみがストリーミングされる場合、すべてのトークンが同じ世代に属し、index の値は返されません。 そのため、`index` が返されるのは、ストリーミングリクエストにおいて `num_generations` の値が 1 より大きい場合に限ります。
+ `prompt` — 入力リクエストからのプロンプト (常に返されます)。
+ `id` - リクエストの識別子 (常に返されます)。

詳細については、「Cohere ドキュメント」の「[生成](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()
```