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.
Log on to the Alibaba Cloud Model Studio console.
In the left-side navigation pane, choose .
On the Prompt Optimization tab, enter your prompt in the Original Prompt field.
Click Optimization. The result is displayed in the Optimized Prompt field.
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. |
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.
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:
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! #BailianInnovates #ZephyrZ9 #LightweightTechRevolution" | Introducing Bailian Zephyr Z9: Light as Air, Smart as Tomorrow! 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. Innovative 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. All-Day Power Play Fuel your digital adventures without the charger anxiety. Our optimized battery guarantees non-stop fun from sunrise to sunset, and beyond. Snap 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. 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. 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. Privacy First, Always Your digital life is yours alone. Advanced biometrics ensure your Zephyr Z9 stays locked to you and only you. 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! 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#
|
Output | Dry Your Locks in Style with the Johnson Hair Dryer Hey fashion-forward ladies! Your hunt for the perfect blowout buddy ends here. Let me introduce you to the Johnson Hair Dryer – your new BFF for salon-worthy hair every day! Compact & Travel-Ready Its sleek, compact design slides into any purse or luggage effortlessly. Perfect for that spontaneous weekend getaway or post-gym touch-ups! Stylish Statement Piece With 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! Power Packed Performance Say 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. Smart Heat for Healthy Hair Here's the smart part - intelligent heat control that adjusts to protect your tresses from overheating. Hello, shine! Goodbye, damage! 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! #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! 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 , solved my storage woe and made packing a breeze. The real game-changer? Its powerful airflow 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. 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. 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! #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
Final Output
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
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.