翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
InvokeModel または InvokeModelWithResponseStream (ストリーミング) を使用して、Cohere Command R および Cohere Command R+ モデルに推論呼び出しを行います。このとき、使用するモデルのモデル ID が必要になります。モデル ID を取得するには、「Amazon Bedrock でサポートされている基盤モデル」を参照してください。
ヒント
会話アプリケーションの場合は、 Converse API を使用することをお勧めします。Converse API は、メッセージをサポートするすべてのモデルで動作するパラメータの統合セットを提供します。詳細については、「Converse API オペレーションとの会話を実行する」を参照してください。
トピック
リクエストとレスポンス
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 ドキュメント」の「ドキュメントモードガイド」を参照してください。 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
パラメータの値を増やすことでさらに最大化できます。デフォルト値 最小値 最大値 0.3
0
1
-
p – 低い値を指定すると、可能性の低い選択肢を無視することができます。
デフォルト値 最小値 最大値 0.75
0.01
0.99
-
k – Top K。モデルが次のテキストを生成するために使用するトークン選択数を指定します。
デフォルト値 最小値 最大値 0
0
500
-
prompt_truncation – デフォルトは
OFF
です。プロンプトの構築方法を指定します。prompt_truncation
をAUTO_PRESERVE_ORDER
に設定するとchat_history
およびdocuments
の一部の要素はモデルのコンテキスト長制限内のプロンプトの構成を中断します。このプロセス中、ドキュメントとチャット履歴の順序は維持されます。prompt_truncation
` をOFF
に設定すると、要素は中断されません。 -
frequency_penalty – 生成されたトークンの反復性を減らすために使用します。値が高いほど、以前に存在したトークンにより強力なペナルティが適用されます。これは、プロンプトまたは以前の世代に既に出現した回数に比例します。
デフォルト値 最小値 最大値 0
0
1
-
presence_penalty – 生成されたトークンの反復性を減らすために使用します。
frequency_penalty
と似ていますが、このペナルティは、正確な頻度に関係なく、すでに出現したすべてのトークンに平等に適用される点が異なります。デフォルト値 最小値 最大値 0
0
1
-
seed – 指定した場合、バックエンドは決定的にトークンをサンプリングするために最善を尽くします。これにより、同じシードとパラメータを持つリクエストを繰り返すと、同じ結果が返されます。ただし、決定論を完全に保証することはできません。
-
return_prompt – モデルに送信された完全なプロンプトを返すように
true
を指定します。デフォルト値はfalse
です。レスポンスの場合、prompt
フィールドのプロンプトです。 -
tools – テキストレスポンスを生成する前にモデルが呼び出す場合がある利用可能なツール (関数) の一覧。
tools
が (tool_results
なしで) 渡されると、レスポンスのtext
フィールドは、""
となり、レスポンスのtool_calls
フィールドには、呼び出しが必要なツール呼び出しが入力されます。呼び出しを行う必要がない場合、tool_calls
配列は空欄になります。詳細については、「Cohere ドキュメント」の「ツールの使用
」を参照してください。 ヒント
ツールの使用をアプリケーションに統合するには、 Converse API を使用することをお勧めします。詳細については、「ツールを使用して Amazon Bedrock のモデルレスポンスを完成させる」を参照してください。
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 ドキュメント」の「シングルステップツールの使用 (関数呼び出し)
」を参照してください。 -
tools_results – 前のチャットターンでモデルが推奨するツールを呼び出す結果のリスト。結果はテキストレスポンスの生成に使用され、引用で参照されます。
tool_results
を使用する場合、tools
も渡す必要があります。各tool_result
には、呼び出し方法に関する情報と、ディクショナリ形式の出力のリストが含まれています。Cohere 独自のきめ細かな引用ロジックでは、出力を一覧化する必要があります。出力が{"status": 200}
など 1 つのみの場合でも、リスト内で囲う必要があります。詳細については、「Cohere ドキュメント」の「ツールの使用
」を参照してください。 tools_results
フィールドの JSON 例は次のとおりです。[ { "call": { "name": "top_song", "parameters": { "sign": "WZPZ" } }, "outputs": [ { "song": "Elemental Hotel" } ] } ]
-
stop_sequences – ストップシーケンスのリスト。ストップシーケンスが検出されたら、モデルは、それ以降のトークン生成を停止します。
-
raw_prompting –
true
を指定して、事前処理を行う前に、ユーザーのmessage
をモデルに送信します。送信しない場合は、False を指定します。
コード例
この例は、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()