运行 Amazon Bedrock 流代码示例 - Amazon Bedrock

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

运行 Amazon Bedrock 流代码示例

以下代码示例假定您已满足以下先决条件:

  1. 设置一个拥有 Amazon Bedrock 操作权限的角色。如果您尚未设置,请参阅 开始使用 Amazon Bedrock

  2. 设置您的凭证以使用 AWS API。如果您尚未设置,请参阅 开始使用 API

  3. 创建一个服务角色,以代表您执行与流相关的操作。如果您尚未设置,请参阅 在 Amazon Bedrock 中为 Amazon Bedrock 流创建服务角色

要创建流,请使用 Amazon Bedrock 代理构建时端点发送 CreateFlow 请求。有关示例代码,请参阅运行 Amazon Bedrock 流代码示例。

以下字段是必填字段:

字段 Basic description
名称 工作流的名称。
executionRoleArn 具有创建和管理工作流权限的服务角色的 ARN。

以下字段是可选字段:

字段 应用场景
定义 包括构成工作流的 nodesconnections
description 用于描述工作流。
tags 将标签与流相关联。有关更多信息,请参阅标记 Amazon Bedrock 资源
customerEncryptionKeyArn 使用 KMS 密钥加密资源。有关更多信息,请参阅Amazon Bedrock 流资源加密
clientToken 用于确保 API 请求仅完成一次。有关更多信息,请参阅确保幂等性

虽然 definition 字段是可选字段,但必须填写该字段才能使工作流正常运行。您可以选择先创建没有定义的工作流,然后再更新工作流。

对于 nodes 列表中的每个节点,您可以在 config 字段中指定节点的类型,并在 type 字段中提供该节点的相应配置。有关不同类型节点的 API 结构的详细信息,请参阅流的节点类型

要试用 Amazon Bedrock 流的一些代码示例,请选择与您的首选方法对应的选项卡,然后按照以下步骤操作:

Python
  1. 使用具有以下节点的 Amazon Bedrock 代理构建时端点发送 CreateFlow 请求,创建流:

    • 一个输入节点。

    • 一个提示节点,具有一个内联定义的提示,该提示使用两个变量(genrenumber)创建了一个音乐播放列表。

    • 一个输出节点,用于返回模型完成情况。

    运行以下代码片段来加载适用于 Python (Boto3) 的 AWS SDK,创建 Amazon Bedrock 代理客户端,然后使用节点创建流(将 executionRoleArn 字段替换为您为流创建的服务角色的 ARN):

    # Import Python SDK and create client import boto3 client = boto3.client(service_name='bedrock-agent') # Replace with the service role that you created. For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html FLOWS_SERVICE_ROLE = "arn:aws:iam::123456789012:role/MyFlowsRole" # Define each node # The input node validates that the content of the InvokeFlow request is a JSON object. input_node = { "type": "Input", "name": "FlowInput", "outputs": [ { "name": "document", "type": "Object" } ] } # This prompt node defines an inline prompt that creates a music playlist using two variables. # 1. {{genre}} - The genre of music to create a playlist for # 2. {{number}} - The number of songs to include in the playlist # It validates that the input is a JSON object that minimally contains the fields "genre" and "number", which it will map to the prompt variables. # The output must be named "modelCompletion" and be of the type "String". prompt_node = { "type": "Prompt", "name": "MakePlaylist", "configuration": { "prompt": { "sourceConfiguration": { "inline": { "modelId": "amazon.nova-lite-v1:0", "templateType": "TEXT", "inferenceConfiguration": { "text": { "temperature": 0.8 } }, "templateConfiguration": { "text": { "text": "Make me a {{genre}} playlist consisting of the following number of songs: {{number}}." } } } } } }, "inputs": [ { "name": "genre", "type": "String", "expression": "$.data.genre" }, { "name": "number", "type": "Number", "expression": "$.data.number" } ], "outputs": [ { "name": "modelCompletion", "type": "String" } ] } # The output node validates that the output from the last node is a string and returns it as is. The name must be "document". output_node = { "type": "Output", "name": "FlowOutput", "inputs": [ { "name": "document", "type": "String", "expression": "$.data" } ] } # Create connections between the nodes connections = [] # First, create connections between the output of the flow input node and each input of the prompt node for input in prompt_node["inputs"]: connections.append( { "name": "_".join([input_node["name"], prompt_node["name"], input["name"]]), "source": input_node["name"], "target": prompt_node["name"], "type": "Data", "configuration": { "data": { "sourceOutput": input_node["outputs"][0]["name"], "targetInput": input["name"] } } } ) # Then, create a connection between the output of the prompt node and the input of the flow output node connections.append( { "name": "_".join([prompt_node["name"], output_node["name"]]), "source": prompt_node["name"], "target": output_node["name"], "type": "Data", "configuration": { "data": { "sourceOutput": prompt_node["outputs"][0]["name"], "targetInput": output_node["inputs"][0]["name"] } } } ) # Create the flow from the nodes and connections response = client.create_flow( name="FlowCreatePlaylist", description="A flow that creates a playlist given a genre and number of songs to include in the playlist.", executionRoleArn=FLOWS_SERVICE_ROLE, definition={ "nodes": [input_node, prompt_node, output_node], "connections": connections } ) flow_id = response.get("id")
  2. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 ListFlows 请求,列出账户中的流(包括您刚刚创建的流):

    client.list_flows()
  3. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 GetFlow 请求,获取有关您刚刚创建的流的信息:

    client.get_flow(flowIdentifier=flow_id)
  4. 准备好流,以便应用工作草稿中的最新更改,并准备好为其创建版本。运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 PrepareFlow 请求:

    client.prepare_flow(flowIdentifier=flow_id)
  5. 为流的工作草稿创建版本,以创建流的静态快照,然后通过以下操作检索有关该快照的信息:

    1. 运行以下代码段,使用 Amazon Bedrock 代理构建时端点发送 CreateFlowVersion 请求以创建版本:

      response = client.create_flow_version(flowIdentifier=flow_id) flow_version = response.get("version")
    2. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 ListFlowVersions 请求,列出流的所有版本:

      client.list_flow_versions(flowIdentifier=flow_id)
    3. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 GetFlowVersion 请求,获取有关版本的信息:

      client.get_flow_version(flowIdentifier=flow_id, flowVersion=flow_version)
  6. 创建一个别名并将其指向您为流创建的版本,然后通过以下操作检索有关该别名的信息:

    1. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 CreateFlowAlias 请求,创建一个别名并将其指向您刚刚创建的版本:

      response = client.create_flow_alias( flowIdentifier=flow_id, name="latest", description="Alias pointing to the latest version of the flow.", routingConfiguration=[ { "flowVersion": flow_version } ] ) flow_alias_id = response.get("id")
    2. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 ListFlowAliass 请求,列出流的所有别名:

      client.list_flow_aliases(flowIdentifier=flow_id)
    3. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 GetFlowAlias 请求,获取有关您刚刚创建的别名的信息:

      client.get_flow_alias(flowIdentifier=flow_id, aliasIdentifier=flow_alias_id)
  7. 运行以下代码片段,创建 Amazon Bedrock 代理运行时客户端并调用工作流。请求会在流的提示中填写变量,并返回模型的响应,以便使用 Amazon Bedrock 代理运行时端点发送 InvokeFlow 请求:

    client_runtime = boto3.client('bedrock-agent-runtime') response = client_runtime.invoke_flow( flowIdentifier=flow_id, flowAliasIdentifier=flow_alias_id, inputs=[ { "content": { "document": { "genre": "pop", "number": 3 } }, "nodeName": "FlowInput", "nodeOutputName": "document" } ] ) result = {} for event in response.get("responseStream"): result.update(event) if result['flowCompletionEvent']['completionReason'] == 'SUCCESS': print("Flow invocation was successful! The output of the flow is as follows:\n") print(result['flowOutputEvent']['content']['document']) else: print("The flow invocation completed because of the following reason:", result['flowCompletionEvent']['completionReason'])

    响应应返回包含三首歌曲的流行音乐播放列表。

  8. 通过以下操作删除您创建的别名、版本和流:

    1. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 DeleteFlowAlias 请求,删除别名:

      client.delete_flow_alias(flowIdentifier=flow_id, aliasIdentifier=flow_alias_id)
    2. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 DeleteFlowVersion 请求,删除版本:

      client.delete_flow_version(flowIdentifier=flow_id, flowVersion=flow_version)
    3. 运行以下代码片段,使用 Amazon Bedrock 代理构建时端点发送 DeleteFlow 请求,删除流:

      client.delete_flow(flowIdentifier=flow_id)