

# 一般最佳实践
<a name="prompting-best-practices"></a>

以下最佳实践主要适用于 Amazon Nova 文本模型，在遵循各模态专属最佳实践的基础上，也适用于其他模型。

有关如何提示多模态输入的更多信息，请参阅[多模态输入提示](prompting-multimodal.md)。有关如何提示语音输入的更多信息，请参阅[语音对话提示](sonic-system-prompts.md)。

## 了解角色
<a name="understanding-roles"></a>

Amazon Nova 模型允许您使用三个不同的角色来构造提示：系统、用户和助手。
+ **系统（选填）**：虽非必填，但可用于设定助手的整体行为规则。它还可以用来提供用户希望模型在整个对话中遵守的额外说明和指南。
+ **用户**：可根据需要附带上下文、任务、指令、预期输出及用户查询。
+ **助手**：有助于引导模型朝着预期的响应前进。

**Topics**
+ [了解角色](#understanding-roles)
+ [创建精准提示](create-precise-prompts.md)
+ [聚焦提示的各个部分](prompting-bring-focus.md)
+ [使用系统角色](prompting-system-role.md)
+ [提供示例（少样本提示）](prompting-provide-examples.md)
+ [工具调用系统](prompting-tools-function.md)
+ [进阶提示技巧](advanced-prompting-techniques.md)

# 创建精准提示
<a name="create-precise-prompts"></a>

在提示工程中，创建具体的用户查询至关重要。精心设计的查询可引导 Amazon Nova 文本理解模型生成准确的相关回复。要设计此类查询，必须先在查询中提供上下文信息。所提供的上下文通过与清晰的目标用户情景保持一致，更好地定位模型，从而提升输出的相干性与一致性。

## 提供具体的上下文信息
<a name="prompting-specific-info"></a>

若指令清晰、结构合理、简短且具体，模型将发挥最佳性能。此提示模板指导适用于用户提示和系统提示。

**提示模板**

```
# 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}"""
```

### 示例：具体的上下文信息
<a name="specific-collapsible"></a>

以下是结合具体上下文信息重写的部分提示示例。添加更多上下文信息可帮助模型尽力实现预期行为。

------
#### [ 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]
```

------
+ 清晰性原则：向模型提供提示时，需以人类可理解的方式（而非机器逻辑，如 JSON 样式的列表）进行表述，使指令尽可能清晰。
+ 具体性原则：为模型提供具体说明，明确任务内容、预期输出以及任何其他上下文信息，以便引导模型生成符合预期的回复。

## 指定输出格式和样式
<a name="prompting-style"></a>

如果希望 Amazon Nova 2 生成贴合具体需求的响应，可以指定输出的格式和样式。例如，只希望生成 JSON 样式的回复，或者限制回复长度（如最大词数、项目符号数、段落数）。此方式可帮助 Amazon Nova 2 更精准地理解需求，生成易于解析的相关输出。

通过加粗和强烈措辞（如“务必”“切勿”“必须”）来强调希望模型严格遵守的规则。例如，若希望回复仅包含一个 JSON 对象，可对模型下达如下指令。“必须仅以 JSON 格式回答，切勿使用其他格式。”

以下是结合具体上下文信息重写的部分提示示例。添加更多上下文信息可帮助模型尽力实现预期行为。

### 示例 1：补充额外细节
<a name="style-collapsible1"></a>

补充有关回复格式的额外细节可帮助模型达成预期结果。其他一些常用的回复格式包括 CSV、Markdown、YAML 和 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
 ```
```

------

### 示例 2：设定样式限制
<a name="style-collapsible2"></a>

在此实例中，带样式限制的提示提供了有关要遵循的限制条件及所需回复格式的全面信息。正如回复所示，优化后的提示更符合所要求的简洁性与项目符号列表结构。

------
#### [ 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.
```

------

### 示例 3：限制回复格式
<a name="style-collapsible3"></a>

在此示例中，带回复格式限制的提示会强制命令模型仅回复 1-10 之间的类别编号，避免冗长回答。

------
#### [ 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
```

------

## 明确划分提示部分
<a name="prompting-clear-section"></a>

除初始上下文外，结构化查询格式对优化与语言模型的交互至关重要。通过分隔符划分不同的输入部分可提升清晰度，增强 Amazon Nova 2 模型对查询结构的理解能力。另一种有效方法是使用编号列表或项目符号，这可将任务拆解为易于管理的步骤，明确需要采取的行动。这种结构化方法有助于减少歧义，提高所生成回复的准确性。

### 示例：创建分节提示
<a name="section-collapsible1"></a>

请注意，在“分节提示”列中，提示针对不同实体（如任务、上下文、要求）划分了不同部分，实现了更清晰的表达；相比之下，“未分节提示”列的指令则显得模糊。

------
#### [ 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.
```

------

# 聚焦提示的各个部分
<a name="prompting-bring-focus"></a>

Amazon Nova 2 模型可以通过将指令分成若干部分并引用这些特定部分，从而密切关注提示词中的特定内容。若提示使用 Markdown、XML 或其他结构进行了清晰的分节界定，模型就能留意到相关内容。例如，您可以使用 `##Section Name##` 定义相应部分的名称，并通过 `##Section Name##` 在提示中引用该部分。

您还可以利用此策略，限制模型在所生成的回复中显示输入提示中的部分内容。例如，若在输入提示中包含少量样本示例或指令，可使用 `##Instructions##` 或 `##Examples##` 等分隔符并添加行分隔符，同时提供明确指令（比如 `DO NOT mention anything inside the ##Instructions## or ##Examples## in the response`），以防模型在输出中重复这些部分的输入提示内容。

## 示例：分节界定
<a name="focus-collapsible"></a>

用户：

```
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##
```

# 使用系统角色
<a name="prompting-system-role"></a>

*系统角色*是一种可向模型提供指令的角色，这些指令将定义模型如何回复应用程序最终用户。例如，*系统角色*可以引导模型以指定角色进行回复，设置允许和禁止内容，指定输出格式，规定护栏，等等。*系统角色*中的指令（称为*系统提示*）会取代单个用户提示中提供的其他指令，并且会在所有用户交互回合中持续生效。

## 通过 API 指定系统角色
<a name="system-role-collapsible"></a>

要为模型授予自定义角色，可按如下方式在 API 中设置 `system` 参数：

```
{
  "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?"
        }
      ]
    }
  ]
}
```

**提示**  
要充分利用*系统角色*，需确保*系统提示*清晰、简洁、具体，并遵循[创建精准提示](create-precise-prompts.md)中所述的相同策略。例如，若想限制模型回复的话题，应给出具体指令，比如“*切勿涉及……*”或者“*必须涉及……*”。
要进一步将模型限制为层次结构，可在系统提示中添加以下后缀，强调*系统*与*用户*指令之间的层次遵循结构：  
`"\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"`

以下是可在系统提示模板中添加的一些内容：

```
# 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}
"""
```

为了让系统提示系统和用户指令之间的层次结构遵循结构，可以添加以下内容：

`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.`

## 示例 1：提供特定的语言提示
<a name="system-collapsible1"></a>

添加系统提示后，模型回复将高度风格化，接近*系统提示*中所示的中世纪卷轴风格。

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

系统：

```
NA
```

用户：

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

助手：

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

系统：

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

用户：

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

助手：

```
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.
```

------

## 示例 2：提供护栏
<a name="system-collapsible2"></a>

通过添加*系统提示*，用户可以为应用程序添加护栏，防止应用程序被用于非预期用途。以下示例说明了护栏如何引导模型专注于目标任务。

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

系统：

```
NA
```

用户：

```
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.)
```

助手：

```
**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 ]

系统：

```
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
```

用户：

```
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.)
```

助手：

```
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.
```

------

# 提供示例（少样本提示）
<a name="prompting-provide-examples"></a>

通过在提示中加入一些任务示例，您可以构建一个结构化模板供 Amazon Nova 2 遵循。这减少了模糊性，提高了输出的准确性和质量。提供清晰的示例，使模型的回复与所需结果更加一致的技巧称为*少样本提示*。

少样本提示的概念是为语言模型提供一些任务示例以及输入和输出格式，然后要求它根据提供的示例为新的输入生成输出结果。这种方法还有助于澄清复杂的指令或任务，使 Amazon Nova 2 更容易理解和解释提出的问题。

**在提示中添加示例有何帮助：**

添加示例有助于模型生成 
+ 与示例风格一致的回复 
+ 由于减少了误解指令的几率并最大限度地减少了幻觉，从而提高了回复性能

使用少样本提示提高模型性能的程度将取决于所选示例的质量和多样性。以下项目演示了提示中良好样本的特征：
+ **选择不同的示例**：所选示例应代表预期输入/输出在多样性（从常见应用场景到边缘情况）方面的分布情况，以充分涵盖相关应用场景。请务必避免示例中的任何偏差，因为输入中的偏差也会导致输出偏差。
+ **匹配复杂性级别**：所提供示例的复杂性应与目标任务或场景保持一致。重要的是要确保在提示中预期的输入和选定的示例之间映射复杂性级别。
+ **确保相关性**：所选示例应与手头的问题或目标直接相关。这确保了回复的一致性和均匀性。

**提示**  
如果上述建议不起作用，建议您构建一个基于 RAG 的系统，根据用户输入查询和可用样本池之间的相似之处，通过动态选择样本来增强提示。

## 示例 1：在用户提示中提供示例
<a name="example-collapsible1"></a>

在这里，您的用户正在尝试将传入的客户支持工单分类为预定义类别。您可以为 Amazon Nova 2 模型提供一些正确分类的工单示例，以提高其对工单中使用的类别和语言的理解。样本示例应简明扼要，并代表应用程序中针对的所有任务。如果有对任务有意义的特定字段名称（例如本示例中的 `Ticket` 或 `Category`），则您的用户可以直接使用这些字段，后跟冒号 `":"`。

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

用户：

```
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."
```

助手：

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

用户：

```
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."
```

助手：

```
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.
```

------

## 示例 2：提供示例作为回合提示
<a name="example-collapsible2"></a>

在此示例中，样本以回合形式提供，每个样本一回合，其中 `User` 角色包含输入，`Assistant` 角色包含该样本的预期输出。

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

系统：

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

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

用户：

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

助手：

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

系统：

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

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

用户：

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

助手：

```
Food
```

用户：

```
I enjoy watching movies.
```

助手：

```
Entertainment
```

用户：

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

助手：

```
Health
```

用户：

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

助手：

```
Wealth
```

------

## 示例 3：在系统提示中提供示例
<a name="example-collapsible3"></a>

在此示例中，您可以指定“示例”部分，然后在系统提示中列出一系列示例。如果您的样本长且复杂，则这种在提示中提供样本的方式特别有用，并且可以帮助模型找到示例样本。

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

系统：

```
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.
```

用户：

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

助手：

```
# 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 ]

系统：

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

用户：

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

助手：

```
<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.
```

------

# 工具调用系统
<a name="prompting-tools-function"></a>

通过在请求中传递工具配置架构，即可在 Amazon Nova 模型上进行工具调用。模型提示可通过此工具配置得到增强，因此这也是开始优化工具调用系统的极具影响力的一步。

考虑以下关键原则：
+ 工具定义应该清晰简洁。定义应易于理解，意图必须非常明显。
+ 使用关键区分因素和边界条件来定义何时应使用某一个工具而不是其他工具。
+ 输入参数类型很重要。需思考：它们有意义吗？通常会以这种方式使用它们吗？

**使用“工具选择”来控制何时调用工具**

“工具选择”参数允许您自定义模型调用工具的行为。我们建议使用此参数来精细控制调用哪些工具以及何时调用。

例如，对于结构化输出等应用场景，您可能需要在每次调用 Amazon Nova 时系统调用特定的工具。您可以将输出架构定义为工具，然后将“工具选择”设置为该工具的名称。

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

对于许多座席应用场景，您可能需要确保模型始终选择其中一个可用工具。为此，您可以将“工具选择”设置为 `any`，这样每次调用模型时，系统只会调用一个工具。

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

最后，如果在应用场景中是否调用工具很大程度上取决于对话上下文，您可以将“工具选择”设置为 `auto`。这是默认行为，并且“工具选择”完全由模型决定。

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

# 进阶提示技巧
<a name="advanced-prompting-techniques"></a>

以下章节提供了进阶指导，帮助您了解如何提高提示质量以及利用扩展思考等关键功能。

## 使用推理模式
<a name="use-reasoning-mode"></a>

Amazon Nova 2 模型提供了一个可选的推理模式，该模式允许模型在响应之前系统地处理问题，从而增强模型解决复杂问题的能力。利用模型的推理模式是提高提示词准确性的有效方法。

**何时使用：**建议在复杂任务中使用推理模式，例如以下使用案例：
+ **多步推理：**数学证明、算法设计、系统架构
+ **信息交叉引用：**文档分析、选项比较、权衡评估
+ **易错计算：**金融建模、数据分析、复杂调试
+ **约束规划：**资源优化、依赖管理、风险评估
+ **复杂分类：**多标签分类、层次化分类体系、细微决策边界
+ **工具调用场景：**多步 API 工作流、数据库查询优化、协调系统集成

**注意**  
有关推理模式的更多信息，请参阅[使用推理](using-converse-api.md#converse-api-reasoning)。

## 采用自上而下的方法
<a name="top-down-approach"></a>

当模型需要评测多种解题方法时，可指示其采用**自上而下**的方法。
+ Amazon Nova 2 模型若先从整体框架入手，再将其拆解为更细致的子问题或执行步骤，效果会更佳。
+ 明确明确引导模型先确定核心目标，再将其分解为可处理的模块，最后逐一细化各部分内容。
+ 这种结构化方法有助于模型梳理思路，形成更连贯的推理链。

**示例：**

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

## 引导思维链
<a name="steer-chain-of-thought"></a>

虽然推理模式通过系统化解题提升了准确性，但在部分特定场景中，在非推理模式下采用思维链（CoT）提示会更贴合需求。

**何时使用：**
+ **透明度与可审计性：**如需查看、验证或审计模型的推理过程，CoT 可完整呈现每一步细节。这对受监管行业、高风险决策场景或需要记录答案逻辑的场景尤为关键。
+ **自定义推理结构：**通过 CoT 设定特定的推理模式与方法论。您可引导模型遵循组织内部决策框架、采用领域专属解题思路，或按指定顺序考量相关因素。
+ **提示词开发与调试：**在提示工程阶段，CoT 可帮助您理解模型的解题逻辑，定位推理失效点，并更高效地迭代优化提示词。
+ **混合方案：**可在开发阶段使用 CoT 完善提示词，待确认模型在特定使用案例下的表现符合预期后，再切换至推理模式进行生产部署。

**注意**  
并非所有任务都需要使用 CoT。对于较简单的任务，可直接使用模型自身的推理逻辑。

**引导模型的 CoT 方向：**

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

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

## 利用长上下文窗口
<a name="utilizing-long-context"></a>

Amazon Nova 2 模型支持 100 万个词元的上下文长度，并且在代码理解和长文档问答方面表现出色。随着上下文长度增加，模型性能（包括对系统提示的遵从度与工具使用能力）可能略有下降。

**使用方法：**
+ **将长格式数据放在开头**：将长文档和输入放在提示的开头附近。将它们放在查询、指令和示例之前。
+ **将指令放在末尾**：将指令放在提示的末尾。当首先提供上下文并在末尾提供指令时，模型表现最佳。
+ **构建文档内容开始和结束标记**：使用开始和结束标记（例如 `DOCUMENT {idx} START` 和 `DOCUMENT {idx} END`）来标识长文档的开始和结束，其中 \$1idx\$1 代表特定文档的索引。

**示例模板：**

```
// 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
```

## 基于参考文本生成有据回答
<a name="ground-answers-supporting-text"></a>

建议向模型提供与当前查询相关的可信信息。通常，此类信息与输入查询共同构成检索增强生成（RAG）系统的一部分。
+ 在此过程中，相关的上下文文档或信息将添加到实际用户提示中，使模型基于可信内容生成相关且精准的回复。
+ 通过指令要求 Amazon Nova 2 使用来自可信来源的参考文本进行回答，可以引导其根据所提供的材料撰写回复，并确保回复以准确的相关信息为依据，从而提升所生成内容的可靠性与可信度。
+ 使用参考文本可有效规避幻觉，从而提升回复的整体质量与可信度。为最大限度减少幻觉，建议在模型指令中明确注明：`DO NOT USE INFORMATION THAT IS NOT IN REFERENCE TEXTS!`。

提示模板

```
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}
```

### 示例：提供依据上下文避免模型产生幻觉
<a name="grounding-example"></a>

此示例说明了依据上下文如何避免模型产生幻觉。

系统：

```
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!
```

用户：

```
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.
```

### 基于引文标记生成有据回答
<a name="grounding-citations"></a>

针对长篇文档任务，建议先指示 Amazon Nova 2 模型依据文档对应章节引文生成回复，再执行后续任务。

这种方法有助于模型关注最相关的信息，避免被无关内容分散注意力。要求模型基于依据生成回复时，可引用的章节应预先进行编号。例如：`Passage %[1]%`、`Passage %[2]%`，依此类推。

#### 示例：使用引文标记
<a name="citations-example"></a>

**Example 引文标记提示**  

```
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)
...
```

在基于用户任务提取关键信息后，您可以使用提取的财务指标来回答相关问题，如下所示：

**Example 使用提取的指标进行后续分析**  

```
## 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
```

### 使用 Nova Web Grounding
<a name="prompting-web-grounding"></a>

Amazon Nova 2 模型无需通过提示词直接要求引文作为依据文本，而是内置了 Web Grounding 工具。启用后，Amazon Nova 2 模型将直接查询 Web 和 Amazon 的知识图谱，并在最终响应中附带引文依据。

要详细了解如何利用 Amazon Nova Web Grounding，请参阅《[Amazon Nova Web Grounding 用户指南](https://docs.aws.amazon.com/nova/latest/nova2-userguide/web-grounding.html)》。

## 生成结构化输出
<a name="prompting-structured-output"></a>

为确保输出格式的一致性和结构化，您可以使用结构化输出，包括 XML、JSON、Markdown 等格式，或使用工具使用功能。
+ 这种方法可使下游系统更有效地理解和解析模型生成的输出。
+ 向模型提供明确指令，生成的回复将以符合预定义架构的方式呈现。

例如，若下游解析器希望 JSON 对象的键名遵循特定命名约定，您应该在提示末尾指定响应架构。此外，如果希望回复以 JSON 格式呈现，且不带任何前言文本，则须相应地向模型提供指令。即明确写明：“**请仅输出 JSON 内容，切勿添加任何前置说明**”，保证输出格式纯净。

**提示**  
我们发现，将数据格式要求直接定义在架构本身中，模型的遵守效果最佳，优于通过示例进行指定（例如将日期格式设为 YYYY/MM/DD）。
对于最多包含 10 个键的简单 JSON 输出，可直接使用下方提供的架构。对于更复杂的架构，建议通过工具来定义架构。工具使用采用了一种名为“约束解码”的技术，可提升模型对这类复杂架构的遵从度。

### 常见格式架构
<a name="common-formatting-schemas"></a>

以下是常见格式架构的示例。

------
#### [ 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 )


"""
```

------

### 预填充助手内容
<a name="prompting-prefill"></a>

如果您在非推理模式下生成结构化输出，则可以通过预填充助手内容来引导模型的响应。

预填充可以提高非推理模式下输出格式的一致性。这有助于引导模型的行为，省略前置说明，并强制输出 JSON、XML 等指定格式。例如，若使用 `{` 或 ````json` 预填充助手内容，则该输入可引导模型直接生成不带额外信息的 JSON 对象。

**提示**  
若需明确提取 JSON 内容，常用方式为使用 ````json` 进行预填充，并在 ````` 位置设置停止序列。此操作可确保模型输出能够以编程方式解析的 JSON 对象。

**Example 预填充助手内容**  
以下代码演示了如何使用 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())
```

### 指定用于复杂架构的工具
<a name="prompting-tool-complex-schemas"></a>

另一种方法是在工具使用的架构部分中加入 *pydantic JSON 架构*，强制模型响应遵循指定架构。可为所提供架构指定工具选择，这样 Amazon Nova 就会根据所选工具的架构生成回复。如需了解关于如何使用工具的详情，请参阅[工具使用](https://docs.aws.amazon.com/nova/latest/userguide/tool-use.html)。

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

#### 示例 1：添加输出架构
<a name="add-output-schema-example"></a>

向“输出架构”部分添加恰当的架构可引导模型遵循该架构生成内容。然而，模型输出具有不确定性，可能与输出架构存在差异。

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

用户：

```
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.
```

助手：

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

用户：

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

助手：

```
[
 {
 "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."
 }
 ]
```

------

#### 示例 2：预填充模型回复
<a name="prefill-model-response-example"></a>

第二种方法是在助手消息中包含所需的初始文本，从而预填充模型的回复。在这种情况下，Amazon Nova 模型将从助手消息中断处继续回复。

**提示：**仅当未启用推理功能时，预填充才有效。

用户：

```
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.
```

助手（预填充）：

```
```json
```

助手：

```
{
 "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."
 }
 ]
 }
 ```
```

#### 示例 3：指定使用工具
<a name="specify-tool-use-example"></a>

作为使用预填充技术进行结构化输出的替代方案，您可以将 Nova 的工具功能与 toolChoice 结合使用。在本示例中，模型将生成符合所提供 JSON 架构的工具调用，并按照定义的完整 JSON 格式调用指定工具。有关其他指导，请参阅“高级系统”。

用户：

```
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"
            }
        }
    }
```

## 多语言使用案例
<a name="prompting-multilingual"></a>

Amazon Nova 2 模型已在超过 200 种语言上进行了训练，并为 15 种语言进行了优化。

**Topics**
+ [精准翻译提示词](#accurate-translations)
+ [强制执行一致的书写规范](#consistent-writing-conventions)

### 精准翻译提示词
<a name="accurate-translations"></a>

如需使用该功能进行短文本翻译（若干句子），可直接指示模型将文本译为指定目标语言。

**Example 翻译提示**  

```
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}
```

### 强制执行一致的书写规范
<a name="consistent-writing-conventions"></a>

在基于字符的语言中，Amazon Nova 2 模型可能会使用源语言的字符集。您可采用如下提示来强制执行一致的输出。

**Example 强制执行书写规范**  

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

## 工具调用
<a name="tool-calling-advanced-techniques"></a>

### 代理系统
<a name="agentic-systems"></a>

**Topics**
+ [设置正确的推理参数](#set-inference-parameters)
+ [考虑延迟要求](#consider-latency-requirements)
+ [工具调用指令应措辞精准](#intentional-wording-tool-calling)
+ [使用“思考”指令](#leverage-thinking-commands)
+ [工具调用顺序](#tool-call-ordering)
+ [构建高质量工具架构](#designing-tool-schema)
+ [创建子代理](#create-sub-agents)
+ [多模态输入的工具使用](#use-tools-multimodal-inputs)
+ [后续步骤](#next-steps-best-practices)

#### 设置正确的推理参数
<a name="set-inference-parameters"></a>

工具调用要求模型输出高度特定的结构化内容，通过以下推理参数可提升效果：
+ **非推理模式：**Temperature：0.7；TopP：0.9
+ **推理模式：**Temperature：1；TopP：0.9

#### 考虑延迟要求
<a name="consider-latency-requirements"></a>

**提示**  
Amazon Nova 2 模型在启用或关闭推理的情况下都能进行工具调用。不过，推理模式对延迟有显著影响。

对于延迟敏感的应用程序，建议采用关闭推理模式进行优化，并尽可能简化所需的工具调用。将多步工作流拆分为离散步骤，以减少模型对机械输出不必要参数的依赖。

#### 工具调用指令应措辞精准
<a name="intentional-wording-tool-calling"></a>

**工具名称：**。在工具调用系统中，通常会在系统提示中引用工具，以指示模型何时调用工具。在提示中引用工具时，建议直接使用工具名称，而非采用 XML 或 Python 风格的引用方式或示例。

##### 优质工具引用示例
<a name="Example-of-a-good-tool-reference"></a>

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

##### 劣质工具引用示例
<a name="Example-of-a-bad-tool-reference"></a>

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

#### 使用“思考”指令
<a name="leverage-thinking-commands"></a>

在所有思考有助于工具调用的场景中，建议使用推理模式，而非提示模型“在标签内思考”或使用“思考”类工具。

 Amazon Nova 2 模型针对推理模式进行了大量训练，在推理模式下执行思维链任务可获得最优效果。

#### 工具调用顺序
<a name="tool-call-ordering"></a>

在需要同时使用内置工具与原生工具调用的场景中，模型会优先调用内置工具。

请勿在提示词中指示模型改变行为，而应在工作流设计中对此加以考量。

例如，若不希望模型使用内置工具，只需将其排除在工作流之外，即可避免模型倾向于调用此类工具。

#### 构建高质量工具架构
<a name="designing-tool-schema"></a>

工具架构是通过提示工程实现高效工具调用系统的核心环节之一。设计时需重点关注：架构本身应包含哪些内容、各元素的语义描述方式，以及系统提示在指令中如何引用工具与架构元素。

Amazon Nova 2 模型针对工具架构的简洁描述进行了专项优化。请保持描述简短精炼。

**工具架构与系统提示指南：**

**工具架构应包含以下内容：**
+ 核心功能：工具实现的功能（建议 20 – 50 个字）
+ 参数规范：各参数清晰描述（每个参数约 10 个字）
+ 格式要求：数据类型（如枚举、整数、浮点数）、必填字段及有效值范围

**系统提示应包含以下内容：**
+ 专门设立 `#Tool Usage` 章节，说明编排逻辑（何时及为何使用特定工具）与业务规则（条件逻辑、执行顺序及依赖关系）。
+ **错误处理策略：**添加 `#Error Handling and Troubleshooting` 章节，说明如何应对调用失败或意外输出
+ **输出格式：**详细说明结果的呈现方式

##### 示例
<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>
```

#### 创建子代理
<a name="create-sub-agents"></a>

若出现以下情形，建议搭建专用子代理，而非使用搭载大量工具的单一代理：
+ **工具数量超过 20 个：**工具集过大会增加管理难度，同时提升工具选择错误率
+ **功能领域差异显著：**工具可自然划分为不同类别（如数据检索、数据处理、报表生成）
+ **架构复杂：**参数层级深度超 3 – 4 层，或工具间存在复杂关联依赖
+ **对话轮次过长：**工作流常规超过 15 – 20 轮对话，专用子代理效果更优
+ **性能下降：**工具选择准确率降低、响应延迟升高

**提示**  
MCP 服务器自带部分无法自主管控的工具与架构，仅需纳入工作流执行任务所需的必要工具即可。

#### 多模态输入的工具使用
<a name="use-tools-multimodal-inputs"></a>

在多模态任务中，使用工具处理结构化任务（如信息提取、时间戳生成）并未提升准确率。

建议查阅“多模态输入提示”章节中的相关内容，参考提供的模板编写有效提示词。

#### 后续步骤
<a name="next-steps-best-practices"></a>
+ 有关多模态提示的信息，请参阅[多模态输入提示](prompting-multimodal.md)。