

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

# 运行提示管理器示例代码
<a name="prompt-management-code-ex"></a>

要尝试一些用于 Prompt 管理的代码示例，请选择首选方法的选项卡，然后按照以下步骤操作：以下代码示例假设您已设置凭据以使用 AWS API。如果您尚未设置，请参阅 [开始使用 API](getting-started-api.md)。

------
#### [ Python ]

1. 运行以下代码片段 适用于 Python (Boto3) 的 AWS SDK，通过创建[适用于 Amazon Bedrock 的 A [CreatePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePrompt.html)gents 构建时终端节点，使用两个变量（`genre`和`number`）来加载、创建客户端，并创建用于](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)创建音乐播放列表的提示：

   ```
   # Create a prompt in Prompt management
   import boto3
   
   # Create an Amazon Bedrock Agents client
   client = boto3.client(service_name="bedrock-agent")
   
   # Create the prompt
   response = client.create_prompt(
       name="MakePlaylist",
       description="My first prompt.",
       variants=[
           { 
               "name": "Variant1",
               "modelId": "amazon.titan-text-express-v1",
               "templateType": "TEXT",
               "inferenceConfiguration": {
                   "text": {
                       "temperature": 0.8
                   }
               },
               "templateConfiguration": { 
                   "text": {
                       "text": "Make me a {{{{genre}}}} playlist consisting of the following number of songs: {{{{number}}}}."
                   }
               }
         }
       ]
   )
                           
   prompt_id = response.get("id")
   ```

1. 运行以下代码片段，查看您刚刚创建的提示（以及您账户中的任何其他提示），以创建[适用于 Amazon Bedrock 的[ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html)代理构建](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)时终端节点：

   ```
   # List prompts that you've created
   client.list_prompts()
   ```

1. 您应该在 `promptSummaries` 字段中的对象中的 `id` 字段中看到您创建的提示的 ID。运行以下代码片段以显示您通过创建 [Amazon Bedrock [GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html)代理构建时终端节点创建的](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)提示信息：

   ```
   # Get information about the prompt that you created
   client.get_prompt(promptIdentifier=prompt_id)
   ```

1. 通过运行以下代码片段创建[适用于 Amazon Bedrock 的[CreatePromptVersion](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePromptVersion.html)代理构建](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)时终端节点，创建提示符版本并获取其 ID：

   ```
   # Create a version of the prompt that you created
   response = client.create_prompt_version(promptIdentifier=prompt_id)
                           
   prompt_version = response.get("version")
   prompt_version_arn = response.get("arn")
   ```

1. 通过运行以下代码片段创建[适用于 Amazon Bedrock 的[ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html)代理构建](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)时终端节点，查看有关您刚刚创建的提示版本的信息以及有关草稿版本的信息：

   ```
   # List versions of the prompt that you just created
   client.list_prompts(promptIdentifier=prompt_id)
   ```

1. 通过运行以下代码片段创建适用于 [Amazon Bedrock 的[GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html)代理构建时终端节点，查看您刚刚创建的](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)提示版本的信息：

   ```
   # Get information about the prompt version that you created
   client.get_prompt(
       promptIdentifier=prompt_id, 
       promptVersion=prompt_version
   )
   ```

1. 按照[运行 Amazon Bedrock 流代码示例](flows-code-ex.md)中的步骤将提示添加到流来测试提示。在创建流的第一步中，请改为运行以下代码段以使用您创建的提示，而不是在流中定义内联提示（将 `promptARN` 字段中提示版本的 ARN 替换为您创建的提示版本的 ARN）：

   ```
   # Import Python SDK and create client
   import boto3
   
   client = boto3.client(service_name='bedrock-agent')
   
   FLOWS_SERVICE_ROLE = "arn:aws:iam::123456789012:role/MyPromptFlowsRole" # Flows service role that you created. For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html
   PROMPT_ARN = prompt_version_arn # ARN of the prompt that you created, retrieved programatically during creation.
   
   # 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 contains a prompt that you defined in Prompt management.
   # 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": {
                   "resource": {
                       "promptArn": ""
                   }
               }
           }
       },
       "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
   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
       }
   )
   ```

1. 通过运行以下代码片段来创建[适用于 Amazon Bedrock 的[DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html)代理构建时终端节点，删除您刚刚创建的](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)提示版本：

   ```
   # Delete the prompt version that you created
   client.delete_prompt(
       promptIdentifier=prompt_id, 
       promptVersion=prompt_version
   )
   ```

1. 完全删除您刚刚通过运行以下代码段创建[适用于 Amazon Bedrock 的[DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html)代理构建时终端节点而](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)创建的提示：

   ```
   # Delete the prompt that you created
   client.delete_prompt(
       promptIdentifier=prompt_id
   )
   ```

------

## 调用托管提示符
<a name="prompt-management-invoke-ex"></a>

在创建提示并对其进行版本控制后，您可以使用 C [onverse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 调用它进行推理。将提示 ARN 指定为，并为`modelId`字段中的任何提示变量提供值。`promptVariables`

```
import boto3, json

bedrock_runtime = boto3.client(service_name="bedrock-runtime", region_name="us-east-1")

# Use the prompt ARN (with version) as the modelId
prompt_arn = "arn:aws:bedrock:us-east-1:123456789012:prompt/PROMPT_ID:VERSION"

response = bedrock_runtime.converse(
    modelId=prompt_arn,
    promptVariables={
        "genre": {"text": "jazz"},
        "number": {"text": "5"}
    }
)

# Print the response
print(response["output"]["message"]["content"][0]["text"])
```

**注意**  
调用托管提示时，您无需指定`messages`或`system`字段，这些字段是在提示模板中定义的。您只需要为提示中定义的变量提供值即可。