View a markdown version of this page

Client-side 工具使用 - Amazon Bedrock

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Client-side 工具使用

如果您使用响应 API、聊天完成 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")

将响应 API 用于客户端工具

你可以使用 OpenAI 提供的函数调用功能来调用这个工具。响应 API 是 OpenAI 的首选 API。以下是用于客户端工具的响应 API 的 Python 代码:

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)

将 “聊天完成” API 用于客户端工具

您也可以使用 “聊天完成” 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,它要求模型至少请求一个工具,而且tool,它要求模型请求一个您命名的工具,某些模型支持但其他模型不支持。一个模型可以支持两者中的一个,而不能支持另一个。

如果模型不支持您发送的设置,则请求将失败,ValidationException而不是回退到auto。该消息标识了要删除的字段,例如,This model doesn't support the toolConfig.toolChoice.tool field. Remove toolConfig.toolChoice.tool and try again.有些模型会返回模型提供者报告的错误,例如The model returned the following errors: tool_choice: type "tool" and "any" are not supported for this model.对于不支持的 Anthropic Claude 模型,any或者tool,请参阅强制使用工具。

完全不支持使用工具的模型在所有toolChoice设置中都会失败,包括auto。This model doesn't support tool use.

在响应流中使用工具

对工具使用的支持和对响应流的支持是独立的功能。大多数支持工具使用的模型也接受开启字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

响应流本身适用于所有这些模型。仅不支持串流和工具使用的组合。如果您需要使用其中一个工具,请Converse改为致电。

关于工具使用 ID

响应中的每个工具请求都带有标识toolUseId该请求的。你在相应的toolResult区块中回显相同的值,这样模型就可以将结果与请求相匹配。Amazon Bedrock 如何产生这个值取决于工具的种类和模型:

  • 对于您在中定义的工具toolConfig,Amazon Bedrock 会生成价值。它是一个随机生成的标识符,前缀为前缀tooluse_,它不是由模型的输出生成的,也不是从模型的输出中派生的。

  • 对于 Amazon Bedrock 服务器端工具和 MCP 工具,Amazon Bedrock 会根据工具请求确定性地计算值,而不是随机生成值。该值仍带有前tooluse_缀。

  • 对于某些模型,模型提供者返回的标识符会保持不变。这样的值使用提供者自己的格式,不带tooluse_前缀,并且可以包含从您的请求中派生的文本,例如工具的名称。

要在运行时区分两者,请检查前缀。Amazon Bedrock 生成的每个标识符都以 tooluse_ 22 个字符开头。不是以开头的标识符tooluse_来自模型提供者。在同一系列的模型之间,这种行为可能有所不同,因此请测试您调用的特定模型。

重要

如果您的应用程序编辑了模型生成的内容,例如为了履行受保护的健康信息的合规义务,请不要假设每个模型toolUseId都是由 Amazon Bedrock 生成的。除非您已确认所调用的特定模型的行为,否则将该值视为模型派生值。

使用调用 API 供客户端工具使用

可以将工具与基本推理运算(InvokeModel或 InvokeModelWithResponseStream)一起使用。要查找您在请求正文中传递的推理参数,请参阅您要使用的模型的推理参数。