

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Ejecución de ejemplos de código de administración de peticiones
<a name="prompt-management-code-ex"></a>

Para probar algunos ejemplos de código para la administración de Prompt, elige la pestaña del método que prefieras y, a continuación, sigue los pasos: En los siguientes ejemplos de código se supone que has configurado tus credenciales para usar la AWS API. Si no lo ha hecho, consulte [Introducción a la API](getting-started-api.md).

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

1. Ejecute el siguiente fragmento de código para cargar AWS SDK para Python (Boto3), crear un cliente y crear un mensaje que cree una lista de reproducción de música mediante dos variables (`genre`y`number`) creando un punto final de tiempo de compilación de [CreatePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePrompt.html)[Agents for Amazon Bedrock](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. Ejecuta el siguiente fragmento de código para ver la solicitud que acabas de crear (junto con cualquier otra solicitud de tu cuenta) para crear un punto final en tiempo de compilación de Agents [ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html)[for Amazon Bedrock](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt):

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

1. Debería ver el ID de la petición que ha creado en el campo `id` del objeto en el campo `promptSummaries`. Ejecute el siguiente fragmento de código para mostrar la información de la solicitud que creó al crear un punto final de tiempo de compilación de [GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html)[Agents for 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. Cree una versión del mensaje y obtenga su ID ejecutando el siguiente fragmento de código para crear un punto final en tiempo de compilación de [CreatePromptVersion](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreatePromptVersion.html)[Agents for Amazon Bedrock](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt):

   ```
   # 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. Para ver la información sobre la versión rápida que acaba de crear, junto con la información sobre la versión preliminar, ejecute el siguiente fragmento de código para crear un punto final en tiempo de compilación de [ListPrompts](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListPrompts.html)[Agents for 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. Para ver la información de la versión rápida que acaba de crear, ejecute el siguiente fragmento de código para crear un punto final en tiempo de compilación de [GetPrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetPrompt.html)[Agents for 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. Para probar la petición, añádala a un flujo siguiendo los pasos que se indican en [Ejecución de ejemplos de código de Flujos de Amazon Bedrock](flows-code-ex.md). En el primer paso al crear el flujo, ejecute el siguiente fragmento de código para utilizar la petición que ha creado en lugar de definir una petición en línea en el flujo (sustituya el ARN de la versión de la petición en el campo `promptARN` por el ARN de la versión de la petición que ha creado):

   ```
   # 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. Elimine la versión rápida que acaba de crear ejecutando el siguiente fragmento de código para crear un punto final en tiempo de compilación de [DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html)[Agents for 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. Elimine por completo el mensaje que acaba de crear ejecutando el siguiente fragmento de código para crear un punto final en tiempo de compilación de [DeletePrompt](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeletePrompt.html)[Agents for 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
   )
   ```

------

## Invoca un mensaje gestionado
<a name="prompt-management-invoke-ex"></a>

[Después de crear y versionar una solicitud, puedes invocarla para hacer inferencias mediante la API de Converse.](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) Especifique el ARN de solicitud como `modelId` y proporcione valores para cualquier variable de solicitud del `promptVariables` campo.

```
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"])
```

**nota**  
Al invocar una solicitud gestionada, no es necesario especificar ningún `system` campo, `messages` ya que se definen en la plantilla de solicitud. Solo necesita proporcionar valores para las variables definidas en la solicitud.