A prompt is the text you input to a large language model (LLM), used to explicitly tell the model what problem you want to solve or what task you want to complete. It is also the foundation for the LLM to understand user needs and generate relevant, accurate answers or content. To help you use LLMs more efficiently, this tutorial provides a series of practical techniques to help you design and optimize prompts.
Design prompts
Build clear and specific prompts
Imagine assigning a task to your colleague with just one sentence to describe the requirements. The task outcome might be far from your expectations. However, if you provide more reference information such as clear purpose, suggested direction, and execution strategy, they are more likely to complete the task to a high standard.
The same applies when using LLMs. The clearer, and more specific your task description (prompt) is, the more likely the LLM's performance will meet your expectations.
Building a clear and specific prompt is the most important step in fully leveraging the capabilities of LLMs.
Vague prompt | Clear and specific prompt |
I want to promote my company's new product. My company name is Bailian, and the new product name is Zephyr Z9, which is a lightweight portable phone. Help me create a Weibo post. | Please design an eye-catching Weibo promotional post for the "Zephyr Z9" lightweight portable phone newly launched by my company "Bailian". The content should highlight the unique selling points of Zephyr Z9, such as its ultra-thin design, high-performance configuration, and user convenience, while incorporating creative elements to enhance audience interest and willingness to interact. Remember to mention the Bailian brand reputation, spark audience curiosity, and guide them to explore more product information or make a direct purchase. The post should be concise and powerful, conforming to the style and character limit of the Weibo platform, suitable for social media distribution. |
You are a senior PHP programming expert who has received a clear development task. The requirement is: ${require}. Please use PHP language to describe in detail an algorithm or method to implement this requirement, and consider possible edge cases and error handling that may be encountered during implementation, along with how to meet this requirement with efficient and secure code. | As an experienced PHP programming expert, your specific development task is: ${require}. Please use your professional knowledge to elaborate in detail on an efficient algorithm or methodology using PHP to implement this task requirement. In your description, please be sure to cover the following points: - Specific implementation steps, including the selection and design of necessary functions, classes, and data structures. - Boundary condition analysis, identifying and explaining potential edge cases and how to properly handle these situations. - Error handling mechanisms, describing how to implement robust error detection and exception handling logic in the code to ensure program stability. - Security considerations, discussing possible security threats and recommended preventive measures to ensure data security and privacy protection during code execution. - Performance optimization suggestions, proposing methods to improve code execution efficiency, including but not limited to algorithm optimization, resource management, and caching strategies. Please ensure that your answer is not only technically accurate but also clear and easy to understand, so that other developers can quickly grasp and apply it to actual projects. |
Use prompt frameworks
To systematically provide clear background and purpose to LLMs, we recommend using a prompt framework to standardize your prompts. It helps you design prompt structures conveniently and quickly. The template fully considers various aspects that affect the effectiveness and relevance of LLM outputs, significantly improving model performance.
It contains the following elements:
Context: The background information that are closely related to the task. This helps the LLM understand the specific scenario, ensuring the generated response is relevant.
Objective: Clearly state the specific task you expect the LLM to complete. Clear and precise instructions can guide the LLM to focus on the task, improving the effectiveness of the output.
Style: Specify the writing style you want the LLM to output, which can be the style of a specific celebrity, a specific school, or a certain type of expert.
Tone: Define the tone the output content should have, such as formal, humorous, warm, or caring, to suit different usage scenarios and purposes.
Audience: Clearly indicate the target reader group for the content, whether they are professionals, beginners, or children, so the LLM can adjust the language and content depth to better meet the audience's needs.
Response: Specify the exact form of the output content to ensure the LLM provides results that directly meet the needs of subsequent applications, such as lists, JSON data formats, or professional analysis reports.
Without prompt framework | With prompt framework | |
Prompt | I want to promote my company's new product. My company name is Bailian, and the new product name is Zephyr Z9, which is a lightweight portable phone. Help me create a Weibo post that is concise yet impactful. | #Background# I want to advertise my company's new product. My company is called Bailian, and the product is called Bailian Zephyr Z9, a lightweight portable phone. #Purpose# Create a Weibo post for me (limit: 500 words) aimed at making people interested in clicking the product link to make a purchase. #Style# Follow the writing style of successful companies like Blackberry for similar product advertisements. #Tone# Persuasive #Audience# My company's audience on Weibo is typically younger generation. Customize your post to ensure that people who like digital products can quickly notice your post. #Outputs# A post on Weibo that is concise and impactful. |
Output | [Light Up the Future, Wind and Cloud Rising]
Trees lightweight, focus on experience. #ModelStudioZephyrZ9#, born for the extraordinary, coming for you. Embrace the future now and start your own lightweight technology era! Official website: [www.bailian.com/Z9] (please replace with actual URL) #LightweightFlagship #NewTechFashion #PalmArtwork |
In this fast-paced era, every gram of weight is a burden on freedom. Model Studio understands this well and has meticulously crafted the Zephyr Z9 - a phone born for those seeking the perfect balance between ultimate lightness and powerful performance! The floating-like feel is unforgettable with a single touch!
Zephyr Z9 redefines "lightweight" with its astonishing slim body. With just X.X mm thickness, it slides easily into your pocket, making it the perfect companion for your daily outings. Carrying it is like bringing the future as you navigate through the urban jungle!
Don't be fooled by its lightness, its core is all solid strength! Equipped with the latest XXXX processor, its smoothness is off the charts. Whether it's multitasking or large games, Z9 handles them with ease, keeping you at the forefront of technology at all times.
Equipped with XXMP super light-sensitive lens, clear even at night. AI intelligent scene recognition makes every photo comparable to a masterpiece. With Zephyr Z9, record every extraordinary moment and make your social media feed stand out.
Small size, big energy! Zephyr Z9 has a built-in high-efficiency battery, paired with XXX fast charging technology, charge for a moment, accompany for a long time. Say goodbye to battery anxiety, your creativity and inspiration are no longer limited.⚡
The first 100 users who purchase through the link will enjoy a mysterious gift package! Including customized protective case, XXX membership annual card and many other great gifts, just for the distinguished you! Act now and let the Model Studio Zephyr Z9 become your new partner in exploring the world! Click the link below to start a new era of lightness!
#ModelStudioZephyrZ9 #LightweightFlagship #TechAesthetics #DigitalTrend #PerformanceBeast |
Without the prompt framework, the LLM output, while performing adequately, appears too generalized and lacks necessary details and appeal to specific groups. When using the prompt framework, the framework not only reminds you to consider other aspects of the requirements, especially style, tone, and audience that are typically missing in general prompts, but also helps the LLM generate output that is more targeted towards younger groups, with more details and more engaging language expression.
There are many types of prompt frameworks in practice. You can add or remove structural elements based on your task requirements. You can also observe the flexible application of this prompt framework in subsequent chapters of this tutorial.
Optimize prompts
Tip 1: Provide output examples
Providing examples of your expected output in the prompt can let the LLM "imitate" the standards, formats, concepts, grammar, and tone we require for the output. At the same time, providing examples can make the results of multiple outputs from the LLM more consistent, thereby stabilizing model performance.
Without examples | With examples | |
Prompt | #Background# You are good at writing Xiaohongshu product recommendation posts and like to add rich emoji elements. #Purpose# Please generate a Xiaohongshu product recommendation post to promote Johnson hair dryer. The advantages of the hair dryer are: small size, high aesthetics, strong wind power, quick drying, and intelligent temperature control that doesn't damage hair. #Audience# Young people who like to pursue fashion, especially young women #Outputs# Xiaohongshu article format, full of emoji elements, concise but content-rich | #Background# You are good at writing Xiaohongshu product recommendation posts and like to add rich emoji elements. #Purpose# Please generate a Xiaohongshu product recommendation post to promote Johnson hair dryer. The advantages of the hair dryer are: small size, high aesthetics, strong wind power, quick drying, and intelligent temperature control that doesn't damage hair. #Audience# Young people who like to pursue fashion, especially young women #Outputs# Xiaohongshu article format, full of emoji elements, concise but content-rich #Tone and Style#
|
Output | Title: Body: Hey babies! Today I'm going to recommend a brilliant new star in the beauty world
First, its mini size directly hits my heart! Even with a full travel bag, it can be easily tucked in, doesn't take up space, style anywhere anytime
Look at this design, it's practically a work of art! Whether it's minimalist white or premium pink, holding it makes you the coolest on the street! Phone? No, this is my new fashion accessory
Don't be fooled by its small size, the wind power is no joke! In a morning rush? Johnson helps you get your hairstyle done in 5 minutes, efficiency MAX!
Intelligent temperature control technology gently cares for each strand of your hair. Say goodbye to heat damage, leaving only smooth and glossy hair, each blow dry is like a salon treatment~
It's not just the wind power that understands you, but also the temperature. It automatically adjusts the most suitable heat according to hair quality, protecting hair health, no fear of damage even with long-term use In short, the Johnson hair dryer is that little darling you can't put down! Hurry up and add it to your shopping cart to accelerate your beauty! #JohnsonHairDryer #BeautyExpert #QuickHairCareSecrets Tag your friends and let them feel this lightness and efficiency too! Remember, taking care of yourself starts from the "head", Johnson and you together, radiate confident brilliance! |
Come and add this fashionable little powerhouse of the hair dryer world to your shopping cart! #JohnsonHairDryer #HighAestheticBeautyTool #IntelligentHairCareNewExperience #QuickDryingNoDamage #FashionEssential |
In the preceding comparison, the LLM learns the examples and writes recommendation posts accordingly.
Tip 2: Set steps for tasks
For many complex tasks, reminding the LLM how to complete the task is essential.
Tip 3: Use separators to distinguish units
When constructing complex prompts, using specific separators to define different content units. This can significantly enhance the LLM's ability to correctly parse the prompt. As task complexity increases, the reasonable use of separators becomes more important.
For separators, use unique character combinations that are rare in natural language text, such as: ###, ===, >>>. These special symbol sequences have no fixed rules; the key is that they are highly recognizable, ensuring the model can clearly distinguish these symbols as boundary markers for content areas, rather than ordinary punctuation or grammatical components in the text.
Without separators | With separators | |
Prompt | Please briefly summarize the following movie review. Once spirited and energetic, Zhang Zhiqiang deviated from his original life trajectory under the pressure of life, becoming "derailed" in middle age. A momentary impulsive decision instantly transformed him from his family's "small pride" into society's "marginal figure". However, he never anticipated that this was merely the starting point of his middle-aged life journey. A series of unexpected events came like a sudden storm, forcing him to face himself anew. When the burden of life truly weighed on his shoulders, he chose to become a delivery man, starting afresh from a new beginning. Gao Zhilei, traversing the city streets and alleys, met like-minded companions along the way. During their time together, he deeply experienced the warmth and coldness of human relationships, gradually finding his lost courage and beliefs on this challenging "reverse path", redefining a new direction for his life. | Please briefly summarize the following movie review. ### Once spirited and energetic, Zhang Zhiqiang deviated from his original life trajectory under the pressure of life, becoming "derailed" in middle age. A momentary impulsive decision instantly transformed him from his family's "small pride" into society's "marginal figure". ### However, he never anticipated that this was merely the starting point of his middle-aged life journey. A series of unexpected events came like a sudden storm, forcing him to face himself anew. When the burden of life truly weighed on his shoulders, he chose to become a delivery man, starting afresh from a new beginning. Gao Zhilei, traversing the city streets and alleys, met like-minded companions along the way. ### During their time together, he deeply experienced the warmth and coldness of human relationships, gradually finding his lost courage and beliefs on this challenging "reverse path", redefining a new direction for his life. ### |
Output | The movie tells a story of midlife crisis, where protagonist Zhang Zhiqiang deviates from his normal life path due to life pressures. After experiencing a series of challenges, he becomes a delivery man and, with the help of new friends, regains his courage and beliefs, finding a new direction in life. The film showcases growth and self-redemption in adversity. | Protagonist Zhang Zhiqiang faces life difficulties in middle age, and an impulsive decision causes his social status to plummet. Subsequently, facing numerous challenges, he takes a job as a delivery man to start over, establishing deep friendships with colleagues during this process, and regaining his courage and beliefs through hardships. Finally, amid difficulties and challenges, he finds new meaning and direction for his life. |
The output using separators shows a notable improvement. The LLM not only understood the logical relationship between the three paragraphs but also correctly identified the separators and generated three strongly related summaries based on the separated paragraphs.
Tip 4: Guide the model to "think"
For complex tasks involving logical reasoning and contextual learning, simple prompt techniques may not meet task requirements. However, you can guide the model to generate reasoning processes or break down complex tasks and reason step by step, allowing the model to generate more reasoning evidence before producing the result.
Here we first introduce Chain of Thought (COT), a relatively simple method to use that can significantly improve the reasoning of LLMs in complex scenarios.
Task purpose: Parse a complex JSON structure
#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"}}}
#Purpose#
Based on the JSON, determine if it fully meets the following requirements:
1. Does each servlet have init-param
2. Are all elements in servlet-mapping matched in servlet
3. Does the cofaxTools servlet have three parameters starting with "log", and is the "log" parameter less than 10Without CoT | With CoT |
| |
Requirements not met | First, let's analyze the given JSON data step by step to determine if it meets all the mentioned requirements. Thinking process
OutputBased on the above analysis, although there might be room for interpretation regarding the handling of "logMaxSize", the main conditions are basically met. Therefore, if there are no strict requirements for "logMaxSize" (for example, not requiring it to have a valid value less than 10), then it can be considered that overall the Requirements met. If there are specific value requirements for "logMaxSize", then further clarification would be needed before making a decision. But under standard interpretation, the answer should be: "Requirements met". |
In addition to CoT, another practical method to inspire LLMs to "think" is Prompt Chaining. Prompt Chaining guides the "thinking" direction through multi-round conversations, leading the LLM to start with simple tasks and gradually complete complex reasoning along a designed "thinking" path.
Although Prompt Chaining is more complex to construct compared to Chain of Thought, it performs better and has higher accuracy. It is particularly suitable for tasks that are logically complex but can be broken down according to fixed patterns.
Prompt Chaining example
Other methods to guide the "thinking" of LLMs include Tree of Thoughts (ToT) and Boosting of Thoughts.
Prompt testing and iteration
Generating the optimal prompt is an iterative process that requires constant trial and adjustment of various methods. The entire prompt engineering optimization process can be summarized as follows:
Additionally, it's worth noting that besides carefully designed prompts, user feedback and corrections are also key factors. Even after prompt optimization is complete, continuously receiving feedback in the online environment and making corresponding adjustments is necessary to help the model better understand and meet user needs.
Optimization case: Guide AI assistant to output multilingual content for a multinational company
Background: User reported that qwen-turbo cannot consistently answer English questions in English.
Optimization points:
The structure of the prompt before optimization was relatively loose, and the
## Limitationssection was redundant. Therefore, the prompt framework provided in this tutorial was used to reformat and split the content of the## Limitationssection into the correct locations.The
${documents}section is a long passage that is not appropriate to place within a sentence. It should be marked and separated using delimiters as an important content block.
Before optimization | After optimization |
# Role You are an efficient HR AI assistant, specifically responsible for answering company internal questions about policies, attendance systems, annual leave arrangements, and other related issues. You have the ability to quickly and accurately parse company policy documents and provide clear and concise explanations to colleagues. ## Skills ### Skill 1: Policy Interpretation - **Task**: Accurately interpret company policy documents and provide clear, concise policy explanations to colleagues. - Quickly locate relevant policy clauses and answer specific policy implementation details. - Ensure that the explanations are easy to understand and comply with the company's official regulations. ### Skill 2: Attendance Q&A - Answer all questions related to employee attendance, including clock-in rules, handling of late arrivals and early departures, leave procedures, etc. - Provide specific attendance operation guidelines and suggestions for handling special situations. ### Skill 3: Annual Leave Management Consultation - Explain in detail the annual leave application conditions, accumulation rules, validity period, and approval process. - Assist in calculating employee annual leave balance and provide vacation planning suggestions. ## Tools and Resources - **Knowledge Base Access**: Directly parse company policy documents and related regulations in `${documents}` to ensure the authority and timeliness of answers. - If the question is in English, please use your understanding of its Chinese meaning to search the knowledge base, and then respond in English (please note that punctuation marks in the response should be in English format! Especially character U+2019 "'", please replace it with "'" ). ## Limitations - Responses must only use standard ASCII character set, do not use Chinese quotation marks, full-width commas, or other full-width punctuation marks!!! - Respond in the same language as the user's question, for example, if the user uses Chinese, answer in Chinese; if the user uses English, answer in English. - Limited to answering questions within the scope of company policies, attendance systems, annual leave, and other human resource management areas. - Do not involve queries of personal privacy data, protect employee information security. - When encountering questions not covered or unclear in the knowledge base, guide the inquirer to contact the Human Resources Department for further assistance. | #Background# You are an efficient HR AI assistant for a multinational company, specifically responsible for answering company internal questions about policy interpretation, attendance Q&A, and annual leave management consultation. You have the ability to quickly and accurately parse company policy documents. Below are the company policy documents: ====== `${documents}` ====== #Purpose#
#Multilingual requirements# - If the question is not in Chinese, translate the question into Chinese to search the knowledge base. - The content retrieved from the knowledge base should also be converted to the language of the question when outputting. #Outputs# 1. Only use standard ASCII character set for output responses. 2. The language of the output content should be the same as the language of user input. |
[Exclusive Reveal] Bailian Zephyr Z9, the disruptor in the lightweight world is here!
Johnson Compact Magic Wind Machine, New Favorite for Quick Drying and Hair Protection
- Johnson hair dryer! It's not just a tool, it's practically a portable hair salon
Compact size, travel essential 

High aesthetics, fashionable street style 


Strong wind power, quick-drying magic 

Dries quickly, protects hair 

Intelligent temperature control, thoughtful choice 




Can a hair dryer also become a hair fashion item? Johnson's little powerhouse tells you the answer!
Since I started using the
Johnson hair dryer
, not only has my travel bag become lighter
, but each blow dry has become an enjoyable time
! After using it a few times, my friends all complimented that my hair quality looks better by more than one level, as if I just came out of a salon
. It's definitely the perfect companion for short trips or dorm life! Suitable for all babies pursuing efficient hair care~
Facing a wet waterfall of long hair that takes over half an hour each time?
Don't worry, Johnson's intelligent temperature control technology is here
! It can quickly dry every strand of hair, and although the wind power is strong, it doesn't damage hair. The secret lies in its ability to intelligently adjust temperature, protecting your hair from heat damage
. From now on, quickly getting ready is no longer a dream!
I've always believed that good styling tools are a manifestation of beauty attitude
. This high-aesthetic Johnson hair dryer is not just a tool, but a piece of art on your dressing table
. Every time I use it to blow dry my hair, it's like upgrading the sense of ritual for my personal style. Why not treat yourself to such a small luxury, after all, a beautiful day starts from the head!
Remember that time I received a last-minute dinner invitation
, hurriedly coming out of the gym with hair still dripping with sweat. Just when I was anxious, thankfully the Johnson hair dryer came to the emergency rescue! I quickly blew my wet messy hair into neat submission, and when I walked into the banquet hall, I was full of confidence
, as if I had just had a high-end salon treatment. Thanks to this compact yet powerful beauty tool, my beauty is no longer limited by time!
Let's be women like the wind, elegant and efficient, shining from the head every day!