翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
ツールを使用して Amazon Bedrock のモデルレスポンスを完成させる
Amazon Bedrock API を使用すると、モデルに送信したメッセージに対するレスポンスを生成するのに役立つツールへのアクセスをモデルに与えることができます。例えば、ラジオステーションで最も人気のある曲を見つけることができるチャットアプリケーションがあるとします。最も人気のある曲のリクエストに答えるには、モデルは、曲の情報をクエリして返すことができるツールが必要です。
注記
ツールの使用で構造化出力を使用できるようになりました。詳細については、「モデルから検証済みの JSON 結果を取得する」を参照してください。
Amazon Bedrock では、モデルはツールを直接呼び出しません。モデルにメッセージを送信するときは、モデルがレスポンスを生成するのに役立つ可能性のある 1 つ以上のツールの定義も一緒に与えます。この例では、特定のラジオステーションの最も人気のある曲を返すツールの定義を与えます。モデルがメッセージに対するレスポンスを生成するツールが必要であると判断した場合、モデルは、モデルの呼び出しに使用される API に応じて、クライアント側の呼び出しを実行するか、サーバー側のツール呼び出しを使用してツールを呼び出すように Bedrock に依頼できます。これら 2 つのオプションについて詳しく説明します。
クライアント側のツール呼び出し
Responses API、Chat Completions API、Converse API、または InvokeModel API を使用してリクエストを送信する場合、モデルはクライアント側のツール呼び出しを使用します。つまり、コードでは、モデルに代わってツールを呼び出します。このシナリオでは、ツールの実装が API であると仮定します。ツールは、データベース、Lambda 関数、またはその他のソフトウェアのどれでも構いません。ツールの実装方法を決定します。次に、ツールの結果をメッセージで入力して、モデルとの会話を続行します。最後に、モデルは、モデルに送信したツールの結果を含む元のメッセージのレスポンスを生成します。
ツールの使用に使用するツールを定義しましょう。次の Python の例は、架空のラジオステーションで最も人気のある曲を返すツールの使用方法を示しています。
def get_most_popular_song(station_name: str) -> str: stations = { "Radio Free Mars": "Starman – David Bowie", "Neo Tokyo FM": "Plastic Love – Mariya Takeuchi", "Cloud Nine Radio": "Blinding Lights – The Weeknd", } return stations.get(station_name, "Unknown Station – No chart data available")
クライアント側のツールに Responses API を使用する
OpenAI が提供する関数呼び出し
from openai import OpenAI import json client = OpenAI() response = client.responses.create( model="oss-gpt-120b", input="What is the most popular song on Radio Free Mars?", tools=[ { "type": "function", "name": "get_most_popular_song", "description": "Returns the most popular song on a radio station", "parameters": { "type": "object", "properties": { "station_name": { "type": "string", "description": "Name of the radio station" } }, "required": ["station_name"] } } ] ) if response.output and response.output[0].content: tool_call = response.output[0].content[0] args = json.loads(tool_call["arguments"]) result = get_most_popular_song(args["station_name"]) final_response = client.responses.create( model="oss-gpt-120b", input=[ { "role": "tool", "tool_call_id": tool_call["id"], "content": result } ] ) print(final_response.output_text)
クライアント側のツールに Chat Completions API を使用する
Chat Completions API を使用することもできます。チャット完了を使用するための Python コードは次のとおりです。
from openai import OpenAI import json client = OpenAI() completion = client.chat.completions.create( model="oss-gpt-120b", messages=[{"role": "user", "content": "What is the most popular song on Neo Tokyo FM?"}], tools=[{ "type": "function", "function": { "name": "get_most_popular_song", "description": "Returns the most popular song on a radio station", "parameters": { "type": "object", "properties": { "station_name": {"type": "string", "description": "Name of the radio station"} }, "required": ["station_name"] } } }] ) message = completion.choices[0].message if message.tool_calls: tool_call = message.tool_calls[0] args = json.loads(tool_call.function.arguments) result = get_most_popular_song(args["station_name"]) followup = client.chat.completions.create( model="oss-gpt-120b", messages=[ {"role": "user", "content": "What is the most popular song on Neo Tokyo FM?"}, message, {"role": "tool", "tool_call_id": tool_call.id, "content": result} ] ) print(followup.choices[0].message.content)
レスポンス API での関数呼び出しとチャット完了 API の使用の詳細については、OpenAI での関数呼び出し
Converse API をクライアント側のツールに使用する
Converse API を使用すると、会話でモデルにツールを使用させることができます。次の Python の例は、架空のラジオステーションで最も人気のある曲を返すツールの使用方法を示しています。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Shows how to use tools with the Converse API and the Cohere Command R model.""" import logging import json import boto3 from botocore.exceptions import ClientError class StationNotFoundError(Exception): """Raised when a radio station isn't found.""" pass logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def get_top_song(call_sign): """Returns the most popular song for the requested station. Args: call_sign (str): The call sign for the station for which you want the most popular song. Returns: response (json): The most popular song and artist. """ song = "" artist = "" if call_sign == 'WZPZ': song = "Elemental Hotel" artist = "8 Storey Hike" else: raise StationNotFoundError(f"Station {call_sign} not found.") return song, artist def generate_text(bedrock_client, model_id, tool_config, input_text): """Generates text using the supplied Amazon Bedrock model. If necessary, the function handles tool use requests and sends the result to the model. Args: bedrock_client: The Boto3 Bedrock runtime client. model_id (str): The Amazon Bedrock model ID. tool_config (dict): The tool configuration. input_text (str): The input text. Returns: Nothing. """ logger.info("Generating text with model %s", model_id) # Create the initial message from the user input. messages = [{"role": "user", "content": [{"text": input_text}]}] response = bedrock_client.converse(modelId=model_id, messages=messages, toolConfig=tool_config) output_message = response['output']['message'] messages.append(output_message) stop_reason = response['stopReason'] if stop_reason == 'tool_use': # Tool use requested. Call the tool and send the result to the model. tool_requests = response['output']['message']['content'] for tool_request in tool_requests: if 'toolUse' in tool_request: tool = tool_request['toolUse'] logger.info("Requesting tool %s. Request: %s", tool['name'], tool['toolUseId']) if tool['name'] == 'top_song': tool_result = {} try: song, artist = get_top_song(tool['input']['sign']) tool_result = {"toolUseId": tool['toolUseId'], "content": [{"json": {"song": song, "artist": artist}}]} except StationNotFoundError as err: tool_result = {"toolUseId": tool['toolUseId'], "content": [{"text": err.args[0]}], "status": 'error'} tool_result_message = {"role": "user", "content": [{"toolResult": tool_result}]} messages.append(tool_result_message) # Send the tool result to the model. response = bedrock_client.converse(modelId=model_id, messages=messages, toolConfig=tool_config) output_message = response['output']['message'] # print the final response from the model. for content in output_message['content']: print(json.dumps(content, indent=4)) def main(): """Entrypoint for tool use example.""" logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = "cohere.command-r-v1:0" input_text = "What is the most popular song on WZPZ?" tool_config = { "tools": [ { "toolSpec": { "name": "top_song", "description": "Get the most popular song played on a radio station.", "inputSchema": { "json": { "type": "object", "properties": { "sign": { "type": "string", "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ, and WKRP." } }, "required": ["sign"] } } } } ] } bedrock_client = boto3.client(service_name='bedrock-runtime') try: print(f"Question: {input_text}") generate_text(bedrock_client, model_id, tool_config, input_text) except ClientError as err: message = err.response['Error']['Message'] logger.error("A client error occurred: %s", message) print(f"A client error occured: {message}") else: print(f"Finished generating text with model {model_id}.") if __name__ == "__main__": main()
Invoke APIsクライアント側のツールの使用
ベース推論オペレーション (InvokeModel または InvokeModelWithResponseStream) でツールを使用できます。リクエスト本文で渡す推論パラメータを見つけるには、使用するモデルの推論パラメータを参照してください。
サーバー側のツール呼び出し
Responses API を使用してモデルを呼び出す場合、前に説明したクライアント側のツール呼び出しに加えて、サーバー側のツール呼び出しを使用できます。サーバー側のツール呼び出しは、ツール (APIs、関数、ワークフロー) がクライアントではなく信頼できるバックエンド環境で実行されるメカニズムです。これにより、アプリケーションのセキュリティ、信頼性、ガバナンス体制が向上します。Amazon Bedrock がツールの使用を実装する Lambda 関数を実行する前に、Lambda 関数が呼び出すアプリケーションのポリシーと同じ IAM ポリシーを持つようにします。Amazon Bedrock がツールの実行を推進しているため、クライアントはツール機能を追加するのではなく、ビジネスロジックの実装に集中できます。Amazon Bedrock は、ISO、SOC、HIPAA 対応など、最高のガバナンス標準もサポートしています。お客様は、独自のカスタム Lambda 関数を送信してツールを実行するか、メモやタスクなどの既存の事前定義されたツールを使用できます。Responses API を使用するサーバー側のツールは、OpenAI の GPT OSS 20B/120B モデルから利用可能になり、他のモデルも間もなくサポートされる予定です。Models API を使用して、 Responses API で使用できるモデルを検出できます。Responses API の詳細については、OpenAI APIs」を参照してください。
Amazon Bedrock で使用できるツールには、Lambda を使用するカスタムツールと Bedrock でサポートされている定義済みツールの 2 種類があります。このセクションでは、 Responses API を使用してカスタム Lambda ツールを作成する方法を確認します。両方について詳しく説明します。
Responses API で Lambda を使用するカスタムツール
Lambda 関数を Bedrock のカスタムツールとして使用することで、カスタム AWS Lambda 関数をツールとして統合することで、エージェントの機能を拡張できます。これにより、AI アシスタントやその他のアプリケーションが Model Context Protocol (MCP) を通じて呼び出すことができるサーバーレスでスケーラブルなツールを作成できます。この機能の利点は次のとおりです。
機能拡張: カスタムビジネスロジック、API 統合、またはデータ処理機能を追加します。
ツールを安全に実行する: Lambda を使用すると、ツールは完全な VPC アクセスを許可することなく、VPC 内のリソースにアクセスできます。
サーバーレスアーキテクチャ: インフラストラクチャ管理なし、Lambda は自動的にスケーリングを処理します。
コスト効率: 実行時間に対してのみ支払い、アイドル状態のリソースに対しては支払いません。
簡単な統合: Lambda 関数は、組み込みツールと一緒にシームレスに表示されます。
Amazon Bedrock のモデルがツールを使用してメッセージのレスポンスを完了できるようにするには、メッセージと 1 つ以上のツールの定義をモデルに送信します。アプリケーションのプロンプトに基づいて、いずれかのツールがレスポンスの生成に役立つとモデルが判断した場合、Bedrock はツールを使用し、ツールの結果をモデルに送り返すリクエストを返します。モデルはその結果を使用して元のメッセージに対するレスポンスを生成します。
次の手順は、 Responses API でツールを使用する方法を示しています。
仕組み
Lambda 関数: MCP プロトコルを実装する Lambda 関数を作成する
ツール検出: Bedrock は Lambda 関数を呼び出して使用可能なツールを検出します。
ツール登録: ツールが Bedrock に登録されている
ツールの実行: エージェントがツールをリクエストすると、Bedrock は Lambda 関数を呼び出します。
レスポンス処理: 結果は標準インターフェイスを介してエージェントに返されます。
ステップ 1: 最も人気のある曲を取得する Lambda 関数を定義する
MCP プロトコルを実装する Lambda 関数を作成します。Python の簡単な例を次に示します。
import json def lambda_handler(event, context): # Parse JSON-RPC request method = event.get('method') params = event.get('params', {}) request_id = event.get('id') if method == 'tools/list': return { "jsonrpc": "2.0", "id": request_id, "result": { "tools": [ { "name": "my_custom_tool", "description": "My custom business logic tool", "inputSchema": { "type": "object", "properties": { "input": { "type": "string", "description": "Input text to process" } }, "required": ["input"] } } ] } } elif method == 'tools/call': tool_name = params.get('name') arguments = params.get('arguments', {}) if tool_name == 'my_custom_tool': # Your custom logic here result = f"Processed: {arguments.get('input', '')}" return { "jsonrpc": "2.0", "id": request_id, "result": { "content": [ { "type": "text", "text": result } ] } } # Error response for unsupported methods return { "jsonrpc": "2.0", "id": request_id, "error": { "code": -32601, "message": "Method not found" } }
ステップ 2: Lambda 関数をデプロイする
次に、IAM ロールを使用してこの Lambda 関数をデプロイし、ARN を取得します。Lambda 関数のデプロイの詳細については、こちらを参照してください。
# Example using AWS CLI aws lambda create-function \ --function-name my-custom-tool \ --runtime python3.14 \ --role arn:aws:iam::YOUR-ACCOUNT:role/lambda-execution-role \ --handler lambda_function.lambda_handler \ --zip-file fileb://function.zip
ARN が であるとします。 arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool
ステップ 3: 推論リクエストでメッセージとツールの定義を定義する
メッセージとツール定義を送信するには、Responsions API オペレーションを使用します。Amazon Bedrock は、 Responses API のコネクタとリモート MCP サーバー機能connector_idフィールドで、前のステップで作成した Lambda ARN を渡すことができます。Bedrock はモデルを呼び出すアプリケーションに使用されるのと同じ IAM ロールとポリシーを使用するため、認可認証情報を提供する必要はありません。以下は、ラジオステーションで最も人気のある曲を取得するツールのスキーマの例です。
from openai import OpenAI client = OpenAI() resp = client.responses.create( model="oss-gpt-120b", tools=[ { "type": "mcp", "server_label": "xamzn_arn", "connector_id": "arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool", "require_approval": "never", }, ], input="My custom prompt.", ) print(resp.output_text)
ステップ 4: Bedrock がツールを呼び出し、レスポンスをモデルに返す
コネクタツールを使用する機能は、 Responses API
tools パラメータで Lambda 関数を指定すると、API はサーバーからツールのリストを取得しようとします。ツールのリストの取得に成功すると、モデルレスポンスmcp_list_tools出力に新しい出力項目が表示されます。このオブジェクトの toolsプロパティには、正常にインポートされたツールが表示されます。モデルがこれらのツール定義にアクセスできるようになると、モデルのコンテキストの内容に応じて、それらを呼び出すことを選択できます。モデルが Lambda ツールを呼び出すことを決定すると、API は Lambda 関数にツールを呼び出し、その出力をモデルのコンテキストに配置するようにリクエストします。OpenAI ドキュメント
{ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": "Tool execution failed", "data": "Additional error details" } }
Responses API で AWS が提供するツールを使用する
Bedrock で使用できる AWS が提供するツールには、メモを取る機能 (メモツール) とタスク管理 (タスクツール) の 2 つがあります。両方について詳しく説明します。
メモツールの概要
このnotesツールを使用すると、同じ会話セッション内でキーと値のペアを保存および取得できます。これにより、複数のインタラクションにわたってコンテキストを維持するためのシンプルなメモリメカニズムが提供されます。キーは大文字と小文字を区別する文字列であり、キーの長さや命名規則に制限はありません。システムは同じキーの以前の値を上書きします。値は文字列 (JSON、URLsなど) として保存され、ツールレベルで適用されるサイズ制限はありません。値は会話セッション全体で保持されます。メモリは現在の会話のみを対象としています。
パラメータ
| パラメータ | タイプ | 必須 | 説明 |
|---|---|---|---|
operation |
文字列 | はい | 実行するオペレーション: "store"または "recall" |
key |
string | はい | メモリ項目のキー識別子 |
value |
string | 条件付き | 保存する値 ( "store" オペレーションにのみ必要) |
有効なオペレーション
store: キーと値のペアをメモリに保存するrecall: キーで値を取得する
自然言語 (「好きな色が青であることを覚えておいてください」、「好きな色について何を伝えましたか?」、「朝の会議を好むという事実を保存する」、「会議の設定について言ったことを思い出す」など) を使用するか、プロンプトで直接ツールコールを使用できます (「メモツールを使用して E メールを john@example.com として保存する」、「E メールアドレスのメモを確認する」など)。
タスクツールの概要
このtasksツールは、会話セッション内のタスクを管理するための Last-In-First-Out (LIFO) スタックを提供します。これにより、タスクをスタックにプッシュして逆の順序でポップオフできるため、ネストされたワークフロー、一時的なリマインダー、または階層タスクの管理に最適です。タスクは会話セッション全体で保持されます。スタックの状態は複数のインタラクションにわたって維持されます。メモリは現在の会話のみを対象としています。
| パラメータ | タイプ | 必須 | 説明 |
|---|---|---|---|
operation |
文字列 | はい | 実行するオペレーション: "push"または "pop" |
description |
string | 条件付き | タスク項目の説明 ( "push" オペレーションにのみ必要) |
summary |
string | いいえ | タスク項目に関するオプションの概要 ( "push" オペレーションのみ) |
タスクツールは、自然言語 (「予算を確認するタスクを追加する」、「クライアントを呼び出すリマインダーを押す」、「次に何をする必要があるか」、「最新のタスクを押す」、「スタックから最新のタスクを取得する」など) を使用して呼び出すか、プロンプトでツールを直接呼び出すことができます (「タスクツールを使用して「プレゼンテーションを終了する」、「スタックからタスクを押す」、「会議をタスクリストに追加する」)。
AgentCore Gateway とのサーバー側のツール使用統合
Amazon Bedrock は、統合タイプを呼び出すサーバー側のツールとして AgentCore Gateway をサポートするようになりました。この機能を使用すると、モデルを AgentCore Gateway エンドポイントに直接接続できるため、ゲートウェイインフラストラクチャを介して管理されるツールにシームレスにアクセスできます。
AgentCore Gateway 統合は、Lambda 関数統合と同じパターンに従いますが、主な違いは 1 つです。
Lambda 統合:
Lambda 関数 ARNs
AWS Lambda 関数を直接呼び出す
AgentCore Gateway の統合:
AgentCore Gateway ARNs
AgentCore Gateway インフラストラクチャを介してツール呼び出しをルーティングします
一元化されたツール管理と検出を提供します
設定
リクエスト構造
AgentCore Gateway をツールソースとして設定する場合は、Responsions API リクエストのtools配列で次の構造を使用します。
{ "type":"mcp", "server_label":"agentcore_tools", "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp", "server_description":"AgentCore Gateway providing custom tools", "require_approval":"never" }
パラメータ
| パラメータ | タイプ | 必須 | 説明 |
|---|---|---|---|
type |
文字列 | はい | mcp に設定する必要があります。 |
server_label |
string | はい | リクエスト内のこのツールコネクタの一意の識別子 |
connector_id |
string | はい | AgentCore Gateway の ARN |
server_description |
string | いいえ | このゲートウェイが提供するツールの人間が読める説明 |
require_approval |
string | はい | フィールドは である必要があります "never" |
完全なリクエストの例
{ "model":"openai.gpt-oss-120b", "stream":true, "background":false, "store":false, "tools": [ { "type":"mcp", "server_label":"agentcore_tools", "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp", "server_description":"AgentCore Gateway providing custom tools", "require_approval":"never" } ], "input": [ { "type":"message", "role":"user", "content": [ { "type":"input_text", "text":"What is the weather in Seattle?" } ] } ] }
前提条件
AgentCore Gateway 統合を使用する前に、以下を確認してください。
設定されたターゲット (Lambda 関数、API Gateway ステージ、OpenAPI スキーマ、または MCP サーバー) を持つ AgentCore Gateway を作成しました
Bedrock サービスロールがゲートウェイを呼び出すことを許可する IAM アクセス許可を設定しました。Bedrock は IAM 認証を使用するゲートウェイのみをサポートすることに注意してください。
正しい形式のゲートウェイ ARN
AgentCore Gateway 統合の利点
一元化されたツール管理: 単一のゲートウェイエンドポイントを使用してすべてのツールを管理する
ツール検出: エージェントはゲートウェイを介して利用可能なツールを動的に検出できます
セキュリティ: IAM およびゲートウェイポリシーによる組み込みの認証と認可
オブザーバビリティ: ツール呼び出しの包括的なモニタリングとログ記録
柔軟性: 複数のターゲットタイプ (Lambda、API Gateway、OpenAPI、MCP サーバー) のサポート
IAM 許可
Bedrock 実行ロールには、AgentCore Gateway を呼び出すためのアクセス許可が必要です。
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "bedrock-agentcore:InvokeGateway" ], "Resource": "arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp" } ] }