翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
クライアント側のツールの使用
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()
モデルがリクエストするツールの選択
のオプションtoolChoiceフィールドは、モデルがツールをリクエストする必要があるかどうかtoolConfigを制御します。使用できる設定は、モデルプロバイダーやモデルファミリーではなく、呼び出す個々のモデルによって異なります。
auto(デフォルト) は、ツールの使用をサポートするすべてのモデルでサポートされています。モデルは、代わりにツールをリクエストするか、テキストを生成するかを決定します。anyモデルが少なくとも 1 つのツールをリクエストする必要がある と、モデルが名前を付けた 1 つのツールをリクエストtoolする必要がある は、一部のモデルでサポートされていますが、他のモデルではサポートされません。モデルは 2 つのうち 1 つをサポートでき、もう 1 つはサポートできません。
モデルが送信する設定をサポートしていない場合、リクエストは にフォールバックするのValidationExceptionではなく で失敗しますauto。メッセージは削除するフィールドを識別します。たとえば、This model doesn't support the toolConfig.toolChoice.tool field. Remove toolConfig.toolChoice.tool and try again.一部のモデルは、モデルプロバイダーが報告するエラーを返します。たとえば、 anyまたは をサポートしていない Anthropic Claude The model returned the following errors: tool_choice: type "tool" and "any" are not supported for this model. モデルの場合はtool、「強制ツールの使用」を参照してください。
ツールの使用をまったくサポートしていないモデルは、 を含むすべてのtoolChoice設定This model doesn't support tool use.で で失敗しますauto。
レスポンスストリーミングでのツールの使用
ツールの使用とレスポンスストリーミングのサポートは、独立した機能です。ツールをサポートするほとんどのモデルは のtoolConfigフィールドも受け入れますがConverseStream、次のモデルは非ストリーミングConverseオペレーションでのみツールを受け入れ、 ConverseStreamを使用して で拒否しますThis model doesn't support tool use in streaming mode.。
Llama 3.1 8B Instruct、Llama 3.1 70B Instruct、および Llama 3.3 70B Instruct
Llama 4 Scout 17B Instruct および Llama 4 Maverick 17B Instruct
Mistral Large 1 (24.02)、Mistral Large 2 (24.07)、および Pixtral Large (25.02)
Writer Palmyra X4 および Writer Palmyra X5
レスポンスストリーミング自体は、これらのすべてのモデルで機能します。ストリーミングとツールの使用の組み合わせのみがサポートされていません。そのうちの 1 つでツールを使用する必要がある場合は、Converse代わりに を呼び出します。
ツール使用 ID について
レスポンスの各ツールリクエストには、そのリクエストを識別する が格納toolUseIdされます。モデルが結果をリクエストに一致できるように、同じ値を対応するtoolResultブロックにエコーバックします。Amazon Bedrock がこの値を生成する方法は、ツールの種類とモデルによって異なります。
で定義したツールの場合
toolConfig、Amazon Bedrock は 値を生成します。これは、 というプレフィックスが付いたランダムに生成された識別子でありtooluse_、モデルの出力によって生成または派生されません。Amazon Bedrock サーバー側のツールと MCP ツールの場合、Amazon Bedrock はランダムに生成するのではなく、ツールリクエストから決定的に値を計算します。値は
tooluse_プレフィックスを保持します。一部のモデルでは、モデルプロバイダーが返す識別子は変更されずに渡されます。このような値は、プロバイダー独自の形式を使用し、
tooluse_プレフィックスは付いておらず、ツールの名前など、リクエストから派生したテキストを含めることができます。
実行時に 2 つを区別するには、 プレフィックスを確認します。Amazon Bedrock が生成するすべての識別子は、 で始まりtooluse_、その後に 22 文字が続きます。で始まらない識別子は、モデルプロバイダーからtooluse_取得されました。この動作は同じファミリーのモデル間で異なる可能性があるため、呼び出す特定のモデルをテストします。
重要
保護されたヘルス情報のコンプライアンス義務を満たすために、アプリケーションがモデル生成コンテンツを編集する場合、 toolUseIdがすべてのモデルに対して Amazon Bedrock によって生成されると想定しないでください。呼び出す特定のモデルの動作を確認しない限り、値をモデル派生として扱います。
Invoke APIsクライアント側のツールの使用
ベース推論オペレーション (InvokeModel または InvokeModelWithResponseStream) でツールを使用できます。リクエスト本文で渡す推論パラメータを見つけるには、使用するモデルの推論パラメータを参照してください。