All Products
Search
Document Center

Alibaba Cloud Model Studio:Best practices for prompt engineering

Last Updated:Nov 08, 2024

A prompt is a textual input given to a large language model (LLM) about the problem to be solved or the task to be completed. Prompt is the foundation for the LLM to comprehend user requirements and generate relevant and precise responses. This topic offers practical tips for designing and optimizing prompts to enhance your efficiency with LLMs.

Optimize prompts with Model Studio

Use prompt optimization tool

Alibaba Cloud Model Studio offers a prompt optimization tool that can automatically expand and refine your prompt. We recommend that you use the tool to enhance your prompt before applying the other tips outlined in this guide.

  1. Log on to the Alibaba Cloud Model Studio console.

  2. In the left-side navigation pane, choose Application Component > Prompt Engineering.

  3. On the Prompt Optimization tab, enter your prompt in the Original Prompt field.

  4. Click Optimization. The result is displayed in the Optimized Prompt field.

Note

The prompt optimization feature is based on an LLM. The feature consumes tokens and is billed based on the inference fee of qwen-plus. For more information, see Billing for Qwen.

Optimization example:

Before optimization

After optimization

I want to promote my company's new product. My company's name is Bailian, and the new product is called Zephyr Z9, a lightweight and portable phone. Write a post for me.

Compose a promotional post for Bailian's latest product launch, the Zephyr Z9 - a sleek, lightweight, and highly portable smartphone designed for ultimate convenience.

Ensure the post highlights Zephyr Z9's unique selling points, emphasizing its design, functionality, and how it stands out in the market.

Incorporate a captivating introduction that grabs the audience's interest, followed by detailed features and benefits that resonate with tech-savvy consumers.

Conclude with a clear call-to-action, inviting readers to explore more about Zephyr Z9 and encouraging them to engage with our brand through comments or visiting our website for exclusive launch offers.

You are an experienced PHP programming expert and have received a specific development task. The requirement is: ${require}. Please use the PHP language to describe in detail an algorithm or method to achieve this requirement, considering possible boundary conditions and error handling during implementation, and how to meet this requirement with efficient and secure code.

As an adept PHP programming specialist, you've been assigned a precise development challenge.

The task at hand necessitates addressing the following requirement: ${require}.

Your objective is to meticulously delineate an algorithm or methodology employing the PHP language that accomplishes this goal.

In doing so, ensure to contemplate edge cases, incorporate robust error handling mechanisms, and devise strategies for optimizing code efficiency while maintaining the highest standards of security.

image

Prompt design and optimization

Imagine this scenario: You are assigning a task to your assistant with just a single sentence. The outcome from the assistant might not meet your expectations. However, if you can provide clear objectives, suggested approaches, and strategies, the assistant is more likely to complete the task at high-quality.

The same applies to LLMs, as the quality of your prompt directly influences the effectiveness of LLMs.

Tip 1: Clarify background and goals

To systematically provide LLMs with clear background and goals, consider using a prompt framework to standardize your prompts. The CO-STAR framework facilitates prompt design, significantly enhancing the effectiveness and relevance of LLM response.

image

A prompt consists of the following elements: (If you are not sure how to write a specific element, consider using the prompt optimization tool.)

  • Context: The background information that are related to the task. This helps the LLM understand the specific scenario, ensuring the generated response is relevant.

  • Objective: The specific task you expect the LLM to complete. Clear and precise instructions guide the LLM to focus on the task, enhancing output effectiveness.

  • Style: The desired writing style for the output, which can be the style of a specific celebrity, genre, or type of expert.

  • Tone: The tone for the output, such as formal, humorous, or warm and caring, to match different scenarios and purposes.

  • Audience: The target audience for the output, can be professionals, beginners, or children. The LLM can tailor the language and depth accordingly.

  • Response: The desired format for the output. This ensures that the output can directly serve subsequent applications, such as lists or professional reports.

Without prompt framework

With prompt framework

Prompt

I want to promote my company's new product. My company's name is Bailian, and the new product is called Zephyr Z9, a lightweight and portable phone. Write a post for me. I want the post concise and impactful.

#Background#

I want to advertise my company's new product. My company's name is Bailian, and the product is called Bailian Zephyr Z9, a lightweight and portable phone.

#Purpose#

Create a post for me (limit: 300 words) aimed at making people interested in clicking the link to purchase.

#Style#

Follow the writing style of successful companies for similar product advertisements.

#Tone#

Persuasive

#Audience#

Our company's audience is usually the younger generation. Customize your post to ensure that people who like digital products can quickly notice your post.

#Output#

A post, concise and impactful.

Output

"Introducing Zephyr Z9 by Bailian – The Ultimate Lightweight Companion!

Say hello to effortless connectivity with Zephyr Z9, Bailian's latest marvel in portable technology. Engineered for the modern nomad, this featherlight phone packs a punch without weighing you down.

Key Features:

  • Ultra-portable design: Slip it in your pocket and forget it's there!

  • Powerful performance: Speed that keeps up with your every move.

  • All-day battery: No charge anxiety, just non-stop action.

  • Crystal-clear display: Vivid visuals on the go.

The future of mobile tech is here, and it's in the palm of your hand. Experience freedom redefined with Zephyr Z9. Get ready to breeze through life! image

#BailianInnovates #ZephyrZ9 #LightweightTechRevolution"

image Introducing Bailian Zephyr Z9: Light as Air, Smart as Tomorrow! image

Young tech-savvy gen, meet your new obsession – the Bailian Zephyr Z9! This pocket rocket packs a punch with its featherweight design and powerhouse performance.

imageInnovative Design, Effortless Portability Say goodbye to phone-weight fatigue! Zephyr Z9’s sleek, aerospace-inspired build slips into pockets & lifestyles seamlessly. It's not just a phone; it's a fashion statement.

imageAll-Day Power Play Fuel your digital adventures without the charger anxiety. Our optimized battery guarantees non-stop fun from sunrise to sunset, and beyond.

imageSnap Perfection, Anytime Seize life's brilliance with Zephyr Z9's AI-camera. Stunning landscapes, crisp night shots – your memories deserve nothing less than high-definition.

image Gaming Marvel in Your Hands With a lightning-fast processor, Zephyr Z9 redefines mobile gaming. Seamless graphics for victories that feel as smooth as they look.

image Vibrant Display That Mesmerizes Experience visuals that pop with true-to-life colors on Zephyr Z9’s stunning display. Every pixel dances to life for an immersive digital journey.

image Privacy First, Always Your digital life is yours alone. Advanced biometrics ensure your Zephyr Z9 stays locked to you and only you.

image Exclusive Launch Offer Awaits Ready to elevate your tech game? Be among the pioneers to own the Bailian Zephyr Z9 at a special preorder price. Limited time only!

image Grab Your Zephyr Z9 Now!

Don't just keep up with the future – lead the charge with Bailian Zephyr Z9 in your hands. The ultimate blend of lightness and might is just a click away!

-- Bailian: Redefining Tech, One Zephyr at a Time.

Without the CO-STAR framework, the output from the LLM tends to be overly general, missing key details and specificity for particular audiences. The CO-STAR framework, on the other hand, considers elements that are often ignored, such as style, tone, and audience, leading to a response that is more focused, detailed, and engaging, especially for younger audience.

Tip 2: Provide output examples

By including examples of the desired output in the prompt, the LLM can replicate the required specifications, format, concepts, style, and tone. Additionally, examples promote consistency across various outputs from the LLM, enhancing the stability of its performance.

Without examples

With examples

Prompt

#Background#

You excel at writing recommendation posts with a variety of emojis.

#Purpose#

Write a recommendation post to promote Johnson hair dryer, highlighting its compact size, stylish design, powerful airflow, quick drying capability, and intelligent temperature control that prevents hair damage.

#Audience#

Fashion-conscious young people, particularly young women

#Output#

A post formatted with abundant emojis, concise yet informative

#Background#

You excel at writing recommendation posts with a variety of emojis.

#Purpose#

Write a recommendation post to promote Johnson hair dryer, highlighting its compact size, stylish design, powerful airflow, quick drying capability, and intelligent temperature control that prevents hair damage.

#Audience#

Fashion-conscious young people, particularly young women

#Output#

A post formatted with abundant emojis, concise yet informative

#Tone and style#

  1. I've tried + N amazing products + the people who are suitable This structure makes your recommendations highly persuasive! Example: I've personally tested numerous skin-whitening products and finally discovered a gem! In just two months, my skin became smooth and radiant, and I felt like I was on cloud nine~ This method is perfect for those who like to share their experiences and provide precise recommendations, and also help others avoid bad products!

  2. Encounter a problem + uncover the cause + ultimate solution This structure allows for clear and logical sharing, adding value to the content! Example: Dreaming of silky hair? The big reveal is here! I was missing a crucial step until I found this! This shampoo transformed my hair, bringing out an incredible shine! This method is not only about sharing secrets but also guiding readers towards solving their problems.

  3. Unique insights + in-depth analysis + smart recommendations This structure helps you share your thoughts and warmly recommend products! Example: I believe every girl deserves a passion that enriches life. Journaling has become my little joy, and every entry boosts my happiness! It allows you to speak your mind while subtly endorsing your favorites, a win-win approach!

  4. Personal experience + results showcase This structure brings your emotional expression to life! Example: Remember the mosquito-infested summer nights by the sea, the despair of itchy welts until I found my savior! Now, my skin is smooth, my confidence restored, and my skirts twirl freely! It turns your story into a vivid narrative, sharing joy and gratitude, and resonating with others!

Output

imageDry Your Locks in Style with the Johnson Hair Dryerimage

imageHey fashion-forward ladies! image Your hunt for the perfect blowout buddy ends here. Let me introduce you to the imageJohnson Hair Dryerimage – your new BFF for salon-worthy hair every day!

image Compact & Travel-Ready imageIts sleek, compact design slides into any purse or luggage effortlessly. Perfect for that spontaneous weekend getaway or post-gym touch-ups! image

image Stylish Statement Piece imageWith a chic design that screams high-fashion, this dryer isn't just functional - it's a statement piece for your vanity. It's like having a piece of art that gives you great hair! image

image Power Packed Performance imageSay goodbye to weak airflow! Johnson's motor packs a punch, cutting down drying time so you can get out the door faster, without the fuss. image

image Smart Heat for Healthy Hair image Here's the smart part - intelligent heat control that adjusts to protect your tresses from overheating. Hello, shine! Goodbye, damage! image

Don't settle for less when it comes to your crowning glory. The Johnson Hair Dryer is ready to revolutionize your hair game. Grab yours now and experience the ultimate blend of style and substance! image

#JohnsonHairDryer #StylishBlowouts #HealthyHairGoals

I've tried dozens of hair dryers, seeking the perfect mix of style and function for us fashion-forward gals, and let me tell you... the Johnson Hair Dryer hits all the right notes! Singing in the shower just got a whole new meaning!image

Ever had that frustrating moment when your bulky dryer takes up half your luggage space or your morning routine feels like a workout? I know I have. But then, cue the magic, I uncovered the root of my styling struggle - a lack of the right tool! The Johnson dryer, with its compact size image, solved my storage woe and made packing a breeze.

The real game-changer? Its powerful airflow image combined with a quick-drying wizardry that leaves you wondering how you ever managed without it. Think sleek, salon-style hair in record time, girls!

And here's the genius part: Johnson's intelligent temp control. It's like having a personal stylist who knows just the right warmth needed to dry, not fry! Damage? No way, we're talking hair protection at its finest.image

Personal story time: My mane went from drab to fab in mere weeks of using this wonder device. Split ends? A distant memory. Shinier, healthier hair? Check, check! My locks have never looked (or felt) better, and the compliments keep rolling in.image

So, to all my fellow style mavens craving for a hairdryer upgrade that's chic, compact, and cares for your crowning glory, Johnson Hair Dryer is your ultimate solution. Trust me; it'll revolutionize your beauty regimen, and you'll wonder how you dried without it!image

#CompactChic #HealthyHairRevolution #JohnsonDriesBest

In the preceding comparision, the LLM learns the examples and writes recommendation posts accordingly.

Tip 3: Use delimiters to distinguish content units

When constructing complex prompts, you can use delimiters to distinguish content units. Delimiters help the LLM parse your prompt more accurately. In scenarios of complex tasks, delimiters can notably enhance LLM performance.

For delimiters, use unique and uncommon character combinations in natural language texts, such as ###, ===, or >>>. The effectiveness of these sequences lies in their distinctiveness, which helps the model to accurately identify them as content boundaries rather than typical punctuation or text syntax.

Without delimiters

With delimiters

Prompt

Please briefly summarize the following movie review:

Once high-spirited, Zhang Zhiqiang's middle-aged life veers off course under life's pressures. An impulsive decision relegates him from his family's pride to society's margins. Yet, this marks the beginning of his transformative journey. Buffeted by relentless change, he confronts his reality, takes on a courier's role, and embarks on a fresh start. Navigating the city's byways, he finds camaraderie with fellow couriers. Together, they traverse the vicissitudes of human emotions, rekindling Zhang's lost courage and faith, and charting a new path in his life.

Please briefly summarize the following movie review:

###

Once high-spirited, Zhang Zhiqiang's middle-aged life veers off course under life's pressures. An impulsive decision relegates him from his family's pride to society's margins.

###

Yet, this marks the beginning of his transformative journey. Buffeted by relentless change, he confronts his reality, takes on a courier's role, and embarks on a fresh start.

###

Navigating the city's byways, he finds camaraderie with fellow couriers. Together, they traverse the vicissitudes of human emotions, rekindling Zhang's lost courage and faith, and charting a new path in his life.

###

Output

The movie follows Zhang Zhiqiang, whose vibrant life deteriorates due to the weight of middle-aged pressures. After an impulsive decision estranges him from his family and society, he begins a transformative journey by becoming a courier. Through this new job, he encounters various challenges and forms bonds with other couriers, which reignites his courage and restores his faith. As they navigate through life's ups and downs together, Zhang finds a renewed sense of purpose and charts a fresh direction in his life.

The film review outlines the story of Zhang Zhiqiang, who faces a downturn in his middle age due to life's pressures and an impulsive decision that leads him away from his family and into social marginalization.

However, this low point initiates his transformation as he adapts to the continuous changes, accepts a job as a courier, and begins anew.

Through his work, he forms close bonds with other couriers, experiences the depths and heights of human emotion, which revive his courage and hope, and sets him on a different, rejuvenated life trajectory.

The output with delimiters shows a notable improvement. LLM understands the logical connections between the three paragraphs and accurately recognizes the delimiters, producing three closely related summaries for the segmented content.

Tip 4: Guide LLM to "think"

For tasks that require logical reasoning and contextual understanding, simple prompts may fall short. To help the LLM handle complex problems, you can guide it to generate reasoning process or deconstruct the complex task into manageable steps. This approach enables the LLM to compile substantial reasoning evidence before delivering results.

The following section describes Chain of Thought (CoT), an easy guiding technique that substantially enhances the reasoning capabilities of LLMs in complex scenarios.

Prompt 1:

#Background#
JSON input:
{
  "web-app": {
    "servlet": [   
      {
        "servlet-name": "cofaxEmail",
        "servlet-class": "org.cofax.cds.EmailServlet",
        "init-param": {
          "mailHost": "mail1",
          "mailHostOverride": "mail2"
        }
      },
      {
        "servlet-name": "cofaxTools",
        "servlet-class": "org.cofax.cms.CofaxToolsServlet",
        "init-param": {
          "templatePath": "toolstemplates/",
          "log": 1,
          "logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
          "logMaxSize": ""
        }
      }
    ],
    "servlet-mapping": {
      "cofaxEmail": "/cofaxutil/aemail/*",
      "cofaxTools": "/tools/*"
    },
    "taglib": {
      "taglib-uri": "cofax.tld",
      "taglib-location": "/WEB-INF/tlds/cofax.tld"
    }
  }
}

Prompt 2:

#Objective#
Verify the JSON structure against these requirements:
1. Each servlet must include an init-param.
2. All elements defined in servlet-mapping must correspond to a servlet.
3. The cofaxTools servlet should contain three parameters prefixed with "log," and the value of the "log" parameter should be less than 10.

Without CoT

With CoT

Prompt 3

#Output#

If all requirements are met, output "Meets requirements". Otherwise, output "Does not meet requirements".

#Output#

First, output the evaluation process for each requirement.

Then, if all requirements are met, output "Meets requirements". Otherwise, output "Does not meet requirements".

Output

Does not meet requirements

Evaluation Process

  1. Each servlet must include an init-param.

    • Checking cofaxEmail:

      • init-param is present and contains:

        • mailHost: "mail1"

        • mailHostOverride: "mail2"

    • Checking cofaxTools:

      • init-param is present and contains:

        • templatePath: "toolstemplates/"

        • log: 1

        • logLocation: "/usr/local/tomcat/logs/CofaxTools.log"

        • logMaxSize: ""

    • Conclusion: Both servlets include an init-param.

  2. All elements defined in servlet-mapping must correspond to a servlet.

    • Checking servlet-mapping:

      • cofaxEmail maps to /cofaxutil/aemail/

      • cofaxTools maps to /tools/

    • Checking if these names exist in the servlet list:

      • cofaxEmail is found.

      • cofaxTools is found.

    • Conclusion: All elements in servlet-mapping correspond to a servlet.

  3. The cofaxTools servlet should contain three parameters prefixed with "log," and the value of the "log" parameter should be less than 10.

    • Checking cofaxTools init-param:

      • Parameters with "log" prefix:

        • log: 1

        • logLocation: "/usr/local/tomcat/logs/CofaxTools.log"

        • logMaxSize: ""

      • Value of log parameter: 1 (which is less than 10)

    • Conclusion: The cofaxTools servlet contains three parameters prefixed with "log," and the value of the log parameter is 1, which is less than 10.

Final Output

  • All requirements are met.

Output: Meets requirements

Apart from CoT, Prompt Chaining is another effective technique to guide an LLM to think. Prompt Chaining steers the LLM through a series of dialogues progressing from simple tasks to complex reasoning.

Although prompt chaining is more complex than CoT, it yields better performance and accuracy. This approach suits logically complex tasks that can be deconstructed into fixed patterns.

Prompt chaining example

Math problem:

It's Sunday and Timmy is walking to his grandparents' house. Timmy starts walking at exactly 8:00 AM. He walks at a speed of 50 meters per minute. After 12 minutes, Timmy's father realizes that Timmy forgot his homework and decides to catch up with him on his bicycle. Timmy's father rides at a speed of 200 meters per minute. Once he catches up with Timmy, he decides to take Timmy on the bicycle for the rest of the journey. The distance Timmy travels by bicycle is 5 times the distance he walked. At what time do Timmy and his father arrive at the grandparents' house? (The answer is 8:36.)

Prompt 1 (math problem information):

#Background#
It's Sunday and Timmy is walking to his grandparents' house. Timmy starts walking at exactly 8:00 AM. He walks at a speed of 50 meters per minute.
After 12 minutes, Timmy's father realizes that Timmy forgot his homework and decides to catch up with him on his bicycle. 
Timmy's father rides at a speed of 200 meters per minute. Once he catches up with Timmy, he decides to take Timmy on the bicycle for the rest of the journey. 
The distance Timmy travels by bicycle is 5 times the distance he walked.

Prompt 2 (the first simple question):

#Purpose#
At what time does Timmy's father catch up to Timmy? How far has Timmy walked at that time?

Output 1 (LLM's answer to the first simple question):

To determine the time at which Timmy's father catches up to Timmy and how far Timmy has walked by that time, we can follow these steps:

Step 1: Determine the distance Timmy has walked in 12 minutes
Timmy walks at a speed of 50 meters per minute. In 12 minutes, he covers:

Distance walked by Timmy = 50 meters/minute × 12 minutes = 600 meters

Step 2: Determine the relative speed and the time it takes for Timmy's father to catch up
Timmy's father rides at a speed of 200 meters per minute, while Timmy continues to walk at 50 meters per minute. The relative speed at which Timmy's father is catching up to Timmy is:

Relative speed = 200 meters/minute - 50 meters/minute = 150 meters/minute

Timmy's father needs to cover the 600 meters that Timmy has already walked. The time it takes for Timmy's father to catch up is:

Time to catch up = 600 meters / 150 meters/minute= 4 minutes

Step 3: Determine the total time Timmy has walked by the time his father catches up
Timmy has already walked for 12 minutes before his father starts. After his father starts, it takes 4 more minutes for him to catch up. Therefore, the total time Timmy has walked is:

Total time Timmy has walked = 12 minutes + 4 minutes = 16 minutes

Step 4: Determine the distance Timmy has walked by the time his father catches up
In 16 minutes, Timmy has walked:

Distance walked by Timmy = 50 meters/minute × 16minutes = 800meters

Step 5: Determine the time at which Timmy's father catches up
Timmy started walking at 8:00 AM. After 16 minutes, the time will be:

8:00AM + 16 minutes = 8:16AM

Summary
Timmy's father catches up to Timmy at 8:16 AM.
By the time his father catches up, Timmy has walked 800 meters.

Prompt 3 (the second simple question):

#Purpose#
Calculate Calculate how far Timmy needs to travel by bike to arrive at his grandparents' house.

Output 2 (LLM's answer to the second simple question):

To calculate how far Timmy needs to travel by bike to arrive at his grandparents' house, we need to follow these steps:

Determine the distance Timmy has walked by the time his father catches up:

As previously calculated, Timmy has walked 800 meters by the time his father catches up.
Use the given information that the distance Timmy travels by bicycle is 5 times the distance he walked:

Distance traveled by bicycle = 5 × Distance walked
Distance traveled by bicycle = 5 × 800 meters = 4000 meters
Calculate the total distance to the grandparents' house:

Total distance = Distance walked + Distance traveled by bicycle
Total distance = 800 meters + 4000 meters = 4800 meters
Summary
The distance Timmy needs to travel by bike to arrive at his grandparents' house is 4000 meters.
The total distance to the grandparents' house is 4800 meters.

Prompt 4 (the final solution to the math problem):

#Purpose#
At what time does Timmy arrive at his grandparents' house?

Output 3 (LLM's answer to the final complex question):

To determine the time at which Timmy arrives at his grandparents' house, we need to follow these steps:

Determine the total distance to the grandparents' house:

As previously calculated, the total distance is 4800 meters.
Determine the distance Timmy has already walked and the remaining distance he will travel by bicycle:

Distance walked by Timmy: 800 meters
Distance traveled by bicycle: 4000 meters
Calculate the time taken for each part of the journey:

Time taken to walk 800 meters:

Time walking= 800meters/50 meters/minute =16minutes
Time taken to travel 4000 meters by bicycle:
Time biking= 4000meters/200 meters/minute=20minutes
Calculate the total time taken for the journey:

Total time = Time walking + Time biking
Total time = 16 minutes + 20 minutes = 36 minutes
Determine the arrival time:

Timmy started walking at 8:00 AM.
Adding the total time of 36 minutes to the start time:

8:00AM+36minutes=8:36AM
Summary
Timmy arrives at his grandparents' house at 8:36 AM.

Other methods to guide the thinking of LLMs include Tree of Thoughts (ToT) and Boosting of Thoughts.

We recommend that you actively explore and try various techniques of prompt engineering, and put them in use based on your requirements.