この記事は約3分で読めます。
はじめに
Amazon Bedrock は AWS が提供する生成 AI のマネージドサービスであり、複数の大規模言語モデル(LLM)や基盤モデルへのアクセスを提供します。Bedrock では LLM を利用するために 2 つの主要な API が用意されています。それが InvokeModel API と Converse API です。
本記事ではこれら 2 つの API の機能と設計上の違いと具体的なプログラムからの呼び出し例について記載します。
InvokeModel API と Converse API の概要
以降は Python からの利用を想定し、boto3 の BedrockRuntime クラスのメソッドを例に解説します。
API | 概要 |
---|---|
InvokeModel | 抽象化レベルが低い API。各種モデルのプロバイダーの仕様に合わせて呼び出す必要がある。 |
Converse | 抽象化レベルが高い API。各種モデルのプロバイダーの仕様の差異を吸収しており、統一された呼び出しが可能。 |
InvokeModel のリクエストパラメータ
パラメータ | 概要 |
---|---|
modelId | 使用するモデルの ID |
body | モデルに送る実際のデータ(プロンプトなど) |
contentType | リクエスト本文の MIME タイプ |
accept | レスポンスの MIME タイプ |
trace | Bedrock のトレース機能の有効または無効を設定 |
guardrailIdentifier | 適用したいガードレールの一意の識別子 |
guardrailVersion | 使用するガードレールのバージョン番号 |
performanceConfigLatency | リクエストのモデルパフォーマンス設定 |
Converse のリクエストパラメータ
パラメータ | 概要 |
---|---|
modelId | 使用するモデルの ID |
messages | モデルとの会話内容の配列(role と content を含む) |
system | システムプロンプトのような追加のコンテキスト |
inferenceConfig | temperature や maxTokens のような推論パラメータ |
toolConfig | ツールの設定 |
guardrailConfig | ガードレールの設定 |
additionalModelRequestFields | inferenceConfig 以外のモデルの仕様によるパラメータ |
promptVariables | Prompt management で管理しているプレースホルダーに対する具体値の設定 |
additionalModelResponseFieldPaths | 標準レスポンスに含まれない、モデル固有のフィールドを指定 |
requestMetadata | 呼び出しログのフィルタリング |
performanceConfig | リクエストのモデルパフォーマンスの設定 |
レスポンス
レスポンスについては以下を参照ください。
使い分け
However, we recommend using the Converse API as it provides consistent API, that works with all Amazon Bedrock models that support messages.
上記の記載があるように、モデル間で一貫したインターフェースを提供する Converse API の使用が推奨されています。message では role パラメータの値(assistant
と user
)で会話の発信者を統一させる仕様も良い点であると感じます。
一方で、シングルショットのテキスト生成、エンベディング、画像生成、動画生成といった、非対話型のモデルは Converse API ではサポートされていない ため、それらのモデルを使用したい場合は InvokeModel を利用する必要があります。
プログラムからの使用例
バージニア北部(us-east-1)リージョンにおいてモデルに対するアクセスが許可されていることを前提に進めていきます。
InvokeModel API
プログラム例
import jsonimport boto3bedrock_runtime_client = boto3.client("bedrock-runtime",region_name="us-east-1",)model_id = "anthropic.claude-3-sonnet-20240229-v1:0"user_prompt = "How do you write a program to output Hello World in Python?"payload = {"anthropic_version": "bedrock-2023-05-31","max_tokens": 512,"messages": [{"role": "user","content": user_prompt,},],}response = bedrock_runtime_client.invoke_model(modelId=model_id,body=json.dumps(payload),)response_body = response["body"].read().decode("utf-8")response_json = json.loads(response_body)assistant_prompt = response_json["content"][0]["text"]print(assistant_prompt)
出力結果
{"id": "msg_bdrk_0124pRQhxNBKUNyhEYnk5r6s","type": "message","role": "assistant","model": "claude-3-sonnet-20240229","content": [{"type": "text","text": 'To write a program that outputs "Hello World" in Python, you can use the `print()` function. Here\'s the code:\n\n```python\nprint("Hello World")\n```\n\nWhen you run this code, it will display the output `Hello World` in the console or terminal.\n\nAlternatively, you can store the string `"Hello World"` in a variable and then print the variable:\n\n```python\nmessage = "Hello World"\nprint(message)\n```\n\nThis code will also output `Hello World` in the console or terminal.\n\nIn Python, the `print()` function is used to display output to the console or terminal. You can pass strings, variables, or expressions as arguments to the `print()` function, and it will print their values.',}],"stop_reason": "end_turn","stop_sequence": None,"usage": {"input_tokens": 20, "output_tokens": 168},}
Converse API
プログラム例
import boto3bedrock_runtime_client = boto3.client("bedrock-runtime",region_name="us-east-1",)model_id = "anthropic.claude-3-sonnet-20240229-v1:0"user_prompt = "How do you write a program to output Hello World in Python?"messages = [{"role": "user","content": [{"text": user_prompt,}],},]response = bedrock_runtime_client.converse(modelId=model_id,messages=messages,)print(response)
出力結果
{"ResponseMetadata": {"RequestId": "80fa8d6e-c10f-4366-8735-10f7a52c2984","HTTPStatusCode": 200,"HTTPHeaders": {"date": "Tue, 08 Apr 2025 04:01:15 GMT","content-type": "application/json","content-length": "1035","connection": "keep-alive","x-amzn-requestid": "80fa8d6e-c10f-4366-8735-10f7a52c2984",},"RetryAttempts": 0,},"output": {"message": {"role": "assistant","content": [{"text": 'To output "Hello World" in Python, you can use the `print()` function. Here\'s how you can write the program:\n\n```python\nprint("Hello World")\n```\n\nThis single line of code will output the string "Hello World" to the console or terminal when you run the program.\n\nAlternatively, you can also write it like this:\n\n```python\nmessage = "Hello World"\nprint(message)\n```\n\nIn this case, we first store the string "Hello World" in a variable called `message`, and then we print the value of that variable using the `print()` function.\n\nBoth of these approaches will yield the same output:\n\n```\nHello World\n```\n\nPython\'s `print()` function is a built-in function that allows you to display output to the console or terminal. It can print strings, numbers, variables, and even more complex data types like lists and dictionaries.'}],}},"stopReason": "end_turn","usage": {"inputTokens": 20, "outputTokens": 199, "totalTokens": 219},"metrics": {"latencyMs": 6004},}
まとめ
Amazon Bedrock の InvokeModel API と Converse API の違いと各 API の使い方について解説しました。
InvokeModel はあらゆるモデルに対する低レベルな推論 API で、モデル固有の入力・出力形式に応じた実装が必要ですが、テキスト生成以外の用途も含め広く利用できます。Converse は対話型 LLM 向けに設計された高レベル API で、統一的なメッセージインタフェースによる複数回やり取りをするチャットとしての利用やツール連携を容易にし、モデル間の差異を吸収する役割があります。
対話型のアプリケーション開発では積極的に Converse API の利用を検討し、テキスト生成以外のモデルを利用したい場合など、ケースに応じて InvokeModel API と使い分けていこうと思います。