AnthropicClaude メッセージ API - Amazon Bedrock

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

AnthropicClaude メッセージ API

このセクションでは、AnthropicClaudeMessages API を使用するための推論パラメータとコード例を示します。

AnthropicClaude Messages API の概要

Messages API を使用して、チャットボットまたは仮想アシスタントアプリケーションを作成できます。API は、ユーザーとAnthropicClaudeモデル (アシスタント) の間の会話交換を管理します。

Anthropic は、ユーザーとアシスタントの会話ターンを交互に操作するように Claude モデルをトレーニングします。新しいメッセージを作成するときは、メッセージパラメータを使用して以前の会話ターンを指定します。次に、モデルは会話で次のメッセージを生成します。

各入力メッセージは、ロールとコンテンツを含むオブジェクトである必要があります。1 つのユーザーロールメッセージを指定することも、複数のユーザーおよびアシスタントメッセージを含めることもできます。最初のメッセージは常にユーザーロールを使用する必要があります。

からの応答を事前入力する手法を使用している場合 Claude (最終的なアシスタントロール Message を使用して Claude の応答の先頭に を入力)、 Claudeは中断した場所から応答します。この方法では、 Claudeはアシスタントロールを含むレスポンスを返します。

最後のメッセージがアシスタントロールを使用する場合、レスポンスの内容は、そのメッセージのコンテンツからすぐに続行されます。これを使用して、モデルのレスポンスの一部を制限できます。

単一のユーザーメッセージの例:

[{"role": "user", "content": "Hello, Claude"}]

会話ターンが複数ある例:

[ {"role": "user", "content": "Hello there."}, {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"}, {"role": "user", "content": "Can you explain LLMs in plain English?"}, ]

Claude からのレスポンスが部分的に入力されている例:

[ {"role": "user", "content": "Please describe yourself using only JSON"}, {"role": "assistant", "content": "Here is my JSON description:\n{"}, ]

各入力メッセージコンテンツは、1 つの文字列でも、コンテンツブロックの配列でもかまいません。各ブロックには特定のタイプがあります。文字列の使用は、「text」型の 1 つのコンテンツブロックの配列の省略形です。次の入力メッセージは同等です。

{"role": "user", "content": "Hello, Claude"}
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}

Anthropic Claude モデルのプロンプトの作成については、 AnthropicClaudeドキュメントの「プロンプトの概要」を参照してください。メッセージ API に移行する既存のテキスト完了プロンプトがある場合は、「テキスト完了からの移行」を参照してください。

システムプロンプト

リクエストにシステムプロンプトを含めることもできます。システムプロンプトを使用すると、特定の目標やロールの指定などClaude、コンテキストと指示を Anthropic に提供できます。次の例に示すように、 systemフィールドにシステムプロンプトを指定します。

"system": "You are Claude, an AI assistant created by Anthropic to be helpful, harmless, and honest. Your goal is to provide informative and substantive responses to queries while avoiding potential harms."

詳細については、 Anthropicドキュメントの「システムプロンプト」を参照してください。

マルチモーダルプロンプト

マルチモーダルプロンプトは、複数のモダリティ (画像とテキスト) を 1 つのプロンプトに結合します。content 入力フィールドにモダリティを指定します。次の例は、提供されたイメージの内容を記述AnthropicClaudeするように に求める方法を示しています。サンプルコードについては、「マルチモーダルコードの例」を参照してください。

{ "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "messages": [ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "iVBORw..." } }, { "type": "text", "text": "What's in these images?" } ] } ] }

モデルには最大 20 個のイメージを指定できます。アシスタントロールにイメージを配置することはできません。

リクエストに含める各イメージは、トークンの使用量にカウントされます。詳細については、 Anthropicドキュメントの「イメージコスト」を参照してください。

サポートされているモデル

Messages API は、次のAnthropicClaudeモデルで使用できます。

  • Anthropic Claude Instant v1.2

  • Anthropic Claude 2 v2

  • Anthropic Claude 2 v2.1

  • Anthropic Claude 3 Sonnet

  • Anthropic Claude 3 Haiku

  • Anthropic Claude 3 Opus

リクエストとレスポンス

リクエスト本文は、 InvokeModelまたは へのリクエストの bodyフィールドに渡されますInvokeModelWithResponseStream。リクエストで送信できるペイロードの最大サイズは 20MBです。

詳細については、https://docs.anthropic.com/claude/reference/messages_post を参照してください。

Request

Anthropic Claude には、メッセージ推論呼び出しの次の推論パラメータがあります。

{ "anthropic_version": "bedrock-2023-05-31", "max_tokens": int, "system": string, "messages": [ { "role": string, "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "content image bytes" } }, { "type": "text", "text": "content text" } ] } ], "temperature": float, "top_p": float, "top_k": int, "stop_sequences": [string] }

必須パラメータを以下に示します。

  • anthropic_version – (必須) anthropic バージョン。値は bedrock-2023-05-31 にする必要があります。

  • max_tokens – (必須) 停止する前に生成するトークンの最大数。

    Anthropic Claude モデルは、 の値に達する前にトークンの生成を停止する場合があることに注意してくださいmax_tokens。このパラメータの最大値はAnthropicClaudeモデルによって異なります。詳細については、「モデル比較」を参照してください。

  • messages – (必須) 入力メッセージ。

    • role – 会話ターンのロール。有効な値は、user および assistant です。

    • content – (必須) 会話ターンの内容。

      • type – (必須) コンテンツのタイプ。有効な値は、image および text です。

        を指定する場合はimage、次の形式でイメージソースも指定する必要があります。

        source – (必須) 会話ターンの内容。

        • type – (必須) イメージのエンコードタイプ。を指定できますbase64

        • media_type – (必須) イメージのタイプ。次のイメージ形式を指定できます。

          • image/jpeg

          • image/png

          • image/webp

          • image/gif

        • data – (必須) イメージの base64 でエンコードされたイメージのバイト数。最大イメージサイズは 3.75 MB です。イメージの最大の高さと幅は 8000 ピクセルです。

        を指定する場合はtext、 でプロンプトも指定する必要がありますtext

オプションのパラメータを以下に示します。

  • system – (オプション) リクエストのシステムプロンプト。

    システムプロンプトは、特定の目標やロールを指定するなどClaude、コンテキストと指示を Anthropic に提供する方法です。詳細については、 Anthropicドキュメントの「システムプロンプトの使用方法」を参照してください。

    注記

    Anthropic Claude バージョン 2.1 以降では、システムプロンプトを使用できます。

  • stop_sequences – (オプション) モデルの生成を停止するカスタムテキストシーケンス。AnthropicClaudeモデルは通常、ターンを自然に完了すると停止します。この場合、stop_reasonレスポンスフィールドの値は ですend_turn。カスタムテキスト文字列を検出したときにモデルの生成を停止する場合は、 stop_sequencesパラメータを使用できます。モデルがカスタムテキスト文字列の 1 つに遭遇した場合、stop_reasonレスポンスフィールドの値は stop_sequenceで、 の値には一致した停止シーケンスstop_sequenceが含まれます。

    エントリの最大数は 8191 です。

  • temperature – (オプション) レスポンスに挿入されるランダム性の量。

    デフォルト値 最小値 最大値

    1

    0

    1

  • top_p – (オプション) nucleus サンプリングを使用します。

    nucleus サンプリングでは、 は、後続の各トークンのすべてのオプションに対する累積分布を低い確率順でAnthropicClaude計算し、 で指定された特定の確率に達すると切り捨てますtop_ptemperature または のいずれかを変更する必要がありますがtop_p、両方を変更することはできません。

    デフォルト値 最小値 最大値

    0.999

    0

    1

オプションのパラメータを以下に示します。

  • top_k – (オプション) 後続の各トークンの上位 K オプションからのみサンプリングします。

    を使用してtop_k、ロングテールの低確率レスポンスを削除します。

    デフォルト値 最小値 最大値

    デフォルトでは無効になっています

    0

    500

Response

このAnthropicClaudeモデルは、メッセージ推論呼び出しに対して次のフィールドを返します。

{ "id": string, "model": string, "type" : "message", "role" : "assistant", "content": [ { "type": "text", "text": string } ], "stop_reason": string, "stop_sequence": string, "usage": { "input_tokens": integer, "output_tokens": integer } }
  • id – レスポンスの一意の識別子。ID の形式と長さは、時間の経過とともに変更される可能性があります。

  • model – リクエストを行ったAnthropicClaudeモデルの ID。

  • stop_reason – がレスポンスの生成AnthropicClaudeを停止した理由。

    • end_turn – モデルが自然な停止ポイントに到達しました

    • max_tokens – 生成されたテキストがmax_tokens入力フィールドの値を超えたか、モデルがサポートするトークンの最大数を超えました。

    • stop_sequence – モデルは、stop_sequences入力フィールドで指定した停止シーケンスの 1 つを生成しました。

  • type – レスポンスのタイプ。値は常に message です。

  • role – 生成されたメッセージの会話ロール。値は常に assistant です。

  • content – モデルによって生成されたコンテンツ。配列として返されます。

    • type – コンテンツのタイプ。現在、サポートされている値は text のみです。

    • text – コンテンツのテキスト。

  • usage – リクエストで指定したトークンの数と、モデルがレスポンスで生成したトークンの数のコンテナ。

    • input_tokens – リクエスト内の入力トークンの数。

    • output_tokens – モデルがレスポンスで生成した の数トークン。

    • stop_sequence – モデルは、stop_sequences入力フィールドで指定した停止シーケンスの 1 つを生成しました。

コードの例

次のコード例は、メッセージ API の使用方法を示しています。

メッセージコードの例

この例では、1 回のターンユーザーメッセージを送信し、ユーザーが事前入力済みのアシスタントメッセージでモデルを切り替える方法を示しますAnthropicClaude 3 Sonnet。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate a message with Anthropic Claude (on demand). """ import boto3 import json import logging from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_message(bedrock_runtime, model_id, system_prompt, messages, max_tokens): body=json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "system": system_prompt, "messages": messages } ) response = bedrock_runtime.invoke_model(body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude message example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' system_prompt = "Please respond only with emoji." max_tokens = 1000 # Prompt with user turn only. user_message = {"role": "user", "content": "Hello World"} messages = [user_message] response = generate_message (bedrock_runtime, model_id, system_prompt, messages, max_tokens) print("User turn only.") print(json.dumps(response, indent=4)) # Prompt with both user turn and prefilled assistant response. #Anthropic Claude continues by using the prefilled assistant text. assistant_message = {"role": "assistant", "content": "<emoji>"} messages = [user_message, assistant_message] response = generate_message(bedrock_runtime, model_id,system_prompt, messages, max_tokens) print("User turn and prefilled assistant response.") print(json.dumps(response, indent=4)) except ClientError as err: message=err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

マルチモーダルコードの例

次の例は、マルチモーダルメッセージの画像とプロンプトテキストをAnthropicClaude 3 Sonnetモデルに渡す方法を示しています。

を使用したマルチモーダルプロンプト InvokeModel

次の例は、 AnthropicClaude 3 Sonnetを使用してマルチモーダルプロンプトを に送信する方法を示していますInvokeModel

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to run a multimodal prompt with Anthropic Claude (on demand) and InvokeModel. """ import json import logging import base64 import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens): """ Invokes a model with a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. messages (JSON) : The messages to send to the model. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ body = json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": messages } ) response = bedrock_runtime.invoke_model( body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude multimodal prompt example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' max_tokens = 1000 input_image = "/path/to/image" input_text = "What's in this image?" # Read reference image from file and encode as base64 strings. with open(input_image, "rb") as image_file: content_image = base64.b64encode(image_file.read()).decode('utf8') message = {"role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": content_image}}, {"type": "text", "text": input_text} ]} messages = [message] response = run_multi_modal_prompt( bedrock_runtime, model_id, messages, max_tokens) print(json.dumps(response, indent=4)) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

を使用したマルチモーダルプロンプトのストリーミング InvokeModelWithResponseStream

次の例は、 AnthropicClaude 3 Sonnetで に送信されたマルチモーダルプロンプトからレスポンスをストリーミングする方法を示していますInvokeModelWithResponseStream

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to stream the response from Anthropic Claude Sonnet (on demand) for a multimodal request. """ import json import base64 import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def stream_multi_modal_prompt(bedrock_runtime, model_id, input_text, image, max_tokens): """ Streams the response from a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. input_text (str) : The prompt text image (str) : The path to an image that you want in the prompt. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ with open(image, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) body = json.dumps({ "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": [ { "role": "user", "content": [ {"type": "text", "text": input_text}, {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": encoded_string.decode('utf-8')}} ] } ] }) response = bedrock_runtime.invoke_model_with_response_stream( body=body, modelId=model_id) for event in response.get("body"): chunk = json.loads(event["chunk"]["bytes"]) if chunk['type'] == 'message_delta': print(f"\nStop reason: {chunk['delta']['stop_reason']}") print(f"Stop sequence: {chunk['delta']['stop_sequence']}") print(f"Output tokens: {chunk['usage']['output_tokens']}") if chunk['type'] == 'content_block_delta': if chunk['delta']['type'] == 'text_delta': print(chunk['delta']['text'], end="") def main(): """ Entrypoint for Anthropic Claude Sonnet multimodal prompt example. """ model_id = "anthropic.claude-3-sonnet-20240229-v1:0" input_text = "What can you tell me about this image?" image = "/path/to/image" max_tokens = 100 try: bedrock_runtime = boto3.client('bedrock-runtime') stream_multi_modal_prompt( bedrock_runtime, model_id, input_text, image, max_tokens) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()