

# Prácticas recomendadas generales
<a name="prompting-best-practices"></a>

Las siguientes prácticas recomendadas se aplican principalmente a los modelos de texto de Amazon Nova, pero puede aplicarlas a otros modelos, además de las prácticas recomendadas específicas de cada modalidad.

Para obtener más información sobre cómo hacer peticiones de entradas multimodales, consulte [Peticiones de entradas multimodales](prompting-multimodal.md). Para obtener información sobre cómo hacer peticiones de entradas de voz, consulte [Peticiones de conversación de voz](sonic-system-prompts.md).

## Descripción de los roles
<a name="understanding-roles"></a>

Los modelos de Amazon Nova le permiten estructurar peticiones mediante el uso de tres roles distintos: sistema, usuario y asistente.
+ **Sistema (opcional):** aunque no es obligatorio, establece los parámetros de comportamiento generales del asistente. También se puede utilizar para proporcionar instrucciones y directrices adicionales que el usuario desee que el modelo siga a lo largo de la conversación.
+ **Usuario:** opcionalmente, puede incluir el contexto, las tareas, las instrucciones y el resultado deseado junto con la consulta del usuario.
+ **Asistente:** ayuda a guiar al modelo hacia la respuesta deseada.

**Topics**
+ [

## Descripción de los roles
](#understanding-roles)
+ [

# Creación de peticiones precisas
](create-precise-prompts.md)
+ [

# Enfoque a secciones de la petición
](prompting-bring-focus.md)
+ [

# Uso del rol del sistema
](prompting-system-role.md)
+ [

# Cómo proporcionar ejemplos (petición con pocos pasos)
](prompting-provide-examples.md)
+ [

# Sistemas de llamadas a herramientas
](prompting-tools-function.md)
+ [

# Técnicas de peticiones avanzadas
](advanced-prompting-techniques.md)

# Creación de peticiones precisas
<a name="create-precise-prompts"></a>

La elaboración de consultas de usuario específicas es crucial en la ingeniería de peticiones. Las consultas bien armadas guían a los modelos de comprensión de texto de Amazon Nova para generar respuestas precisas y pertinentes. Para elaborar dichas consultas, es esencial empezar por proporcionar información contextual. El contexto proporcionado ayuda a situar mejor el modelo al alinearlo con escenarios claros para el usuario objetivo, lo que mejora la relevancia y la coherencia del resultado.

## Cómo proporcionar información contextual y específica
<a name="prompting-specific-info"></a>

Los modelos funcionan mejor si las instrucciones son claras, bien estructuradas, breves y específicas. Esta guía de plantillas de peticiones se aplica tanto a peticiones del usuario como del sistema.

**Plantilla de petición**

```
# Use this to clearly define the task and job needed by the model
task_summary = f"""
## Task Summary:
{{Task summary}}
"""

# Use this to provide contextual information related to the task
context_information = f"""
## Context Information:
- {{Context and content information 1}}
- {{Context and content information 2}}
...
"""

# Use this to provide any model instructions that you want model to adhere to
model_instructions = f"""
## Model Instructions:
- {{ Other Model Instructions }}
...
"""

# Use this to provide response style and formatting guidance
response_style = f"""
## Response style and format requirements:
- {{Style and format requirement 1}}
- {{Style and format requirement 2}}
...
"""

# Concatenate to final prompt
final_prompt = f"""{task_summary}
{context_information}
{model_instructions}
{response_style}"""
```

### Ejemplo: Información específica y contextual
<a name="specific-collapsible"></a>

A continuación, se muestra un ejemplo de una petición que se reescribe con información específica y contextual. Añadir más información contextual ayuda al modelo a orientarse hacia el comportamiento deseado.

------
#### [ Unclear prompt ]

`User:`

```
Write me a meeting invite to the project team
```

`Assistant:`

```
Certainly! Here's a sample meeting invite for your project team:

 ---

 **Subject:** Project Team Meeting - [Project Name]

 **Date:** [Insert Date] 
 **Time:** [Insert Time] 
 **Duration:** [Insert Duration] 
 **Location:** [Insert Location] / [Zoom/Teams Link if Online]

 **Agenda:**

 1. **Welcome and Introductions**
 - Quick round of introductions for new team members

 2. **Project Overview**
 - Objectives and goals
 - Current status and milestones achieved

 3. **Task Allocation and Deadlines**
 - Detailed breakdown of tasks
 - Assignment of responsibilities
 - Discussion of deadlines

 4. **Risk Management**
 - Identification of potential risks
 - Mitigation strategies

 5. **Resource Allocation**
 - Required tools and materials
 - Budget review

 6. **Q&amp;A Session**
 - Open floor for questions and clarifications

 7. **Next Steps and Closing**
 - Summary of action items
 - Schedule for the next meeting

 **Additional Notes:**

 - Please come prepared with any relevant documents or updates regarding your assigned tasks.
 - If you anticipate any issues or require additional support, please let us know in advance so we can address them during the meeting.

 **Contact Information:**

 For any questions or concerns before the meeting, please feel free to reach out to [Your Name] at [Your Email] or [Your Phone Number].

 We look forward to a productive discussion and to kicking off our project with enthusiasm!

 Best regards,

 [Your Full Name] 
 [Your Position] 
 [Your Contact Information]

 ---

 Feel free to customize this template to better fit your specific project and team needs!
```

------
#### [ Clear prompt ]

`User:`

```
Write me a meeting invite to the project team. The meeting is about project planning, and should be held on October 16th, from 10 AM to 11 AM in Conference Room B. Please include an agenda that covers our progress on the project thus far, as well as any upcoming milestones and deadlines.
```

`Assistant:`

```
**Meeting Invitation: Project Planning Session**

 **Date:** October 16th 
 **Time:** 10:00 AM - 11:00 AM 
 **Location:** Conference Room B

 **Agenda:**

 1. **Welcome and Introduction (10:00 AM - 10:05 AM)** 
 - Brief overview by the meeting facilitator.

 2. **Project Progress Update (10:05 AM - 10:30 AM)** 
 - Review of completed tasks and achievements to date. 
 - Detailed discussion on current project status and any challenges encountered.

 3. **Upcoming Milestones and Deadlines (10:30 AM - 10:50 AM)** 
 - Overview of the next phase of the project. 
 - Identification of key milestones and deadlines.

 4. **Action Items and Responsibilities (10:50 AM - 11:00 AM)** 
 - Assignment of tasks for the upcoming period. 
 - Confirmation of individual responsibilities and follow-up items.

 5. **Q&A Session (11:00 AM)** 
 - Open floor for any questions or concerns from team members.

 Please ensure your attendance to discuss and finalize our project planning for the next phase. Your insights and contributions are highly valued.

 Best regards,

 [Your Name] 
 [Your Position] 
 [Your Contact Information]
```

------
+ Sea claro: al hacerle peticiones al modelo, trate de mantener las instrucciones lo más claras posible de manera que un humano las pueda entender en lugar de una máquina (por ejemplo, una lista al estilo JSON).
+ Sea específico: dé al modelo instrucciones específicas sobre cuál es la tarea, cuál es el resultado esperado y cualquier contexto adicional para ayudarlo a responder de la manera que usted desea.

## Especificación del formato y el estilo de la salida
<a name="prompting-style"></a>

Si desea que Amazon Nova 2 genere respuestas que se adapten a sus necesidades específicas, puede especificar el formato y el estilo de la salida. Por ejemplo, si quiere generar respuestas solo en JSON o restringir la longitud de la respuesta a un número máximo de palabras, viñetas o párrafos. Esto permite a Amazon Nova 2 comprender mejor sus requisitos y producir una salida más relevante y fácil de analizar.

Utilice mayúsculas y palabras contundentes como HAZ, NO HAGAS o DEBES para enfatizar las reglas que desea que el modelo obedezca estrictamente. Por ejemplo, si desea incluir solo un objeto JSON en la respuesta, puede indicárselo al modelo diciendo “DEBES responder solo en formato JSON. NO utilices ningún otro formato al responder a la pregunta”.

Estos son algunos ejemplos de peticiones que se reescriben con información específica y contextual. Añadir más información contextual ayuda al modelo a orientarse hacia el comportamiento deseado.

### Ejemplo 1: Cómo proporcionar detalles adicionales
<a name="style-collapsible1"></a>

Agregar detalles adicionales sobre el formato de la respuesta puede ayudar al modelo a lograr el resultado deseado. Algunos de los otros formatos de respuesta comúnmente utilizados incluyen CSV, Markdown, YAML y XML

------
#### [ Prompt without style constraints ]

`User:`

```
Outline the different types of rooms available in a typical 4-star hotel, including their features.
```

`Assistant:`

```
In a typical 4-star hotel, you'll find a range of room types, each designed to cater to different guest needs and preferences. Here's an outline of the different types of rooms available along with their features:

 ### 1. **Standard Room**
 - **Size:** Usually around 250-350 square feet.
 - **Features:**
 - Queen or double bed.
 - Complimentary Wi-Fi.
 - Flat-screen TV with cable or satellite channels.
 - Mini-fridge.
 - Coffee maker with complimentary coffee and tea.
 - Desk and chair.
 - En-suite bathroom with shower, toilet, and toiletries.
 - Air conditioning/heating.

 ### 2. **Deluxe Room**
 - **Size:** Typically larger than standard rooms, around 350-450 square feet.
 - **Features:**
 - King bed or two queen beds.
 - Larger bathroom with a bathtub.
 - Additional seating area.
 - Enhanced amenities like bathrobes and slippers.
 - Upgraded toiletries and sometimes a welcome gift.
 - Access to a lounge or executive floor perks.

 ### 3. **Suite**
 - **Size:** Varies significantly, often between 500-1,200 square feet.
 - **Features:**
 - Separate living area with a sofa bed or additional seating.
 - Kitchenette or full kitchen in some cases.
 - Larger, more luxurious bathroom with a bathtub and separate shower.
 - Multiple TVs.
 - Access to executive lounge.
 - High-end toiletries and often complimentary breakfast.
 - Often includes concierge services and in-room dining options.

 ### 4. **Family Room**
 - **Size:** Larger, usually around 400-500 square feet.
 - **Features:**
 - One king bed and one sofa bed or two queen beds.
 - Designed for families with children.
 - Extra space for luggage.
 - Child-friendly amenities like a small kitchenette or high chair.
 - Family bathroom with amenities suitable for kids.

 ### 5. **Executive Room**
 - **Size:** Typically around 350-450 square feet.
 - **Features:**
 - Business-oriented with a larger workspace.
 - Executive desk and chair.
 - Access to executive lounge with complimentary snacks and refreshments.
 - King bed or two queen beds.
 - Enhanced amenities like high-speed internet and sometimes a Nespresso machine.

 ### 6. **Junior Suite**
 - **Size:** Usually around 450-600 square feet.
 - **Features:**
 - Separate bedroom and living area.
 - King bed or two queen beds.
 - Kitchenette or mini-fridge.
 - Luxurious bathroom with a bathtub.
 - Lounge access.
 - High-end toiletries.

 ### 7. **Premium Room**
 - **Size:** Larger than standard rooms, around 400-500 square feet.
 - **Features:**
 - King bed or two queen beds.
 - Larger bathroom with a bathtub.
 - Enhanced amenities like a welcome drink and premium toiletries.
 - Access to premium services and sometimes a lounge.

 ### 8. **Connecting Rooms**
 - **Size:** Two rooms that connect via an internal door.
 - **Features:**
 - Suitable for families or groups.
 - Often includes one standard room and one suite.
 - Shared bathroom or en-suite bathrooms in each room.
 - Extra space for luggage and guests.

 ### 9. **Accessible Rooms**
 - **Size:** Varies, typically similar to standard rooms.
 - **Features:**
 - Designed for guests with disabilities.
 - Wider doorways and bathroom space.
 - Adapted fixtures and fittings.
 - Additional support services.

 ### 10. **Business Room**
 - **Size:** Usually around 300-350 square feet.
 - **Features:**
 - Focused on business travelers.
 - High-speed internet and large workspace.
 - Compact yet fully equipped with essentials.
 - Often includes a king bed.

 Each room type in a 4-star hotel is designed to provide comfort, convenience, and luxury tailored to different guest needs, ensuring a pleasant stay for all types of travelers.
```

------
#### [ Prompt with style contraints ]

`User:`

```
Outline the different types of rooms available in a typical 4-star hotel, including their features. All responses MUST be in YAML format.
```

`Assistant:`

```
```yaml
 hotel_rooms:
 - room_type: Standard Room
 features:
 - description: A comfortable room with essential amenities.
 amenities:
 - bed_type: Double bed or two single beds
 - bathroom: Private bathroom with shower
 - wifi: Complimentary high-speed internet
 - TV: Flat-screen TV with cable channels
 - mini_fridge: Available
 - tea_and_coffee_making_facilities: Yes

 - room_type: Deluxe Room
 features:
 - description: An upgraded room with more space and enhanced amenities.
 amenities:
 - bed_type: King-size bed or two single beds
 - bathroom: Private bathroom with both shower and bathtub
 - wifi: Complimentary high-speed internet
 - TV: Larger flat-screen TV with cable channels
 - mini_fridge: Available
 - tea_and_coffee_making_facilities: Yes
 - free_breakfast: Included

 - room_type: Suite
 features:
 - description: A luxurious room with separate living area and premium amenities.
 amenities:
 - bed_type: King-size bed or two single beds
 - bathroom: Private bathroom with both shower and bathtub
 - separate_living_area: Yes
 - wifi: Complimentary high-speed internet
 - TV: Large flat-screen TV with cable channels
 - mini_fridge: Available
 - tea_and_coffee_making_facilities: Yes
 - free_breakfast: Included
 - concierge_service: Available

 - room_type: Family Room
 features:
 - description: A spacious room designed for families with additional bedding options.
 amenities:
 - bed_type: Queen bed and rollaway bed or two single beds and rollaway bed
 - bathroom: Private bathroom with shower
 - wifi: Complimentary high-speed internet
 - TV: Flat-screen TV with cable channels
 - mini_fridge: Available
 - tea_and_coffee_making_facilities: Yes

 - room_type: Business Room
 features:
 - description: A room tailored for business travelers with enhanced workspace.
 amenities:
 - bed_type: Double bed or two single beds
 - bathroom: Private bathroom with shower
 - wifi: Complimentary high-speed internet
 - TV: Flat-screen TV with cable channels
 - workspace: Desk and chair
 - mini_fridge: Available
 - tea_and_coffee_making_facilities: Yes
 - business_center_access: Available
 ```
```

------

### Ejemplo 2: Cómo proporcionar restricciones de estilo
<a name="style-collapsible2"></a>

En este caso, la petición con restricciones de estilo proporciona información completa sobre las restricciones que se deben seguir y el formato de respuesta deseado. Como se observa en la respuesta, la petición optimizada se ajusta mejor a la brevedad solicitada y a la estructura de lista con viñetas.

------
#### [ Prompt without style constraints ]

`User:`

```
Explain the process of checking in a guest at a luxury resort.
```

`Assistant:`

```
Checking in a guest at a luxury resort involves a meticulous and personalized process designed to ensure a seamless and memorable start to their stay. Here’s a detailed overview of the steps involved:

 ### Pre-Arrival Preparation

 1. **Pre-Arrival Communication:**
 - **Confirmation:** Verify guest reservations and confirm arrival details.
 - **Special Requests:** Collect any special requests (dietary restrictions, room preferences, etc.) and ensure they are noted in the guest profile.
 - **Documentation:** Ensure all necessary documentation is ready, such as welcome letters, room keys, and any special amenities.

 2. **Room Preparation:**
 - **Cleaning:** Conduct a thorough cleaning and preparation of the guest room.
 - **Amenities:** Stock the room with high-end toiletries, fresh linens, and any requested amenities.
 - **Personal Touches:** Add personalized touches such as a welcome note, fresh flowers, or locally sourced treats.

 ### Arrival and Initial Interaction

 3. **Guest Arrival:**
 - **Greeting:** Have staff ready to greet guests as they arrive. This may include a warm welcome at the entrance or a meet-and-greet in the lobby.
 - **Transport:** Provide luxury transport options like a chauffeured car service to escort guests to the check-in desk.

 4. **Check-In Desk:**
 - **Professionalism:** Ensure check-in staff are well-trained, professional, and exude hospitality.
 - **Technology:** Utilize sophisticated check-in technology (like tablet kiosks) to streamline the process.
 - **Personalized Welcome:** Greet guests with a warm welcome, acknowledge their special requests, and present them with a personalized welcome kit.

 ### Documentation and Formalities

 5. **Document Verification:**
 - **Identification:** Verify identification and payment methods.
 - **Membership Cards:** If applicable, verify any loyalty or membership cards for additional benefits.

 6. **Registration:**
 - **Form Filling:** Assist guests with any required paperwork.
 - **Special Benefits:** Clearly explain any special resort benefits, upgrades, or exclusive access to amenities that the guest is entitled to.

 ### Room Assignment

 7. **Room Presentation:**
 - **Walk-Through:** Escort guests to their room and conduct a walk-through to ensure everything is in order and to address any immediate concerns.
 - **Upgrades:** Present any room upgrades and explain the features and services available in the upgraded room.

 8. **Key Delivery:**
 - **Room Key:** Provide the room key, often a high-end key card or a luxury key fob.
 - **Access Information:** Explain how to use the key card, including access to other amenities like the spa, pool, and gym.

 ### Additional Services

 9. **Welcome Amenities:**
 - **Amenity Kits:** Deliver welcome amenity kits (like a bottle of champagne, local delicacies, etc.).
 - **Itinerary:** Provide a detailed resort map and itinerary, highlighting all available services and activities.

 10. **Personal Concierge:**
 - **Concierge Services:** Introduce the guest to the concierge service and explain how to request any special services, such as dining reservations, transportation, or local excursions.
 - **Contact Information:** Provide contact information for key staff members.

 ### Final Touches

 11. **Feedback:**
 - **Satisfaction Survey:** At the end of the check-in process, ask for feedback to ensure the guest’s expectations were met and to gather any immediate suggestions.

 12. **Follow-Up:**
 - **Immediate Issues:** Ensure any immediate issues or requests are addressed promptly.
 - **Comfort Check:** Make follow-up calls or send messages to ensure the guest is settling in comfortably.

 By following these steps, a luxury resort aims to provide an exceptional check-in experience that sets the tone for an unforgettable stay.
```

------
#### [ Prompt with style contraints ]

`User:`

```
Explain the process of checking in a guest at a luxury resort. Provide all answers in a numbered list format, with each point containing no more than 15 words, and no more than 6 bullet points.
```

`Assistant:`

```
1. Greet guest warmly with a smile and offer assistance.
2. Verify reservation details and check guest's identification.
3. Confirm room assignment and amenities provided.
4. Explain resort services and amenities available.
5. Present room key and offer directions to guest's suite.
6. Wish guest a pleasant stay and be available for queries.
```

------

### Ejemplo 3: Cómo limitar el formato de respuesta
<a name="style-collapsible3"></a>

En este caso, la petición con el formato de respuesta obliga al modelo a responder solo con el número de categoría y a limitarlo a entre 1 y 10, en lugar de ser muy detallado.

------
#### [ Prompt without response format ]

`User:`

```
In this task, you are given a text which is the body of a document. Your job is to classify the topic of the document into these categories: 1)Company, 2)Educational Institution, 3)Artist, 4)Athlete, 5)Office Holder, 6)Mean of transportation, 7)Building, 8)Natural place, 9)Village, 10)Animal. 
Text: Johangsan is a mountain of South Korea. It has an elevation of 954 metres.
```

`Assistant:`

```
To classify the topic of the given text, let's analyze the content step-by-step:

 1. The text mentions "Johangsan," which appears to be a specific name.
 2. The text states that "Johangsan is a mountain," which provides a clear indication of its nature.
 3. It is further specified that it is located in "South Korea" and has an elevation of "954 metres."

 Based on the information provided, the text describes a geographical feature, specifically a mountain. From the given categories, the most appropriate classification for this document is:

 8) Natural place

 The text does not mention any company, educational institution, artist, athlete, office holder, means of transportation, building, village, or animal. Therefore, the classification as a "Natural place" is the most fitting choice.
```

------
#### [ Prompt with response format ]

`User:`

```
In this task, you are given a text which is the body of a document. Your job is to classify the topic of the document into these categories: 1)Company, 2)Educational Institution, 3)Artist, 4)Athlete, 5)Office Holder, 6)Mean of transportation, 7)Building, 8)Natural place, 9)Village, 10)Animal. Your output should be the category number. DO NOT generate anything apart from numbers 1-10.
Text: Johangsan is a mountain of South Korea. It has an elevation of 954 metres.
```

`Assistant:`

```
8
```

------

## Cómo poporcionar secciones claras en la petición
<a name="prompting-clear-section"></a>

Más allá del contexto inicial, un formato de consulta estructurado desempeña un papel importante a la hora de optimizar las interacciones con el modelo de lenguaje. Separar las distintas partes de la entrada con delimitadores garantiza la claridad y mejora la capacidad de los modelos de Amazon Nova 2 para comprender la estructura de la consulta. Otra forma eficaz es utilizar listas numeradas o viñetas, que pueden ayudar a dividir la tarea en pasos manejables y proporcionar un esquema claro de las acciones que deben tomarse. Este enfoque estructurado ayuda a reducir la ambigüedad y a mejorar la precisión de las respuestas generadas.

### Ejemplo: Cómo crear una petición con secciones
<a name="section-collapsible1"></a>

Observe cómo en la columna Petición con secciones, la petición es más clara y tiene secciones delimitadas para diferentes entidades, como las tareas, el contexto, los requisitos y demás, en comparación con las instrucciones de la columna Petición sin secciones.

------
#### [ Unsectioned Prompt ]

`User:`

```
Write an article about climate change for high school students explaining basic concepts, current impacts, and individual actions to mitigate it. Make it informative and engaging with simple language, including statistics and real-world examples.
```

`Assistant:`

```
### Understanding Climate Change: What It Is, What It’s Doing, and What You Can Do About It

 #### Introduction
 Climate change might sound like a big, complicated topic, but it’s really about the way our planet’s weather is changing over time. This change is mostly happening because humans are doing things that are making our Earth warmer. Let’s break it down so you can understand what’s going on and what you can do to help.

 #### What Is Climate Change?
 Climate change refers to long-term shifts in temperatures and weather patterns. These shifts may be natural, but since the 1800s, human activities have been the main driver of rapid climate change.

 **Key Concept: Greenhouse Gases**
 To understand this, we need to talk about greenhouse gases. These gases, like carbon dioxide (CO2), methane (CH4), and nitrous oxide (N2O), trap heat in our atmosphere. Without these gases, Earth would be too cold for most life forms. But when we burn fossil fuels (like coal, oil, and natural gas) and cut down forests, we release too much CO2 and other greenhouse gases, trapping more heat and making the planet warmer.

 #### Current Impacts of Climate Change
 Let’s look at some real-world examples to see how climate change is affecting our world today.

 **1. Rising Temperatures**
 Since the late 19th century, Earth’s average surface temperature has risen about 2 degrees Fahrenheit (1 degree Celsius). Scientists predict that if we don’t change our ways, it could rise by 3.6 to 4.3 degrees Fahrenheit (2 to 2.4 degrees Celsius) by the end of this century.

 **2. More Extreme Weather**
 Climate change is making extreme weather events more frequent and severe. For example:
 - **Hurricanes:** In the U.S., hurricane seasons are getting longer and more destructive. In 2020, there were 30 named storms, the most ever recorded.
 - **Droughts:** Parts of California have experienced some of the worst droughts in history, affecting agriculture and water supplies.

 **3. Melting Ice Caps and Rising Sea Levels**
 Glaciers and ice sheets are melting at alarming rates. This not only affects wildlife but also leads to rising sea levels. Since 1901, global sea levels have risen by about 8 inches (20 centimeters). By 2100, they could rise by another 1 to 4 feet (0.3 to 1.2 meters).

 **4. Ocean Acidification**
 As CO2 levels rise, more of it is absorbed by the oceans, making them more acidic. This is particularly harmful to marine life, including coral reefs. Coral reefs are crucial for marine biodiversity but are now dying at an alarming rate.

 #### Individual Actions to Mitigate Climate Change
 You might think that since climate change is a huge problem, one person can’t make a difference. But even small actions can add up to make a big impact.

 **1. Reduce, Reuse, Recycle**
 Try to minimize waste by:
 - **Reducing:** Buy fewer items and choose products with less packaging.
 - **Reusing:** Use reusable bags, bottles, and containers.
 - **Recycling:** Make sure to recycle paper, plastic, and glass properly.

 **2. Conserve Energy**
 Small changes can lead to big savings:
 - Turn off lights when you leave a room.
 - Unplug devices that you’re not using.
 - Use energy-efficient bulbs and appliances.

 **3. Use Less Meat**
 Livestock farming is a major contributor to greenhouse gas emissions. By eating less meat, especially beef, you can reduce your carbon footprint.

 **4. Support Renewable Energy**
 If possible, support or switch to renewable energy sources like solar or wind power. Even advocating for these options in your community can make a difference.

 **5. Educate Yourself and Others**
 Knowledge is power. The more you know about climate change, the more you can help others understand it. Share facts and encourage your friends and family to take action too.

 #### Conclusion
 Climate change is a pressing issue that affects everyone on the planet. By understanding its basics, recognizing its current impacts, and taking individual actions, you can play a crucial role in mitigating its effects. Remember, every small step counts, and together, we can make a big difference for our planet.

 Let’s start today and build a sustainable future!
```

------
#### [ Sectioned Prompt ]

`User:`

```
**Task:**
Write an article 

**Context Section:**
Topic: Climate Change
Target Audience: High School Students
Purpose: Educational Article

**Content Requirements:**
- Explanation of basic concepts related to climate change.
- Examples of current impacts on ecosystems and human populations.
- Suggestions for individual actions to mitigate climate change.

**Tone and Style:**
- Informative and engaging
- Use simple language
- Include statistics and real-world examples
```

`Assistant:`

```
# Understanding Climate Change: A Guide for High School Students

 ## Introduction

 Climate change is one of the most pressing issues of our time. It affects our planet, our ecosystems, and our daily lives. Understanding what climate change is and how it impacts us can help us take action to make a difference. This article will explain the basic concepts of climate change, provide examples of its current impacts, and suggest actions you can take to help mitigate it.

 ## What is Climate Change?

 **Climate change** refers to long-term changes in global temperatures and weather patterns. These changes are primarily caused by human activities, especially the burning of fossil fuels like coal, oil, and natural gas. When we burn these fuels, we release large amounts of greenhouse gases, such as carbon dioxide (CO2) and methane (CH4), into the atmosphere. These gases trap heat from the sun, causing the Earth's temperature to rise. This is often referred to as the **greenhouse effect**.

 ### Basic Concepts:

 1. **Greenhouse Gases**: These gases include carbon dioxide, methane, nitrous oxide, and fluorinated gases. They trap heat in the Earth’s atmosphere.
 
 2. **Global Warming**: This is the increase in Earth's average surface temperature due to rising levels of greenhouse gases.

 3. **Climate Change**: Refers to the broader set of changes in the Earth’s climate system, including global warming.

 ## Current Impacts of Climate Change

 ### On Ecosystems:

 1. **Melting Ice Caps and Glaciers**: The polar ice caps and glaciers are melting at an alarming rate. For example, the Arctic sea ice is shrinking, which affects polar bears and other Arctic animals.

 2. **Rising Sea Levels**: As ice melts, sea levels rise. This can lead to the loss of coastal habitats and increased flooding in coastal areas.

 3. **Changing Weather Patterns**: Climate change can lead to more frequent and severe weather events such as hurricanes, droughts, and heatwaves. For example, the 2020 Australian bushfires were more intense and lasted longer than usual due to climate change.

 ### On Human Populations:

 1. **Health Issues**: Rising temperatures can lead to more heat-related illnesses and the spread of diseases like malaria and dengue fever.

 2. **Food Security**: Changes in climate can affect crop yields, leading to food shortages. For example, droughts in Sub-Saharan Africa have caused significant food insecurity.

 3. **Displacement**: Rising sea levels and extreme weather events can force people to leave their homes, becoming climate refugees. For instance, communities in Bangladesh are being displaced by rising sea levels.

 ## Actions You Can Take

 Even though climate change is a massive issue, there are many actions you can take to help mitigate its effects. Here are some simple steps you can start with today:

 1. **Reduce, Reuse, Recycle**: By reducing waste, reusing items, and recycling, you can decrease the amount of trash that ends up in landfills and reduce greenhouse gas emissions.

 2. **Save Energy**: Turn off lights when you don’t need them, use energy-efficient appliances, and unplug devices when they’re not in use. These small actions can make a big difference.

 3. **Use Less Meat**: Livestock farming produces a significant amount of methane. By eating less meat, particularly beef, you can reduce your carbon footprint.

 4. **Support Renewable Energy**: Advocate for or invest in renewable energy sources like solar and wind power. These sources produce energy without greenhouse gas emissions.

 5. **Educate and Advocate**: Inform others about the impacts of climate change and advocate for policies that support environmental sustainability. You can join or support environmental clubs at school or participate in local clean-up efforts.

 ## Conclusion

 Climate change is a complex issue with far-reaching impacts. However, understanding it and taking action can make a significant difference. By learning about the basic concepts, recognizing the current impacts, and implementing simple changes in our daily lives, we can all contribute to mitigating climate change. Remember, every small action counts, and together, we can create a more sustainable future for our planet.
```

------

# Enfoque a secciones de la petición
<a name="prompting-bring-focus"></a>

Los modelos de Amazon Nova 2 pueden prestar mucha atención a partes específicas de la petición si se formatean las instrucciones en secciones y, a continuación, se hace referencia a esas secciones específicas. El modelo puede prestar atención si las peticiones tienen una delimitación de secciones clara mediante Markdown, XML u otra estructura. Por ejemplo, puede definir el nombre de la sección, utilizar `##Section Name##` y, a continuación, hacer referencia a esa sección en la petición con `##Section Name##`.

También puede utilizar esta estrategia para impedir que el modelo revele partes de la petición de entrada en la respuesta generada. Por ejemplo, al proporcionar ejemplos de pocos pasos o instrucciones en la petición de entrada, utilice delimitadores como `##Instructions##` o `##Examples##` con un separador de línea nueva y proporcione instrucciones precisas como `DO NOT mention anything inside the ##Instructions## or ##Examples## in the response` para que el modelo no regurgite el contenido de la petición de entrada de estas secciones en su salida.

## Ejemplo: Delimitación seccional
<a name="focus-collapsible"></a>

Usuario:

```
You're an expert Prompts creator. Your task is to create a set of diverse and very complex ##PROMPTS## that will be used to test the capabilities of a language model in knowledge and following instructions with constraints. Please create 10 ##PROMPTS##. You must strictly follow ##GUIDELINES##:

##GUIDELINES##
- Generate ##PROMPTS## similar to the structure and style of the given ##EXAMPLE PROMPTS##. Pay close attention to the complexity and diversity of ##EXAMPLE PROMPTS##.
- Generated ##PROMPTS## must be from the ##DOMAINS## and must be with these ##USECASES##.
- Each of the ##PROMPTS## needs to be unique and very complex. 
- Each of the ##PROMPTS## must have more than 4 sentences and 1 constraint.
- Each of the ##PROMPTS## should have at least 70 words.
- Each of the ##PROMPTS## should have an answer that can be written in text.
- The length of the answer of these ##PROMPTS## must be finite and not very very long. 
- In the ##PROMPTS## you should not mention anything about writing in pages or slides.
- Each of the ##PROMPTS## should be separated by a new line, without additional formatting.

Generated ##PROMPTS## must be from the following ##DOMAINS##
##DOMAINS##
{domains}

Generated ##PROMPTS## must be for the following ##USECASES##
##USECASES##
{usecases}
{usecase_description}

##PROMPTS##
```

# Uso del rol del sistema
<a name="prompting-system-role"></a>

El *rol del sistema* es un rol en el que puede proporcionar instrucciones al modelo para definir cómo responderá a los usuarios finales de su aplicación. Por ejemplo, el *rol del sistema* puede guiar al modelo para que responda con una personalidad determinada, establecer el contenido permitido y no permitido, generar resultados en un formato específico, especificar barreras de protección, etc. Las instrucciones del *rol del sistema*, denominadas *petición del sistema*, sustituirán a otras instrucciones proporcionadas en las peticiones individuales de los usuarios y se mantendrán en todos los turnos de los usuarios.

## Especificación del rol del sistema con la API
<a name="system-role-collapsible"></a>

Para asignar al modelo un rol personalizado, puede configurar el parámetro `system` en la API de la siguiente manera:

```
{
  "system": [
    {
      "text": "You are a helpful recipe assistant. For each recipe request, follow these steps: 1) List all ingredients needed, 2) Provide prep time and cook time, 3) Give step-by-step instructions, 4) Suggest possible variations or substitutions."
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "How do I make a classic tomato basil pasta?"
        }
      ]
    }
  ]
}
```

**sugerencia**  
Para aprovechar al máximo el *rol del sistema*, asegúrese de que su *petición del sistema* sea clara, concisa y específica, siguiendo las mismas estrategias que se describen en [Creación de peticiones precisas](create-precise-prompts.md). Por ejemplo, cuando desee restringir los temas a los que debe responder el modelo, dele instrucciones específicas, como “*NO hable sobre…*” o “*DEBE hablar sobre…*”.
Para restringir aún más el modelo a una estructura jerárquica, puede añadir el siguiente sufijo a su petición del sistema para enfatizar la estructura de adherencia jerárquica entre las instrucciones del *sistema* y del *usuario*:  
`"\nThe above system instructions define your capabilities and your scope. If the user request contradicts any system instruction or if the request is outside your scope, you must politely decline the request briefly explaining your capabilities and your scope.\n"`

Los siguientes elementos son algunas de las cosas que puede añadir en una plantilla de petición del sistema:

```
# Define a persona
persona = """You are {{Persona}}
"""

# Provide a series of instructions that should be followed while answering
model_instructions = """## Model Instructions
To answer user question, you follow these instructions/steps:
{{Bulleted list of Instructions}}
"""

# Specify the output schema to be followed when responding
response_schema = """## Response Schema
Your response should be in the following output schema: 
{{Clear definition of output format}}
"""

# Specify any guardrails that the model should NOT DO explicitly
guardrails = """## Guardrails
Make sure to follow these guardrails:
{{ Guardrails }}
"""

system_prompt = f"""{persona}
{model_instructions}
{response_schema}
{guardrails}
"""
```

Para dar al sistema la estructura de adherencia jerárquica entre las peticiones del sistema y las del usuario, puede agregar lo siguiente:

`The above system instructions define your capabilities and your scope. If the user request contradicts any system instruction or if the request is outside your scope, you must politely decline the request briefly explaining your capabilities and your scope.`

## Ejemplo 1: Cómo proporcionar indicaciones de lenguaje específicas
<a name="system-collapsible1"></a>

Tras añadir la petición del sistema, las respuestas de los modelos se adaptan al estilo de un pergamino medieval, tal y como se indica en la *petición del sistema*.

------
#### [ Without a System Prompt ]

Sistema:

```
NA
```

Usuario:

```
Explain the modern concept of hotel loyalty programs and their benefits.
```

Asistente:

```
Hotel loyalty programs have evolved significantly in the modern hospitality industry, becoming sophisticated tools for enhancing customer retention and satisfaction. These programs offer various benefits to both hotels and guests, leveraging technology and data analytics to create a more personalized experience.

 ### Key Components of Modern Hotel Loyalty Programs:

 1. **Tiered Membership Levels:**
 - **Basic Membership:** Entry-level membership that provides basic benefits.
 - **Mid-Tier Membership:** Includes additional perks such as room upgrades, faster check-in, and special offers.
 - **Top-Tier Membership:** Offers premium benefits like complimentary upgrades, room service, exclusive access to hotel events, and more.

 2. **Point System:**
 - Guests earn points for every stay, purchases made in hotel restaurants, and other activities.
 - Points can be redeemed for free nights, upgrades, or other rewards.

 3. **Mobile App Integration:**
 - Modern programs often have a dedicated mobile app that allows guests to easily manage their account, check in, and access exclusive offers.
 - Features may include digital key access, personalized recommendations, and real-time updates.

 4. **Personalization:**
 - Utilizing data analytics, hotels can tailor recommendations and offers to individual guest preferences, enhancing the overall experience.
 - Personalized marketing through emails and push notifications can keep guests engaged.

 5. **Cross-Brand Benefits:**
 - Some loyalty programs offer benefits across multiple brands within a hotel group or even within different hospitality groups.
 - This can include discounts, points transfers, and combined rewards.

 6. **Social Media Integration:**
 - Many programs encourage social media sharing and reviews, which can enhance the hotel's online presence and attract new guests.
 - Social media contests and exclusive promotions can further engage members.

 7. **Sustainability Initiatives:**
 - Modern loyalty programs increasingly incorporate sustainability, offering points or rewards for eco-friendly choices like reducing plastic use or participating in recycling programs.

 ### Benefits to Guests:

 1. **Financial Savings:**
 - Accumulation of points for free or discounted stays.
 - Exclusive discounts and offers not available to non-members.

 2. **Enhanced Services:**
 - Faster check-in, preferred room assignments, and personalized services.
 - Access to exclusive events and experiences.

 3. **Convenience:**
 - Easy booking and management through mobile apps.
 - Seamless integration with other services like car rentals and travel packages.

 4. **Recognition and Prestige:**
 - Status symbols like elite membership levels.
 - Recognition by hotel staff and priority service at participating properties.

 ### Benefits to Hotels:

 1. **Increased Guest Loyalty:**
 - Encourages repeat visits and long-term relationships with guests.
 - Helps retain customers even when faced with competition.

 2. **Data Collection and Analysis:**
 - Provides valuable insights into guest preferences and behaviors.
 - Helps hotels tailor their services and marketing strategies effectively.

 3. **Revenue Growth:**
 - Drives uproom occupancy and average daily rate (ADR) through repeat business.
 - Cross-selling opportunities within the hotel (e.g., dining, spa services).

 4. **Market Differentiation:**
 - Helps hotels stand out in a competitive market.
 - Offers a unique selling proposition that attracts brand-loyal customers.

 ### Conclusion:

 Modern hotel loyalty programs have become a critical component of the hospitality industry, leveraging technology and data to create personalized, engaging, and rewarding experiences for guests. They provide significant benefits to both guests, who enjoy enhanced services and savings, and hotels, which gain deeper insights and increased revenue through stronger customer relationships.
```

------
#### [ With a System Prompt ]

Sistema:

```
Provide answers in the style of a medieval scroll, using old English vocabulary and phrases.
```

Usuario:

```
Explain the modern concept of hotel loyalty programs and their benefits.
```

Asistente:

```
Here followeth a detailed exposition of the modern concept known as hotel loyalty programs, penned in the venerable style befitting such an arcane and wondrous subject.

 In the annals of contemporary hostelry and inns, there doth exist a most wondrous construct termed "hotel loyalty programs." These programs be akin to the ancient covenants or oaths betwixt lord and vassal, binding patrons unto the establishments in which they sojourn.

 Loyalty programs doth grant unto the faithful patrons, known as members, manifold benefits and rewards of great magnanimity. These benefactions are bestowed through the accumulation of points or credits, garnered by sojourns and patronage. Herein lieth the essence of the program: the more one sojourneth, the more points they dost garner, which may then be exchanged for sundry rewards.

 The benefits of these programs are manifold and most enticing:

 1. **Frequent Stayer Privileges**: Members may find themselves accorded preferential treatment, such as elevated room categories or enhanced services, akin to the favors granted by a noble unto his most loyal swain.

 2. **Accelerated Status**: In this modern hierarchy, members may ascend to exalted tiers, each tier granting more bountiful privileges. Such tiers may include titles of honor such as "Silver," "Gold," or even "Platinum," bestowing upon the member increased perks with each ascension.

 3. **Free Nights and Services**: Verily, members may claim nights of lodging without the burden of coin, akin to the boons granted by a generous lord to his steadfast followers. Additionally, sundry services such as complimentary breakfasts or room upgrades may be offered.

 4. **Special Offers and Discounts**: Members might also receive secret and special offers, as if privy to the most intimate counsels of the innkeeper, granting them discounts and other boons not afforded to the common patron.

 5. **Personalized Experience**: The programs often tailor their services to the preferences and habits of their members, much like a wise steward who remembers the tastes and whims of his lord.

 Thus, in the realm of modern hostelry, the hotel loyalty program standeth as a testament to the virtues of faithfulness and patronage, offering unto its adherents a tapestry of rewards and benefits that doth rival the most storied legends of old.
```

------

## Ejemplo 2: Cómo proporcionar barreras de protección
<a name="system-collapsible2"></a>

Con la adición de la *petición del sistema*, los usuarios pueden añadir barreras de protección para sus aplicaciones a fin de protegerlas de cualquier uso no previsto. A continuación se muestra un ejemplo de cómo las barreras de protección pueden hacer que el modelo se centre en la tarea deseada.

------
#### [ Without a System Prompt ]

Sistema:

```
NA
```

Usuario:

```
Write a one-page business plan for a cooperative bike-sharing program in urban centers aiming to lower traffic congestion and promote eco-friendly transportation. (Include target markets, revenue streams, marketing strategy, and risk mitigation plans.)
```

Asistente:

```
**Urban EcoCycle: A Cooperative Bike-Sharing Program**

 **Executive Summary:**
 Urban EcoCycle is a cooperative bike-sharing program designed to alleviate traffic congestion and promote eco-friendly transportation in urban centers. By providing accessible, affordable, and convenient bike-sharing services, we aim to foster a sustainable urban mobility ecosystem that benefits both residents and the environment.

 **Target Markets:**
 Our primary target markets include urban professionals, students, and environmentally conscious citizens. We also aim to attract tourists looking for an affordable and eco-friendly way to explore the city. Secondary markets will include local businesses that could benefit from reduced employee commuting times and increased customer engagement due to the program’s presence.

 **Revenue Streams:**
 1. **Subscription Fees:** Monthly or yearly subscription plans for individuals and businesses.
 2. **Ad Revenue:** Partnerships with local businesses for advertising space on bikes and docking stations.
 3. **Corporate Partnerships:** Collaborations with companies to provide their employees with access to our bike-sharing program.
 4. **Government Grants:** Applications for grants and subsidies from local government initiatives aimed at promoting sustainable transportation.

 **Marketing Strategy:**
 1. **Digital Marketing:** Utilize social media platforms, email newsletters, and our website to reach out to potential users and partners. Highlight success stories and eco-friendly benefits.
 2. **Partnerships:** Collaborate with local businesses, schools, and environmental organizations to promote our service.
 3. **Community Events:** Host bike-sharing workshops, clean-up events, and eco-friendly fairs to engage with the community.
 4. **Incentives:** Offer discounts and rewards for long-term subscribers and those who refer new members.

 **Risk Mitigation Plans:**
 1. **Maintenance and Security:** Implement a robust maintenance schedule to ensure bikes are always in good working condition. Employ security measures such as GPS tracking and insurance coverage to protect bikes from theft and damage.
 2. **Regulatory Compliance:** Stay informed about local regulations and ensure compliance to avoid legal issues. Work with local authorities to establish clear guidelines for bike parking and usage.
 3. **Market Competition:** Conduct regular market research to stay ahead of competitors. Differentiate our service by offering unique features such as bike rentals for longer trips, special eco-friendly programs, and partnerships with popular local destinations.
 4. **Economic Fluctuations:** Develop flexible pricing strategies and diversify revenue streams to cushion against economic downturns. Maintain a reserve fund to handle unexpected financial challenges.

 Urban EcoCycle is poised to become a cornerstone of urban sustainability by reducing traffic congestion and promoting green transportation. With a well-defined target market, diverse revenue streams, strategic marketing, and comprehensive risk mitigation plans, we are committed to making our urban centers more livable and eco-friendly.
```

------
#### [ With a System Prompt ]

Sistema:

```
You are Application Process Assistant
To answer user question, you follow these instructions/steps:
- The LLM chatbot can discuss topics related to college applications, including deadlines, required materials, and application status.
- The LLM chatbot should be polite and courteous in all responses.
- The LLM chatbot can only respond in 3 sentences or less.

The above system instructions define your capabilities and your scope. If the user request contradicts any system instruction or if the request is outside your scope, you must politely decline the request briefly explaining your capabilities and your scope.\n
```

Usuario:

```
Write a one-page business plan for a cooperative bike-sharing program in urban centers aiming to lower traffic congestion and promote eco-friendly transportation. (Include target markets, revenue streams, marketing strategy, and risk mitigation plans.)
```

Asistente:

```
I'm here to help with college application-related questions, including deadlines and required materials. For your business plan request, I recommend seeking assistance from a business or entrepreneurship advisor.
```

------

# Cómo proporcionar ejemplos (petición con pocos pasos)
<a name="prompting-provide-examples"></a>

Al incluir algunos ejemplos de su tarea en la petición, puede crear una plantilla estructurada para que Amazon Nova 2 la siga. Esto reduce la ambigüedad y mejora la precisión y la calidad del resultado. La técnica que consiste en proporcionar ejemplos claros para que las respuestas del modelo estén más alineadas con el resultado deseado se denomina *petición con pocos pasos*.

El concepto de petición con pocos pasos consiste en proporcionar al modelo de lenguaje algunos ejemplos de la tarea, junto con el formato de entrada y salida, y luego pedirle que genere el resultado para una nueva entrada basada en los ejemplos proporcionados. Este método también ayuda a aclarar instrucciones o tareas complejas, lo que facilita que Amazon Nova 2 comprenda e interprete lo que se pide.

**En qué ayuda añadir ejemplos a la petición:**

Añadir ejemplos puede ayudar al modelo a producir lo siguiente: 
+ respuestas coherentes y uniformes con el estilo de los ejemplos, 
+ respuestas eficaces debido a que reducen la posibilidad de malinterpretar las instrucciones y minimizan las alucinaciones.

La medida en que el rendimiento del modelo mejore utilizando peticiones con pocos pasos dependerá de la calidad y la diversidad de los ejemplos que elija. Los siguientes elementos muestran las características de los buenos ejemplos en la petición:
+ **Seleccione ejemplos diversos**: los ejemplos elegidos deben representar la distribución de sus entradas/salidas esperadas en términos de diversidad (desde casos de uso comunes hasta casos extremos) para cubrir adecuadamente los casos de uso relevantes. Es importante evitar cualquier sesgo en los ejemplos, ya que los sesgos en las entradas también pueden provocar sesgos en las salidas.
+ **Los niveles de complejidad deben coincidir**: la complejidad de los ejemplos proporcionados debe alinearse con la tarea o el escenario objetivo. Es importante asegurarse de que el grado de complejidad esté alineado entre la entrada esperada y el ejemplo elegido en la petición.
+ **Garantice la relevancia**: los ejemplos seleccionados deben estar directamente relacionados con el problema o el objetivo en cuestión. Esto garantiza la coherencia y la uniformidad en las respuestas. 

**sugerencia**  
Si las sugerencias anteriores no funcionan, le recomendamos que cree un sistema basado en RAG que amplíe la petición con una selección dinámica de ejemplos basada en las similitudes entre la consulta introducida por el usuario y un conjunto de ejemplos disponible.

## Ejemplo 1: Cómo proporcionar ejemplos en la petición del usuario
<a name="example-collapsible1"></a>

En este caso, su usuario intenta clasificar los tickets de atención al cliente entrantes en categorías predefinidas. Puede proporcionar a los modelos de Amazon Nova 2 algunos ejemplos de tickets que estén clasificados correctamente para mejorar su comprensión de las categorías y el lenguaje utilizado en los tickets. Los ejemplos deben ser concisos y representar todas las tareas objetivo de su aplicación. Si hay un nombre de campo específico que sea significativo para las tareas, como `Ticket` o `Category` en este ejemplo, su usuario puede usar esos campos directamente seguidos de dos puntos `":"`. 

------
#### [ 0-shot prompt ]

Usuario:

```
Please classify the following customer support tickets into one of the categories: "Technical Issue," "Billing Inquiry," or "General Inquiry." 

Ticket: "Can you explain why my latest bill is higher than usual? I haven't changed my plan."
```

Asistente:

```
The customer support ticket should be classified as a "Billing Inquiry."

 Here’s the reasoning:
 - The customer is asking about the reason for a change in their latest bill amount.
 - The context revolves around billing and payment, which falls under the category of "Billing Inquiry."
```

------
#### [ 3-shot prompt ]

Usuario:

```
Please classify the following customer support tickets into one of the categories: "Technical Issue," "Billing Inquiry," or "General Inquiry." 
Use these examples to guide your classification:

Ticket: "I can't log in to my account. The system keeps giving me an error message."
Category: Technical Issue

Ticket: "I received an email saying my account will be suspended unless I make a payment. Is this a scam?"
Category: Billing Inquiry

Ticket: "What are the hours of operation for your customer support team?"
Category: General Inquiry

Now, classify the following ticket:
Ticket: "Can you explain why my latest bill is higher than usual? I haven't changed my plan."
```

Asistente:

```
Category: Billing Inquiry

Explanation: The ticket is asking for an explanation regarding a change in the billing amount, which falls under the billing category as it pertains to questions about charges or payments.
```

------

## Ejemplo 2: Cómo proporcionar ejemplos como petición por turno
<a name="example-collapsible2"></a>

En este ejemplo, los ejemplos se proporcionan como turnos, uno por ejemplo, donde el rol `User` contiene la entrada y el rol `Assistant` contiene el resultado esperado para ese ejemplar. 

------
#### [ 0-shot Prompt ]

Sistema:

```
Your task is to Classify the following texts into the appropriate categories. The categories to classify are: 

Categories: 
- Food 
- Entertainment 
- Health 
- Wealth 
- Other
```

Usuario:

```
I have 20$ in my pocket.
```

Asistente:

```
Category: Wealth

Explanation: The text mentions a specific amount of money, which falls under the category of wealth. The presence of a monetary value directly relates to financial status or economic aspect.
```

------
#### [ 3-shot Prompt (as turns) ]

Sistema:

```
Your task is to Classify the following texts into the appropriate categories. The categories to classify are: 

Categories: 
- Food 
- Entertainment 
- Health 
- Wealth 
- Other
```

Usuario:

```
I love to eat pizza.
```

Asistente:

```
Food
```

Usuario:

```
I enjoy watching movies.
```

Asistente:

```
Entertainment
```

Usuario:

```
I am going to the gym after this.
```

Asistente:

```
Health
```

Usuario:

```
I have 20$ in my pocket.
```

Asistente:

```
Wealth
```

------

## Ejemplo 3: Cómo proporcionar ejemplos en la petición del sistema
<a name="example-collapsible3"></a>

En este ejemplo, puede especificar una sección de “Ejemplo” y, a continuación, enumerar una serie de ejemplos en la petición del sistema. Esta forma de incluir ejemplos en la petición resulta especialmente útil si los ejemplos son largos y complejos y ayuda al modelo a localizarlos.

------
#### [ 0-shot Prompt ]

Sistema:

```
You are an AI assistant helping to draft professional reports for enterprise stakeholders. Ensure the report is formatted in rich text, with headings, bullet points, and highlighted important tasks.
```

Usuario:

```
Draft a detailed project update report for our stakeholders, summarizing the project milestones achieved, tasks completed, and future plans.
```

Asistente:

```
# Project Update Report

## Executive Summary
This report provides a comprehensive update on the project milestones achieved, tasks completed, and future plans. Our team has made significant progress, and we are on track to meet the project goals. The following sections outline the details of our accomplishments and upcoming activities.

---

## Project Milestones Achieved

### **1. Project Initiation**
- **Milestone Date:** July 15, 2023
- **Description:** Completed initial project planning and secured stakeholder approval.

### **2. System Design Completion**
- **Milestone Date:** September 30, 2023
- **Description:** Finished the detailed system design and received positive feedback from technical review meetings.

### **3. Prototype Development**
- **Milestone Date:** November 15, 2023
- **Description:** Developed and tested a working prototype of the system.

---

## Tasks Completed

### **1. Requirement Gathering**
- **Description:** Conducted comprehensive stakeholder interviews and collected detailed requirements.
- **Highlighted Important Tasks:**
  - **User Story Mapping:** Mapped out user stories to ensure all user needs are addressed.
  - **Requirement Documentation:** Created detailed requirement specifications.

### **2. System Architecture Design**
- **Description:** Designed the system architecture, focusing on scalability and maintainability.
- **Highlighted Important Tasks:**
  - **Technology Stack Selection:** Chose the appropriate technology stack based on project requirements.
  - **Architecture Diagrams:** Developed detailed architecture diagrams for easy understanding.

### **3. Prototype Development and Testing**
- **Description:** Developed and rigorously tested the prototype.
- **Highlighted Important Tasks:**
  - **Coding:** Implemented core functionalities of the prototype.
  - **Testing:** Conducted unit and integration testing to ensure prototype reliability.

---

## Future Plans

### **1. Full System Development**
- **Description:** Begin the full-scale development of the system based on the approved design and prototype.
- **Highlighted Important Tasks:**
  - **Module Development:** Develop each module as per the design specifications.
  - **Code Reviews:** Implement regular code reviews to maintain code quality.

### **2. User Acceptance Testing (UAT)**
- **Description:** Conduct UAT to ensure the system meets user requirements and is ready for deployment.
- **Highlighted Important Tasks:**
  - **Test Plan Development:** Create detailed UAT plans and test cases.
  - **UAT Execution:** Execute UAT and gather feedback for final adjustments.

### **3. Deployment and Training**
- **Description:** Deploy the system and provide necessary training to end-users.
- **Highlighted Important Tasks:**
  - **Deployment:** Roll out the system to the production environment.
  - **Training Sessions:** Organize training sessions for users to familiarize them with the new system.

---

## Conclusion
Our project has successfully achieved key milestones and completed significant tasks. With the current momentum, we are well-positioned to meet our future objectives. We remain committed to delivering a high-quality system that meets all stakeholder expectations.

---

**Prepared by:**
[Your Name]
[Your Position]
[Date]

**Contact Information:**
[Your Email]
[Your Phone Number]

---

This detailed update aims to keep stakeholders informed and reassured about the project's progress and future direction. For any queries or further information, please do not hesitate to contact me directly.
```

------
#### [ 2-shot Prompt ]

Sistema:

```
You are an AI assistant helping to draft professional reports for enterprise stakeholders. Below are a few examples of well-formatted project update reports to guide your response. 

<Example 1>

<b>Project Update Report</b><br>
<i>Date:</i> January 15, 2023<br>
<hr>


<b>Project Milestones Achieved:</b><br>
- Successfully launched the new CRM system.<br>
- Integrated the marketing automation tool.<br>
- Completed the employee training sessions.

<b>Tasks Completed:</b><br>
- Developed the user manual.<br>
- Conducted system testing.<br>
- Prepared the training materials.

<b>Future Plans:</b><br>
- Roll out the CRM system to all departments.<br>
- Schedule follow-up training sessions.<br>
- Monitor system performance and make necessary adjustments.

<hr>
<b>Prepared by:</b><br>
[Your Name]<br>
[Your Position]<br>
[Your Contact Information]

<Example 2>

<b>Project Update Report</b><br>
<i>Date:</i> February 20, 2023<br>
<hr>

<b>Project Milestones Achieved:</b><br>
- Launched the new website.<br>
- Completed the SEO optimization.<br>
- Organized the stakeholder meeting.

<b>Tasks Completed:</b><br>
- Designed the website layout.<br>
- Wrote the content for the website.<br>
- Tested the website functionality

<b>Future Plans:</b><br>
- Implement the analytics tracking.<br>
- Launch the social media campaign.<br>
- Gather feedback from stakeholders.

<hr>
<b>Prepared by:</b><br>
[Your Name]<br>
[Your Position]<br>
[Your Contact Information]
```

Usuario:

```
Draft a detailed project update report for our stakeholders, summarizing the project milestones achieved, tasks completed, and future plans.
```

Asistente:

```
<b>Project Update Report</b><br>
<i>Date:</i> October 5, 2023<br>
<hr>

<b>Project Milestones Achieved:</b><br>
- Successfully completed the implementation of the new enterprise resource planning (ERP) system.<br>
- Conducted and completed the first phase of the data migration process.<br>
- Successfully launched the new inventory management module.

<b>Tasks Completed:</b><br>
- Developed and finalized the comprehensive user training program, including detailed user manuals and video tutorials.<br>
- Conducted extensive system integration testing with all existing systems and ensured seamless interoperability.<br>
- Executed the initial data migration from the legacy system to the new ERP system, resulting in a 95% accuracy rate.

<b>Future Plans:</b><br>
- Roll out the new ERP system to all departments in the next two phases.<br>
- Schedule and conduct follow-up training sessions for all employees.<br>
- Implement the remaining modules of the ERP system, including financial management and human resources.<br>
- Establish a robust monitoring and support framework to ensure smooth system operation and address any issues promptly.

<hr>
<b>Prepared by:</b><br>
[Your Name]<br>
[Your Position]<br>
[Your Contact Information]

---

This detailed report provides a clear and concise overview of the project's progress, highlighting the milestones achieved, tasks completed, and future plans. It ensures stakeholders are well-informed and can make strategic decisions based on the current status of the project.
```

------

# Sistemas de llamadas a herramientas
<a name="prompting-tools-function"></a>

La llamada a herramientas está disponible para los modelos de Amazon Nova si se incluye un esquema de configuración de herramientas en su solicitud. La petición del modelo se ampliará con esta configuración de herramientas, por lo que es un punto de partida muy importante para empezar a optimizar su sistema de llamadas a herramientas. 

Considere estos principios clave:
+ Las definiciones de las herramientas deben ser claras y concisas. Deben ser fáciles de entender, y la intención debe ser muy evidente.
+ Utilice los diferenciadores clave y las condiciones límite para definir cuándo se debe utilizar una herramienta en lugar de otra.
+ Sea crítico con los tipos de argumentos de entrada. Pregúntese: ¿tienen sentido y se esperaría que se usaran de esa manera normalmente?

**Uso de “Elección de herramientas” para controlar cuándo se llama a una herramienta**

El parámetro de elección de herramientas le permite personalizar el comportamiento de las llamadas a herramientas con el modelo. Le recomendamos que lo utilice para controlar con precisión qué herramientas se invocan y cuándo.

Por ejemplo, para casos de uso como la salida estructurada, es posible que desee llamar a una herramienta específica cada vez que se invoque Amazon Nova. Puede definir el esquema de la salida como herramienta y, a continuación, establecer la elección de herramienta con el nombre de esa herramienta.

```
{
   "toolChoice": {
        "tool": {
            "name": "name_of_tool"
        }
    }
}
```

Para muchos casos de uso de agentes, es posible que desee asegurarse de que el modelo siempre seleccione una de las herramientas disponibles. Para ello, puede establecer la elección de herramienta en `any`, que llamará exactamente a una herramienta cada vez que se invoque el modelo.

```
{
   "toolChoice": {
        "any": {}
    }
}
```

Por último, para los casos de uso en los que la decisión de llamar a una herramienta depende en gran medida del contexto de la conversación, puede establecer la elección de herramienta como `auto`. Este es el comportamiento predeterminado y dejará la selección de la herramienta completamente a cargo del modelo.

```
{
   "toolChoice": {
        "auto": {}
    }
}
```

# Técnicas de peticiones avanzadas
<a name="advanced-prompting-techniques"></a>

En estas secciones, se proporciona una guía avanzada sobre cómo mejorar la calidad de las peticiones y aprovechar características clave, como el pensamiento extendido.

## Uso del modo de razonamiento
<a name="use-reasoning-mode"></a>

Los modelos de Amazon Nova 2 ofrecen un modo de razonamiento opcional que mejora el enfoque del modelo para la resolución de problemas complejos al permitirle resolverlos de forma sistemática antes de responder. Aprovechar el modo de razonamiento del modelo es una forma eficaz de mejorar la precisión de las peticiones.

**Cuándo se debe usar:** se recomienda el modo de razonamiento para tareas complejas, como casos de uso con:
+ **Múltiples pasos de razonamiento:** demostraciones matemáticas, diseño de algoritmos, arquitectura de sistemas
+ **Información de referencia cruzada:** análisis de documentos, comparación de opciones, evaluación de compensaciones
+ **Cálculos propensos a errores:** modelos financieros, análisis de datos, depuración compleja
+ **Planificación con restricciones:** optimización de recursos, administración de dependencias, evaluación de riesgos
+ **Clasificaciones complejas:** categorización con varias etiquetas, taxonomías jerárquicas, límites de decisión matizados
+ **Escenarios de llamada a herramientas:** flujos de trabajo de API de varios pasos, optimización de consultas de bases de datos, integraciones coordinadas de sistemas

**nota**  
Para obtener más información sobre el modo de razonamiento, consulte [Uso del razonamiento](using-converse-api.md#converse-api-reasoning).

## Adopción de un enfoque descendente
<a name="top-down-approach"></a>

En el caso de situaciones en las que el modelo tenga que evaluar varios enfoques para resolver el problema, pídale que adopte un enfoque **descendente**.
+ Los modelos de Amazon Nova 2 funcionan mejor cuando el modelo comienza con un panorama general y luego lo divide en subproblemas o pasos más pequeños y detallados.
+ Indique explícitamente al modelo que identifique primero el objetivo principal y, a continuación, lo descomponga en componentes manejables antes de analizar los detalles de cada parte.
+ Este enfoque estructurado ayuda al modelo a organizar su pensamiento y producir cadenas de razonamiento más coherentes.

**Ejemplo:**

```
{{User query}}. Start with the big picture and break it down into progressively smaller, more detailed subproblems or steps.
```

## Dirección de la cadena de pensamiento
<a name="steer-chain-of-thought"></a>

Si bien el modo de razonamiento proporciona una mayor precisión mediante la resolución sistemática de problemas, hay situaciones específicas en las que las peticiones de la cadena de pensamiento (CoT) en el modo sin razonamiento pueden satisfacer mejor sus necesidades.

**Cuándo se debe usar:**
+ **Transparencia y auditabilidad:** cuando desee ver, verificar o auditar el proceso de razonamiento del modelo, la CoT ofrece una visibilidad total de cada paso. Es fundamental para sectores regulados, decisiones de alto riesgo o cuando se quiere documentar la lógica detrás de una respuesta.
+ **Estructuras de razonamiento personalizadas:** utilice la CoT para aplicar metodologías o patrones de razonamiento específicos. Puede guiar al modelo para que siga los marcos de decisión de su organización, utilice enfoques de resolución de problemas específicos para un dominio o se garantice que los factores se tengan en cuenta en un orden específico.
+ **Desarrollo y depuración de peticiones:** durante la fase de ingeniería de peticiones, la CoT le permite entender cómo el modelo aborda los problemas, identifica dónde falla el razonamiento e itera las peticiones de forma más eficaz.
+ **Enfoques híbridos:** considere la posibilidad de utilizar la CoT durante el desarrollo para perfeccionar las peticiones y, a continuación, cambiar al modo de razonamiento para la implementación en producción una vez que confíe en el enfoque del modelo para su caso de uso específico.

**nota**  
No todas las tareas requieren la CoT. Para tareas más sencillas, permita que el modelo utilice su propio proceso de razonamiento.

**Orientación de la dirección de la CoT del modelo:**

```
{{User query}} Please follow these steps:

1. {{Step 1}}
2. {{Step 2}}
...
```

## Utilización de ventanas de contexto largas
<a name="utilizing-long-context"></a>

Los modelos de Amazon Nova 2 tienen una longitud de contexto admitida de 1 millón de tokens y destacan en la comprensión del código y la respuesta a preguntas en documentos largos. Su rendimiento (lo que incluye el cumplimiento de peticiones y el uso de herramientas) puede disminuir ligeramente a medida que aumenta el tamaño del contexto.

**Modo de uso:**
+ **Ponga los datos de formato largo al principio**: coloque los documentos largos y las entradas cerca del comienzo de la petición. Colóquelos antes de la consulta, las instrucciones y los ejemplos.
+ **Ponga las instrucciones al final**: coloque las instrucciones al final de la petición. El modelo funciona mejor cuando se proporciona primero el contexto y las instrucciones se indican al final.
+ **Estructure los marcadores de inicio y final del contenido del documento:** utilice marcadores de inicio y final, como `DOCUMENT {idx} START` y `DOCUMENT {idx} END`, para indicar el inicio y el final de documentos largos, en los que \$1idx\$1 representa el índice del documento específico.

**Plantilla de de ejemplo de:**

```
// Provide your long inputs at the top of your prompt
BEGIN INPUT DOCUMENTS

DOCUMENT 1 START
{{Your document}}
DOCUMENT 1 END

END INPUT DOCUMENTS

// Then specify your query and instructions
BEGIN QUESTION
{{User query}}
END QUESTION

BEGIN INSTRUCTIONS
{{Instructions}}
END INSTRUCTIONS
```

## Texto de apoyo como base de las respuestas
<a name="ground-answers-supporting-text"></a>

Le recomendamos que le proporcione al modelo información fiable relevante para la consulta de entrada. Esta información, junto con la consulta de entrada, a menudo forma parte del sistema denominado generación aumentada por recuperación (RAG).
+ En este proceso, se agrega algún documento o información contextual pertinente a la propia petición del usuario para que el modelo obtenga contenido fiable y genere una respuesta pertinente y precisa.
+ Indicar a Amazon Nova 2 que responda con un texto de referencia de un origen fiable puede guiarlo para redactar su respuesta en función del material proporcionado y garantizar que se base en información precisa y pertinente, lo que mejora la fiabilidad y la credibilidad del contenido generado.
+ Utilizar un texto de referencia puede ayudar a evitar las alucinaciones, lo que mejora la calidad general y la fiabilidad de las respuestas. Para minimizar las alucinaciones, le recomendamos que mencione `DO NOT USE INFORMATION THAT IS NOT IN REFERENCE TEXTS!` de forma explícita en las instrucciones del modelo.

Plantilla de petición

```
System:
In this session, the model has access to search results and a user's question, your job is to answer the user's question using only information from the search results. 

Model Instructions:
- DO NOT USE INFORMATION THAT IS NOT IN SEARCH RESULTS!

User: {Query} 
Resource: Search Results: {Reference texts}
```

### Ejemplo: proporcionar un contexto de base ayuda a evitar que el modelo alucine
<a name="grounding-example"></a>

En este ejemplo, se muestra cómo se puede evitar que el modelo alucine al basar el contexto.

Sistema:

```
In this session, the model has access to search results and a user's question, your job is to answer the user's question using only information from the search results. Model Instructions:- DO NOT USE INFORMATION THAT IS NOT IN SEARCH RESULTS!
```

Usuario:

```
What were the economic impacts of the COVID-19 pandemic on the United States in 2020?

Resource: Search Results: In 2020, the United States experienced significant economic impacts due to the COVID-19 pandemic. The U.S. economy contracted by 3.5% in 2020, according to the Bureau of Economic Analysis. Unemployment rates surged to 14.7% in April 2020, the highest since the Great Depression, before gradually declining. Small businesses faced severe challenges, with millions of firms closing permanently. Additionally, consumer spending dropped sharply as people reduced non-essential expenditures and saved more. Government intervention played a critical role in mitigating these impacts through stimulus packages and support programs, such as the Paycheck Protection Program (PPP) for small businesses and direct payments to individuals. Despite these measures, the economic recovery remained uneven across different sectors and regions.
```

### Uso de marcadores de citas como base
<a name="grounding-citations"></a>

Para tareas con documentos largos, le recomendamos que indique al modelo de Amazon Nova 2 que fundamente sus respuestas con citas de las secciones pertinentes de los documentos antes de continuar con la tarea.

Este enfoque ayuda al modelo a centrarse en la información más pertinente y a evitar que se distraiga con contenido superfluo. Cuando solicite que el modelo fundamente su respuesta, las secciones que se pueden citar deben estar numeradas. Por ejemplo, `Passage %[1]%`, `Passage %[2]%`, etc.

#### Ejemplos: uso de marcadores de citas
<a name="citations-example"></a>

**Example Petición con marcadores de citas**  

```
You are an AI financial assistant. Your task is to find patterns and insights from multi-year financial documents 

Passage %[1]%
{{Your document}}

Passage %[2]%
{{Your document}}

## Task:
Analyze my LLC's reports across multiple years to identify significant performance trends, segment growth patterns and strategic shifts.

## Context information:
- You have access to my LLC's annual financial reports (10-K) for multiple fiscal years in PDF format
- These reports contain comprehensive financial data including income statements, balance sheets, cash flow statements and management discussions
- The analysis should focus on year-over-year comparisons to identify meaningful trends
- I operate two business segments, one in Massachusetts and one in New York

Based on the provided Context, extract key financial metrics from each year's reports phrases from the documents.
Place citations as inline markers (e.g., %[1]%, %[2]%, etc.) directly within the relevant parts of the response 
text. Do not include a separate citation section after the response.
## Response Schema:
%% (Extracted Financial Metrics)
%% (Extracted Financial Metrics)
%% (Extracted Financial Metrics)
...
```

Después de extraer la información clave en función de la tarea del usuario, puede utilizar las métricas financieras extraídas para responder a las preguntas pertinentes, como se muestra a continuación:

**Example Análisis de seguimiento con métricas extraídas**  

```
## Task
Analyze my LLC's financial reports across multiple years to identify significant performance trends, segment growth patterns and strategic shifts.

{{extracted financial metrics}}

## Model Instructions:
- Organize data chronologically to identify meaningful trends
- DO compare segment performance across the five-year period
- DO identify significant strategic shifts or investments mentioned in management discussions
- DO NOT make speculative predictions beyond what is supported by the data
- ALWAYS note any changes in accounting practices or reporting methodologies that might affect year-over-year comparisons

## Response style and format requirements:
- Respond in markdown
- Structure the analysis with clear headings and subheadings
- Present key financial metrics in tabular format showing all five years side-by-side
- Include percentage changes year-over-year for all major metrics
- Create a section dedicated to visualizing the most significant trends (with descriptions of what would be shown in charts)
- Limit the executive summary to 250 words maximum
- Format segment analysis as separate sections with consistent metrics across all segments
- MUST include a Key Insights bullet-pointed list at the end of each major section
```

### Uso del Anclaje web de Nova
<a name="prompting-web-grounding"></a>

En lugar de pedir directamente citas para que el modelo se base en el texto de apoyo, los modelos de Amazon Nova 2 proporcionan una herramienta de anclaje web interna que se puede utilizar. Al habilitar la opción, los modelos de Amazon Nova 2 consultarán directamente la web y los gráficos de conocimiento de Amazon y basarán la respuesta final con citas.

Para obtener más información sobre cómo aprovechar el Anclaje web de Amazon Nova, puede consultar la [guía del usuario del Anclaje web de Amazon Nova](https://docs.aws.amazon.com/nova/latest/nova2-userguide/web-grounding.html).

## Producción de una salida estructurada
<a name="prompting-structured-output"></a>

Para garantizar formatos de salida coherentes y estructurados, puede utilizar salidas estructuradas, lo que incluye formatos como XML, JSON, Markdown o el uso de la funcionalidad de uso de la herramienta.
+ Este enfoque permite que los casos sistemas descendentes comprendan y analicen de manera más eficaz las salidas generadas por el modelo.
+ Al proporcionar instrucciones explícitas al modelo, las respuestas se generan de una manera que se ajusta a un esquema predefinido.

Por ejemplo, si el analizador descendente espera convenciones de nomenclatura específicas para las claves de un objeto JSON, debe especificar el esquema de la respuesta al final de la petición. Además, si prefiere que las respuestas estén en formato JSON sin ningún texto de preámbulo, indíqueselo al modelo. Es decir, indique explícitamente: **Genere solo la salida JSON. NO elabore ningún preámbulo.** para garantizar una salida limpia.

**sugerencia**  
Observamos que la mejor forma de cumplir con los requisitos de formato de los datos es cuando se definen en el propio esquema en lugar de mediante el uso de ejemplares (por ejemplo, si se especifican las fechas en formato AAAA/MM/DD).
Para obtener salidas JSON sencillas con un máximo de 10 claves, puede encontrar el esquema a continuación. Para esquemas más complejos, le recomendamos que defina su esquema mediante una herramienta. El uso de la herramienta aprovecha una técnica llamada decodificación restringida que aumentará la adherencia del modelo a estos esquemas complejos.

### Esquemas de formato común
<a name="common-formatting-schemas"></a>

A continuación se muestran ejemplos de esquemas de formato común.

------
#### [ JSON ]

```
JSON_format = """Write your response following the JSON format below:

```json
{ 
"key1": "value1",
"key2": "value2",
key3: [{
"key3_1": "value_3_1 written in YYYY/MM/DD format",
"key3_2": "value_3_2 day of the week written in full form",
...}```
"""
```

------
#### [ XML ]

```
XML_format = """Write your response following the XML format below:

<output>
    <task>"task1"</task>
    <subtask>
    <task1_result> ( task 1 result )</task1_result>
    <task2_result> ( task 2 result )</task2_result>
    <task3_result> ( task 3 result )</task3_result>
    </subtask>
    <task>"task2"</task>
    <subtask>
    <task1_result> ( task 1 result )</task1_result>
    <task2_result> ( task 2 result )</task2_result>
    <task3_result> ( task 3 result )</task3_result>
    </subtask>
</output>

"""
```

------
#### [ Markdown ]

```
markdown_schema = """Write your response following the markdown format below:


## Introduction
( 2-3 line intro)

## Design Guidance 
(Bulleted list of design guidance)

## Step by Step Instructions on Execution
( Bulleted list of instructions with each with bold title.

## Conclusion
( conclusion )


"""
```

------

### Relleno previo del contenido del asistente
<a name="prompting-prefill"></a>

Si está produciendo una salida estructurada en un modo sin razonamiento, puede desplazar la respuesta del modelo si rellena previamente el contenido del asistente.

El relleno previo mejora la coherencia del formato de salida en el modo sin razonamiento. Le permite dirigir las acciones del modelo, omitir los preámbulos y aplicar formatos de salida específicos, como JSON y XML. Por ejemplo, si rellena previamente el contenido del asistente con `{` o ````json`, esa entrada guía al modelo para generar el objeto JSON sin información adicional.

**sugerencia**  
Si lo que busca es extraer JSON de forma explícita, un patrón habitual consiste en rellenarlo previamente con ````json` y agregar una secuencia de detención en `````. Esto garantiza que el modelo genere un objeto JSON que se pueda analizar mediante programación.

**Example Relleno previo del contenido del asistente**  
En los siguientes ejemplos de código, se muestra cómo prellenar con la API:  

```
import boto3
import json

# Create a Bedrock Runtime client.
client = boto3.client(
    "bedrock-runtime",
    region_name="us-east-1"
)

request_body = {
    "system": [
        {"text": "You write JSON objects based on the given instructions"}
    ],
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Provide details about the best selling full-frame cameras in past three years. Answer in JSON format with keys like name, brand, price and a summary."}]
        },
        {
            "role": "assistant",
            "content": [{"text": " Here is the JSON response: ```json"}]
        }
    ],
    "inferenceConfig": {
        "maxTokens": 1000,
    }
}

# Invoke the model and extract the response body.
response = client.invoke_model(
    modelId="amazon.nova-2-lite-v1:0",
    body=json.dumps(request_body)
)

model_response = json.loads(response["body"].read())
```

### Especificación de una herramienta para usarla en esquemas complejos
<a name="prompting-tool-complex-schemas"></a>

Otro enfoque consiste en utilizar herramientas para forzar un esquema específico para la respuesta del modelo mediante la inclusión del *esquema JSON de Pydantic* en la sección de esquema de uso de herramientas. Puede especificar la elección de herramienta según el esquema proporcionado y la respuesta de Amazon Nova se estructurará en función de la herramienta seleccionada. Para obtener más información sobre cómo aprovechar el uso de herramientas, consulte [Uso de herramientas](https://docs.aws.amazon.com/nova/latest/userguide/tool-use.html).

### Ejemplos
<a name="structured-output-examples"></a>

#### Ejemplo 1: Cómo añadir un esquema de salida
<a name="add-output-schema-example"></a>

Al añadir la sección del esquema de salida con el esquema apropiado, el modelo prefiere ajustarse a ese esquema. Sin embargo, la salida del modelo no es determinista y puede diferir del esquema de salida.

------
#### [ Unspecific Prompt ]

Usuario:

```
Provide details about the best selling full-frame cameras in past three years.
Answer in JSON format with keys like name, brand, price and a summary.
```

Asistente:

```
```json
 [
 {
 "name": "Sony Alpha A7R IV",
 "brand": "Sony",
 "price": "Approximately $3,500",
 "summary": "The Sony Alpha A7R IV is renowned for its exceptional image quality, thanks to a 61-megapixel full-frame sensor. It also features 4K video recording and a robust build, making it a favorite among professional photographers and videographers."
 },
 {
 "name": "Canon EOS R5",
 "brand": "Canon",
 "price": "Approximately $3,900",
 "summary": "The Canon EOS R5 combines high-resolution imaging with advanced video capabilities. It houses a 45-megapixel sensor, 8K video recording, and impressive autofocus performance, appealing to both photography and filmmaking professionals."
 },
 {
 "name": "Nikon Z7 II",
 "brand": "Nikon",
 "price": "Approximately $2,800",
 "summary": "The Nikon Z7 II offers a 45.7-megapixel full-frame sensor and is praised for its high resolution and excellent dynamic range. It also supports 4K video recording and features a versatile Z-mount lens system, making it a strong contender in the full-frame market."
 },
 {
 "name": "Fujifilm GFX 100S",
 "brand": "Fujifilm",
 "price": "Approximately $7,000",
 "summary": "While not a traditional full-frame camera, the Fujifilm GFX 100S stands out with its 102-megapixel medium format sensor. It is lauded for its stunning detail and color reproduction, though it comes at a higher price point and is aimed at specialized users."
 }
 ]
 ```
```

------
#### [ Specific Prompt ]

Usuario:

```
Provide details about the best selling full-frame cameras in past three years.
You MUST answer in JSON format only. Write your response following the the format below:
[{
“name”: “name goes here”,
“brand”: “brand goes here”,
“price”: “price goes here“,
"summary": "summary goes here"
}]
```

Asistente:

```
[
 {
 "name": "Nikon D850",
 "brand": "Nikon",
 "price": "$3,296.95",
 "summary": "The Nikon D850 is a professional full-frame DSLR camera known for its exceptional image quality, 45.7-megapixel resolution, 7 fps continuous shooting, and 4K video capabilities."
 },
 {
 "name": "Canon EOS 5D Mark IV",
 "brand": "Canon",
 "price": "$3,499.00",
 "summary": "The Canon EOS 5D Mark IV is a popular full-frame DSLR appreciated for its 30.4-megapixel sensor, 4K video recording, robust build quality, and reliable autofocus system."
 },
 {
 "name": "Sony A7R III",
 "brand": "Sony",
 "price": "$3,198.00",
 "summary": "The Sony A7R III is a high-resolution full-frame mirrorless camera renowned for its 42.4-megapixel sensor, excellent low-light performance, and versatile lens compatibility."
 },
 {
 "name": "Fujifilm GFX 100S",
 "brand": "Fujifilm",
 "price": "$5,999.99",
 "summary": "The Fujifilm GFX 100S is a medium format mirrorless camera that stands out for its 102-megapixel sensor, high dynamic range, and exceptional color reproduction."
 },
 {
 "name": "Sony A7 III",
 "brand": "Sony",
 "price": "$1,998.00",
 "summary": "The Sony A7 III is a full-frame mirrorless camera popular among enthusiasts and professionals for its 24.2-megapixel sensor, fast autofocus, and 4K video capabilities."
 }
 ]
```

------

#### Ejemplo 2: Cómo prellenar la respuesta del modelo
<a name="prefill-model-response-example"></a>

Otro enfoque consiste en prellenar la respuesta del modelo incluyendo el texto inicial deseado en el mensaje del asistente. En este caso, la respuesta del modelo de Amazon Nova continuará desde donde termina el mensaje del asistente.

**Consejo:** el relleno previo solo es válido cuando el razonamiento no está activado.

Usuario:

```
Provide details about the best selling full-frame cameras in past three years.
Your response should be in JSON format, with the following keys: name, brand, year, price, summary.
```

Asistente (relleno previo):

```
```json
```

Asistente:

```
{
 "cameras": [
 {
 "name": "Sony Alpha A7 III",
 "brand": "Sony",
 "year": 2018,
 "price": "$1999",
 "summary": "The Sony Alpha A7 III is a highly acclaimed full-frame mirrorless camera known for its excellent image quality, advanced autofocus system, and 4K video capabilities."
 },
 {
 "name": "Canon EOS R5",
 "brand": "Canon",
 "year": 2020,
 "price": "$3899",
 "summary": "The Canon EOS R5 is a top-tier full-frame mirrorless camera that offers stunning 45MP images, 8K video recording, and exceptional performance in various lighting conditions."
 },
 {
 "name": "Nikon Z7 II",
 "brand": "Nikon",
 "year": 2020,
 "price": "$2999",
 "summary": "The Nikon Z7 II is a flagship full-frame mirrorless camera with a 45.7MP sensor, superb image quality, and advanced video recording features."
 },
 {
 "name": "Fujifilm GFX 100S",
 "brand": "Fujifilm",
 "year": 2020,
 "price": "$7999",
 "summary": "The Fujifilm GFX 100S is a medium format mirrorless camera known for its impressive 102MP sensor, beautiful film simulations, and versatile lens options."
 },
 {
 "name": "Sony Alpha A7R IV",
 "brand": "Sony",
 "year": 2019,
 "price": "$3499",
 "summary": "The Sony Alpha A7R IV features a 61MP sensor, excellent low-light performance, and advanced video capabilities, making it a favorite among professional photographers."
 }
 ]
 }
 ```
```

#### Ejemplo 3: Cómo especificar una herramienta para usar
<a name="specify-tool-use-example"></a>

Como alternativa al uso de la técnica de relleno previo para obtener una salida estructurada, puede combinar la funcionalidad de las herramientas de Nova con toolChoice. En este ejemplo, el modelo generará una llamada a la herramienta que se adhiera al esquema JSON proporcionado y que llame a la herramienta específica indicada en el formato JSON completo definido. Para obtener orientación adicional, consulte Sistemas avanzados.

Usuario:

```
From the below provided Query, extract the relevent entities

Query:
John works in BUILDING-0987 and have been incharge of product id 23564#. His performance have been excellent in past year and is up for a raise.

Use the extract_ner tool.
```

ToolConfig:

```
{
        "tools": [
            {
            "toolSpec": {
                "name": "extract_ner",
                "description": "Extract all the named entities. based on provided input",
                "inputSchema": {
                    "json": {
                        "type": "object",
                        "properties": {
                            "entities": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                "name": {
                                    "type": "string",
                                    "description": "The extracted entity name. This should be a name of a person, place, animal or thing"
                                },
                                "location": {
                                    "type": "string",
                                    "description": "The extracted location name. This is a site name or a building name like SITE-001 or BUILDING-003"
                                },
                                "product": {
                                    "type": "string",
                                    "description": "The extrcted product code, this is generally a 6 digit alphanumeric code such as 45623#, 234567"
                                }
                                },
                                "required": [
                                "name",
                                "location",
                                "product"
                                ]
                            }
                            }
                        },
                        "required": [
                            "entities"
                        ]
                    }
                    
                }
            }
        }],
        "toolChoice": {
            "tool": {
                "name": "extract_ner"
            }
        }
    }
```

## Casos de uso multilingües
<a name="prompting-multilingual"></a>

Los modelos de Amazon Nova 2 se han entrenado en más de 200 idiomas y se han optimizado para 15 idiomas.

**Topics**
+ [

### Peticiones de traducción precisas
](#accurate-translations)
+ [

### Aplicación de convenciones de redacción coherentes
](#consistent-writing-conventions)

### Peticiones de traducción precisas
<a name="accurate-translations"></a>

Para aprovechar esta capacidad para traducciones de formato corto (unas pocas frases), puede pedir al modelo que traduzca el texto al idioma de destino especificado.

**Example Peticiones de traducción**  

```
Translate the following text into {target language}. Please output only the translated text with no prefix or introduction: {text}
```

```
Translate the following sentence from {source_language} to {target language}: {text}
```

```
{text} How do you say this sentence in {target_language}
```

### Aplicación de convenciones de redacción coherentes
<a name="consistent-writing-conventions"></a>

En los lenguajes basados en caracteres, los modelos de Amazon Nova 2 pueden utilizar el conjunto de caracteres del idioma de origen. Puede utilizar la siguiente petición para aplicar una salida coherente.

**Example Aplicación de convenciones de redacción**  

```
When translating, ensure to use the correct orthography / script / writing convention of the target language, not the source language's characters
```

## Llamada a herramientas
<a name="tool-calling-advanced-techniques"></a>

### Sistemas agénticos
<a name="agentic-systems"></a>

**Topics**
+ [

#### Establecimiento de los parámetros de inferencia correctos
](#set-inference-parameters)
+ [

#### Consideración de los requisitos de latencia
](#consider-latency-requirements)
+ [

#### Uso de un lenguaje intencionado para las instrucciones de llamada a herramientas
](#intentional-wording-tool-calling)
+ [

#### Aprovechamiento de los comandos de “pensamiento”
](#leverage-thinking-commands)
+ [

#### Orden de las llamadas a herramientas
](#tool-call-ordering)
+ [

#### Creación de esquemas de herramientas de calidad
](#designing-tool-schema)
+ [

#### Creación de subagentes
](#create-sub-agents)
+ [

#### Uso de herramientas para entradas multimodales
](#use-tools-multimodal-inputs)
+ [

#### Siguientes pasos
](#next-steps-best-practices)

#### Establecimiento de los parámetros de inferencia correctos
<a name="set-inference-parameters"></a>

La llamada a herramientas requiere una salida estructurada muy específica del modelo y se mejora mediante el uso de los siguientes parámetros de inferencia:
+ **Modo sin razonamiento.** Temperatura: 0,7 y Top P: 0,9
+ **Modo de razonamiento.** Temperatura: 1 y Top P: 0,9

#### Consideración de los requisitos de latencia
<a name="consider-latency-requirements"></a>

**sugerencia**  
Los modelos de Amazon Nova 2 pueden llamar a herramientas con el razonamiento activado y desactivado. Sin embargo, los modos de razonamiento tienen un impacto significativo en la latencia.

En el caso de aplicaciones sensibles a la latencia, se debe optimizar el modo de razonamiento desactivado y, en la medida de lo posible, simplificar las llamadas a herramientas necesarias. Divida los flujos de trabajo de varios pasos en pasos discretos para reducir la dependencia del modelo de regurgitar parámetros innecesarios.

#### Uso de un lenguaje intencionado para las instrucciones de llamada a herramientas
<a name="intentional-wording-tool-calling"></a>

**Nombres de herramientas:** hacer referencia a las herramientas en la petición del sistema es habitual en los sistemas de llamadas a herramientas para indicar al modelo cuándo llamar a una herramienta. Cuando haga referencia a herramientas en la petición, le recomendamos que utilice el nombre de la herramienta en lugar de referencias o ejemplos en formato xml o Python.

##### Ejemplo de una buena referencia a una herramienta
<a name="Example-of-a-good-tool-reference"></a>

```
Use the 'run_shell_command' tool for running shell commands
```

##### Ejemplo de una mala referencia a una herramienta
<a name="Example-of-a-bad-tool-reference"></a>

```
Call run_shell_command() to run shell commands
```

#### Aprovechamiento de los comandos de “pensamiento”
<a name="leverage-thinking-commands"></a>

Para todos los casos de uso en los que pensar sea beneficioso para la llamada a herramientas, te recomendamos que aproveche el modo de razonamiento en lugar de hacer peticiones al modelo para que “piense en etiquetas” o que utilice una herramienta de “pensamiento”.

 Los modelos de Amazon Nova 2 están entrenados ampliamente para el modo de razonamiento y producirán los resultados óptimos cuando se utilicen en el modo de razonamiento para la cadena de pensamiento. 

#### Orden de las llamadas a herramientas
<a name="tool-call-ordering"></a>

En los casos de uso que puedan requerir el uso simultáneo de llamadas a herramientas integradas y nativas, el modelo se inclina por llamar primero a las herramientas integradas.

No indique al modelo que actúe de forma diferente en la petición. En su lugar, téngalo en cuenta al diseñar el flujo de trabajo.

Por ejemplo, si no desea que el modelo utilice herramientas integradas, no las incluya en el flujo de trabajo para que el modelo no se incline por ellas.

#### Creación de esquemas de herramientas de calidad
<a name="designing-tool-schema"></a>

Los esquemas de herramientas son uno de los lugares clave en los que puede usar la ingeniería de peticiones para sistemas de llamada a herramientas de forma eficaz. Sin embargo, es importante tener en cuenta lo que se captura en el propio esquema de la herramienta, cómo se describe semánticamente cada elemento del esquema y cómo la petición del sistema hace referencia a las herramientas y los elementos del esquema en las instrucciones del sistema.

Los modelos de Amazon Nova 2 están optimizados para ofrecer descripciones concisas en los esquemas de la herramienta. Sea breve.

**Directrices de esquema de la herramienta frente a petición del sistema:**

**Incluya lo siguiente en el esquema de la herramienta:**
+ Funcionalidad básica: qué hace la herramienta (se recomiendan entre 20 y 50 palabras)
+ Especificaciones de los parámetros: descripciones claras de cada parámetro (alrededor de 10 palabras por parámetro)
+ Formatos esperados: tipos de datos (como enum, int, float), campos obligatorios y rangos de valores válidos

**Incluya lo siguiente en la petición del sistema:**
+ Dedique una sección `#Tool Usage` a la lógica de orquestación (cuándo y por qué se deben utilizar herramientas específicas) y a las reglas empresariales (lógica condicional, requisitos de secuenciación y dependencias).
+ **Estrategias de gestión de errores:** agregue una sección `#Error Handling and Troubleshooting` con instrucciones sobre cómo responder a fallos o a salidas inesperadas
+ **Formato de salida:** agregue detalles sobre cómo se presenta al usuario

##### Ejemplo
<a name="sample-example"></a>

```
You are a software engineering issue root cause analysis agent. You are tasked with reviewing a customer issue and examining the repository to identify a plan to resolve the issue.
      # Core Mandates
- **DO NOT** update the original issue that was posted by the user. You only add *additional* comments to the reported issue if necessary

# Primary Workflows
1. **Understand:** Analyze the user's request and explore the codebase thoroughly using **get_file_contents** to grasp file structures and conventions.
2. **Plan:** Create a coherent, evidence-based plan for resolving the task and share it with the user following the format below

# Tool Usage 
- **Read the Issue:** Always start by using the **read_issue** tool to get the details about the requested issue
- **File Paths:** Always end the file path with "/" if you are searching a directory using the **get_file_contents** tools
- **Parallelism:** Execute multiple independent tool calls in parallel when feasible

# Error Handling and Troubleshooting
- **File Exploration:** If you get an error that a file doesn't exist, try searching at the directory level first to validate the file path

# Output Formatting
Return your plan in markdown in the following format

## Issue
<Your root cause analysis of the issue>

## Resolution Plan
<your step by step plan of how to solve the issue>
```

#### Creación de subagentes
<a name="create-sub-agents"></a>

Considere la posibilidad de crear subagentes especializados en lugar de un solo agente con muchas herramientas cuando se encuentre con lo siguiente:
+ **El número de herramientas supera las 20:** los conjuntos de herramientas grandes se vuelven difíciles de administrar y aumentan los errores de selección
+ **Dominios funcionales distintos:** las herramientas se agrupan de forma natural en categorías separadas (por ejemplo, la recuperación de datos, el procesamiento o la elaboración de informes)
+ **Esquemas complejos:** cuando la profundidad de los parámetros supera los 3 o 4 niveles o las herramientas tienen interdependencias complejas
+ **Duración de la conversación:** los flujos de trabajo que suelen superar los 15 o 20 turnos pueden beneficiarse de la ayuda de subagentes especializados
+ **Degradación del rendimiento:** si observa una disminución de la precisión en la selección de herramientas o un aumento de la latencia

**sugerencia**  
Los servidores MCP vienen con herramientas y esquemas que no puede controlar. Incluya solo las herramientas necesarias para que su flujo de trabajo complete la tarea requerida.

#### Uso de herramientas para entradas multimodales
<a name="use-tools-multimodal-inputs"></a>

En el caso de las tareas multimodales, no hemos observado ninguna mejora en la precisión al aprovechar las herramientas para tareas estructuradas (como la extracción o la generación de marcas de tiempo).

En su lugar, le recomendamos que consulte las secciones pertinentes de la sección Peticiones de entradas multimodales para obtener información sobre cómo activar correctamente el modelo con las plantillas proporcionadas.

#### Siguientes pasos
<a name="next-steps-best-practices"></a>
+ Para las peticiones multimodales, consulte [Peticiones de entradas multimodales](prompting-multimodal.md).