使用适用于 Python 的 AWS SDK(Boto3)运行 Amazon Bedrock API 请求示例
本部分将指导您在 Amazon Bedrock 中尝试使用 AWS Python 来执行一些常见操作,以测试您的权限和身份验证设置是否正确。在运行以下示例之前,应检查您是否满足了以下先决条件:
先决条件
-
您具有 AWS 账户,并且具有已设置身份验证并拥有必要的 Amazon Bedrock 权限的用户或角色。否则,请按照开始使用 API中的步骤操作。
-
您已安装了适用于 Python 的 AWS SDK(Boto3)并设置了身份验证。要安装 Boto3,请按照 Boto3 文档中 Quickstart
中的步骤操作。按照获取凭证来授予编程访问权限中的步骤,验证是否已设置凭证来使用 Boto3。
使用您已设置适当权限的用户或角色,测试是否已针对 Amazon Bedrock 设置了正确的权限。
Amazon Bedrock 文档还包括其他编程语言的代码示例。有关更多信息,请参阅 使用 AWS SDK 的 Amazon Bedrock 代码示例。
列出 Amazon Bedrock 必须提供的基础模型
以下示例使用 Amazon Bedrock 客户端运行 ListFoundationModels 操作。ListFoundationModels 会列出您所在区域的 Amazon Bedrock 中可用的基础模型(FM)。运行以下适用于 Python 的 SDK 脚本来创建 Amazon Bedrock 客户端并测试 ListFoundationModels 操作:
""" Lists the available Amazon Bedrock models in an &AWS-Region;. """ import logging import json import boto3 from botocore.exceptions import ClientError logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def list_foundation_models(bedrock_client): """ Gets a list of available Amazon Bedrock foundation models. :return: The list of available bedrock foundation models. """ try: response = bedrock_client.list_foundation_models() models = response["modelSummaries"] logger.info("Got %s foundation models.", len(models)) return models except ClientError: logger.error("Couldn't list foundation models.") raise def main(): """Entry point for the example. Change aws_region to the &AWS-Region; that you want to use.""" aws_region = "us-east-1" bedrock_client = boto3.client(service_name="bedrock", region_name=aws_region) fm_models = list_foundation_models(bedrock_client) for model in fm_models: print(f"Model: {model["modelName"]}") print(json.dumps(model, indent=2)) print("---------------------------\n") logger.info("Done.") if __name__ == "__main__": main()
如果此脚本成功,响应会返回一个包含 Amazon Bedrock 中可用基础模型的列表。
向模型提交文本提示并使用 InvokeModel 生成文本响应
以下示例使用 Amazon Bedrock 客户端运行 InvokeModel 操作。InvokeModel 允许您提交提示以生成模型响应。运行以下适用于 Python 的 SDK 脚本来创建 Amazon Bedrock 运行时客户端,并使用 操作生成文本响应:
# Use the native inference API to send a text message to Amazon Titan Text G1 - Express. import boto3 import json from botocore.exceptions import ClientError # Create an Amazon Bedrock Runtime client. brt = boto3.client("bedrock-runtime") # Set the model ID, e.g., Amazon Titan Text G1 - Express. model_id = "amazon.titan-text-express-v1" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "inputText": prompt, "textGenerationConfig": { "maxTokenCount": 512, "temperature": 0.5, "topP": 0.9 }, } # Convert the native request to JSON. request = json.dumps(native_request) try: # Invoke the model with the request. response = brt.invoke_model(modelId=model_id, body=request) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["results"][0]["outputText"] print(response_text)
如果此命令成功,响应会返回模型为响应提示而生成的文本。
向模型提交文本提示并使用 Converse 生成文本响应
以下示例使用 Amazon Bedrock 客户端运行 Converse 操作。我们建议在支持时用 Converse 来代替 InvokeModel 操作,因为前者可以统一各个 Amazon Bedrock 模型的推理请求并简化多轮对话的管理。运行以下适用于 Python 的 SDK 脚本来创建 Amazon Bedrock 运行时客户端,并使用 Converse 操作生成文本响应:
# Use the Conversation API to send a text message to Amazon Titan Text G1 - Express. import boto3 from botocore.exceptions import ClientError # Create an Amazon Bedrock Runtime client. brt = boto3.client("bedrock-runtime") # Set the model ID, e.g., Amazon Titan Text G1 - Express. model_id = "amazon.titan-text-express-v1" # Start a conversation with the user message. user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [ { "role": "user", "content": [{"text": user_message}], } ] try: # Send the message to the model, using a basic inference configuration. response = brt.converse( modelId=model_id, messages=conversation, inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, ) # Extract and print the response text. response_text = response["output"]["message"]["content"][0]["text"] print(response_text) except (ClientError, Exception) as e: print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") exit(1)
如果此命令成功,响应会返回模型为响应提示而生成的文本。