翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
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ドキュメントの「プロンプトの概要
システムプロンプト
リクエストにシステムプロンプトを含めることもできます。システムプロンプトを使用すると、特定の目標やロールの指定など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
コードの例
次のコード例は、メッセージ 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()