

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 執行提示管理程式碼範例
<a name="prompt-management-code-ex"></a>

若要嘗試提示管理的一些程式碼範例，請選擇您偏好方法的索引標籤，然後遵循下列步驟：下列程式碼範例假設您已設定登入資料以使用 AWS API。如果您還沒有執行此操作，請參閱[開始使用 API](getting-started-api.md)。

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

1. 執行下列程式碼片段以載入 適用於 Python (Boto3) 的 AWS SDK、建立用戶端，並建立提示，透過建立適用於 Amazon Bedrock 建置時間端點的 [CreatePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePrompt.html) 代理程式，使用兩個變數 (`genre` 和 `number`) 建立音樂播放清單： [https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt](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. 執行下列程式碼片段產生 [ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html) [Amazon Bedrock 代理人建置時期端點](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。執行下列程式碼片段，以透過產生 [GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html) [Amazon Bedrock 代理人建置時期端點](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. 透過執行下列程式碼片段產生 [CreatePromptVersion](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePromptVersion.html) [Amazon Bedrock 代理人建置時期端點](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. 透過執行下列程式碼片段產生 [ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html) [Amazon Bedrock 代理人建置時期端點](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. 透過執行下列程式碼片段產生 [GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html) [Amazon Bedrock 代理人建置時期端點](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. 透過執行下列程式碼片段產生 [DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html) [Amazon Bedrock 代理人建置時期端點](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. 透過執行下列程式碼片段產生 [DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html) [Amazon Bedrock 代理人建置時期端點](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>

建立提示並建立版本後，您可以使用 [Converse](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` 欄位，這些會在提示範本中定義。您只需為提示中定義的變數提供值。