SuperAPI AI Directory

Google "Prompt Engineering" Prompt Engineering Whitepaper (PDF File) - AI Tutorial Materials

Author: AI小集 · Original source: AI工具集

The "Prompt Engineering" prompt engineering whitepaper was jointly released by members of the Google team. Its main content includes how to design high-quality prompts to optimize the output performance of large language models (LLMs). The whitepaper introduces in detail various prompting techniques, such as zero-shot prompting, one-shot and few-shot prompting, system prompting, role prompting, and contextual prompting, etc., discusses the impact of model output configurations (such as temperature, top-K, top-P, and other parameters) on generated results, and provides practical examples and best practices to help users use LLMs more effectively in different scenarios. It emphasizes that prompt engineering is an iterative process and requires adjusting prompt structure and model parameters in combination with task requirements to obtain accurate and relevant output.

Prompt Engineering

CakeGrowth QR code

Get"Prompt Engineering" Prompt Engineering Whitepaper  Original PDF file, scan the QR code to follow and reply: 20250411

Acknowledgements

Content Contributors

Michael Sherman

Yuan Cao

Eric Armbruster

Anant Nawalgaria

Antonio Gulli

Simon Carmel

Editors

Antonio Gulli

Anant Nawalgaria

Grace Morrison

Technical Writer

Joey Haymaker

Designer

Michael Lanning

Introduction

In the input-output mechanism of large language models, a text prompt (sometimes combined with multimodal inputs such as images) is the basic input used by the model to generate predictions. You do not need to be a data scientist or machine learning engineer; anyone can write prompts. But to build truly effective prompts, the process can be quite complex. The effectiveness of a prompt is influenced by multiple factors: the chosen model version, the model's training data, parameter configuration, precision of wording, language style and tone, structural design, and contextual relevance are all crucial. Therefore, prompt engineering is essentially a process that requires continuous optimization. Low-quality prompts not only lead to ambiguous or incorrect outputs, but also limit the model's ability to generate valuable content.

When you communicate with the Gemini chatbot, you are actually writing prompts. However, this whitepaper will focus on how to write prompts for the Gemini model on the Vertex AI platform or through the API, because when you call the model directly, you will have access to complete configuration options such as the temperature parameter.

This whitepaper discusses prompt engineering in detail. We will explore various prompting techniques to help you get started and share tips and best practices for becoming a prompt expert. We will also discuss the challenges you may encounter when designing prompts.

Prompt Engineering

Remember how LLMs work: it is a prediction engine. The model takes a sequence of text as input and then predicts the next token based on its training data. The LLM repeatedly performs this operation, adding the previously predicted token to the end of the sequence of text to predict the next token. The prediction of the next token is based on the relationship between the content of the previous tokens and what the LLM has seen during training.

When writing a prompt, you are setting the correct token sequence for the LLM. Prompt engineering is the process of designing high-quality prompts to guide the LLM to generate accurate outputs. This includes adjusting prompts to find the best version, optimizing prompt length, and evaluating whether the prompt's writing style and structure are relevant to the task. In the context of natural language processing and LLMs, a prompt is the input provided to the model to generate a response or prediction.

These prompts can be used to complete a variety of understanding and generation tasks, such as text summarization, information extraction, question answering, text classification, language or code translation, code generation, and code documentation or reasoning.

Feel free to refer to Google's prompting guide, which contains simple and effective prompt examples.

When doing prompt engineering, you first need to choose a model. Whether you use the Gemini language model in Vertex AI, GPT, Claude, or open-source models such as Gemma or LLaMA, prompts may need to be optimized for your specific model.

In addition to prompts, you also need to adjust various configurations of the LLM.

LLM Output Configuration

After choosing a model, you need to determine the model's configuration. Most LLMs provide multiple configuration options to control output. Effective prompt engineering requires optimizing these settings according to the task.

Output Length

An important configuration parameter is controlling the number of tokens in the generated response. Generating more tokens requires more computation from the large language model, leading to increased energy consumption, potentially slower response times, and higher costs.

Reducing the LLM's output length does not make the LLM more concise or stylized in its output content; it simply makes the LLM stop predicting tokens once the length limit is reached. If your needs require shorter output, you may also need to specially design the prompt to meet the requirements.

Output length limits are especially important for certain LLM prompting techniques, such as ReAct, where the LLM may continue generating useless tokens after the response you want.

Sampling control

An LLM does not predict a single token, but rather predicts a probability distribution over the next token. Temperature, Top-K, and Top-P are the most common configuration options used to decide how to select the output token from the predicted token probabilities.

  • Temperature

The temperature parameter controls the degree of randomness in token selection. Lower temperatures are suitable for prompts that require deterministic output, while higher temperatures may produce more diverse or unexpected results. A temperature of 0 (greedy decoding) is completely deterministic: the token with the highest probability is always selected (but note that if two tokens have the same highest predicted probability, depending on the tie-handling mechanism, the output may also be inconsistent when temperature is set to 0).

As temperature approaches its maximum value, the output tends to be more random. As temperature continues to increase, the probabilities of all tokens being selected as the next predicted token tend to become equal.

The Gemini temperature control mechanism is similar in principle to the softmax function used in machine learning. A low temperature setting is similar to a low softmax temperature (T), emphasizing a single preferred result with high determinism. A high temperature setting is similar to a high softmax temperature, accepting a broader range of results. This flexibility is especially suitable for scenarios that do not require strictly precise output (for example, creative content generation experiments).

  • Top-K and Top-P sampling

Top-K and Top-P (also known as nucleus sampling) are two sampling settings used in LLMs to limit the range of predicted tokens. Similar to the temperature parameter, they control the randomness and diversity of generated text.

  • Top-K sampling selects the K tokens with the highest probabilities from the model's predicted distribution. The larger the K value, the more creative the output; the smaller the K value, the more conservative and accurate the output. When K=1, it is equivalent to greedy decoding.
  • Top-P sampling selects the set of highest-probability tokens whose cumulative probability does not exceed the set value (P). The P value ranges from 0 (greedy decoding) to 1 (including all vocabulary tokens).

The best practice is to compare the two methods (or use them in combination) through experimentation, and choose the optimal approach based on actual needs.

Putting it all together

Choosing among top-K, top-P, temperature, and the number of tokens to generate depends on the specific application and expected results, and these settings all affect one another. At the same time, it is also important to make sure you understand how the chosen model combines different sampling settings.

If temperature, top-K, and top-P are all available (as in Vertex Studio), the tokens that satisfy both the top-K and top-P criteria will become candidates for the next predicted token, and then temperature is applied to sample from these tokens that pass the top-K and top-P criteria. If only top-K or top-P is available, the behavior is the same but uses only one of the top-K or top-P settings.

If temperature is not available, then randomly select from the tokens that satisfy the top-K and/or top-P criteria to generate a single next predicted token.

When a sampling configuration value is set to an extreme value, that sampling setting will either cancel out the other configuration settings or become irrelevant.

  • If you set temperature to 0, top-K and top-P become irrelevant, and the most likely token will become the next predicted token. If you set temperature very high (above 1—usually above 10), temperature becomes irrelevant, and then randomly sample from the tokens that pass the top-K and/or top-P criteria to choose the next predicted token.
  • If you set top-K to 1, temperature and top-P become irrelevant. Only one token passes the top-K criterion, and that token is the next predicted token. If you set top-K very high, such as to the size of the LLM vocabulary, any token with a non-zero probability of becoming the next token will satisfy the top-K criterion, and no token is selected.
  • If you set top-P to 0 (or a very small value), most LLM sampling implementations will consider only the most likely token to satisfy the top-P criterion, which makes temperature and top-K irrelevant. If you set top-P to 1, any token with a non-zero probability of becoming the next token will satisfy the top-P criterion, and no token is selected.

As a general starting point, a configuration with temperature 0.2, top-P value 0.95, and top-K value 30 can produce relatively coherent and moderately creative results. For particularly creative output, try an initial setting of temperature 0.9, top-P 0.99 with top-K 40. For scenarios with lower creative requirements (such as pursuing stability), it is recommended to use a combination of temperature 0.1, top-P 0.9, and top-K 20. Note that when a task has a single correct answer (for example, solving a math problem), the temperature parameter should be set to 0 to obtain deterministic output.

Note: As the degrees of freedom increase (higher temperature, top-K, top-P, and output tokens), the LLM may generate text that is less relevant to the topic.

WarningHave you ever seen a response that ends with a large number of filler words? This is also known as the "repetition loop error," a common problem in large language models. When the model gets stuck in a loop, it repeatedly generates the same (filler) word, phrase, or sentence structure, a situation that is often exacerbated by inappropriate temperature and top-k/top-p settings. This phenomenon can occur under both low-temperature and high-temperature settings, but for different reasons: at low temperature, the model becomes too certain and strictly follows the highest-probability path, and if that path revisits previously generated text, it can lead to a loop. At high temperature, the model's output becomes too random, and because there are so many options available, randomly selected words or phrases may by chance return to a previous state, thus forming a loop. In both cases, the model's sampling process gets "stuck," producing monotonous and useless output until the output window is filled. Solving this problem usually requires carefully adjusting the temperature and top-k/top-p values to find the best balance between determinism and randomness.

Prompting techniques

Large language models (LLMs) are specifically tuned to follow instructions, and through training on massive amounts of data they are able to understand prompts and generate responses. But LLMs are not perfect. The clearer your prompt text is, the more accurately the model can predict the following text. In addition, specific techniques that make full use of the LLMs' training mechanisms and operating principles will help you obtain more precise and relevant results from the model.

Now that we understand what prompt engineering is and what it requires, let us dive into some important examples of prompting techniques.

General prompting / zero-shot

Zero-shot prompting is the simplest type of prompting. It provides only a task description and the base text for the LLM to begin processing. This input can be anything: a question, the beginning of a story, or an instruction. The name "zero-shot" means "no examples."

Let us use Vertex AI Studio (Language) in Vertex AI, which provides an experimental environment for testing prompts. In Table 1, you will see an example of a zero-shot prompt for movie review classification.

The table format shown below is an excellent way to record prompts. Your prompts may go through multiple iterations before they finally enter the codebase, so it is very important to track prompt engineering work in a standardized and structured way. For more on this table format, the importance of tracking prompt engineering work, and the prompt development process, see the "Best practices" section later in this chapter ("Document various prompt attempts").

Because creative output is not needed, set the model temperature to a low value, and we use the default top-K and top-P values of gemini-pro, which effectively disables these two settings (see "LLM output configuration" earlier). Please note the generated output results. The words "disturbing" and "masterpiece" make prediction a little more complicated, because these two words appear in the same sentence.

Objective Classify a movie review as positive, neutral, or negative
Model gemini-pro
Temperature 0.1
Prompt Classify movie reviews as POSITIVE, NEUTRAL or NEGATIVE. Review: "Her" is a disturbing study revealing where humans are headed if AI continues to run unrestrained. I hope there will be more masterpieces like this. Sentiment:
Output POSITIVE

Table 1. Zero-shot prompt example

When zero-shot approaches are ineffective, you can provide demonstration examples in the prompt, thereby adopting "one-shot" or "few-shot" prompting techniques.

One-shot & Few-shot

When creating prompts for AI models, providing examples is helpful. These examples can help the model understand what you are asking for. Examples are especially useful when you want to guide the model to a specific output structure or pattern.

One-shot prompting provides one  example, hence the name one-shot. The idea is that the model has an example it can imitate to best complete the task.

Few-shot prompting provides multiple examples to the model. This approach shows the model the pattern it needs to follow. The idea is similar to one-shot, but providing multiple examples of the target pattern increases the likelihood that the model will follow that pattern.

The number of examples required for few-shot prompting depends on several factors, including task complexity, example quality, and the capability of the generative AI (gen AI) model being used. In general, you should use at least three to five examples for few-shot prompting. However, for more complex tasks, you may need to use more examples, or due to model input length limits, you may need to use fewer examples.

Table 2 shows an example of a few-shot prompt. We will continue to use the same gemini-pro model configuration parameters as before, but need to increase the token limit to accommodate the need to generate longer responses.

Goal Parse pizza orders into JSON
Prompt Example: I want a small pizza with cheese, tomato sauce, and pepperoni. JSON response: { “size”:”small”, “type”:”normal”, “ingredients”:[“cheese”,”tomato sauce”,”pepperoni”] }
Output { “size”:”large”, “type”:”half-half”, “ingredients”:[[“cheese”,”mozzarella”],[“tomato sauce”,”ham”,”pineapple”]] }

Table2.FewshotpromptexampleExample

When selecting prompt examples, you should use examples relevant to the task you want to perform. These examples should be diverse, high-quality, and well-formulated. Even a small error can confuse the model, leading to undesirable output results.

If you need to generate robust output that can handle various inputs, you must include edge cases in the examples. Edge cases refer to uncommon or unexpected input situations that the model should still be able to handle correctly.

System, Context, and Role Prompting

System, context, and role prompting are all techniques used to guide LLM text generation, but they focus on different aspects:

  • System prompting sets the overall context and purpose for the language model. It defines the "big picture" task the model should perform, such as translating languages, classifying comments, etc.
  • Contextual prompting provides specific details or background information related to the current conversation or task. It helps the model understand the nuances of the request and adjust its response accordingly.
  • Role prompting assigns a specific role or identity to the language model. This helps the model generate responses consistent with the assigned role and its associated knowledge and behavior.

There can be considerable overlap among system, context, and role prompting. For example, a prompt that assigns a role for the system can also include context. The main purpose of each prompt type is slightly different:

  • System prompting: Defines the model's basic capabilities and overall goals.
  • Contextual prompting: Provides immediate, task-specific information to guide the response. It is highly specific to the current task or input and is dynamic.
  • Role prompting: Shapes the model's output style and tone. It adds a layer of specificity and personality.

Distinguishing among system prompting, contextual prompting, and role prompting provides a framework for designing prompts with clear intent, allowing flexible combinations, and making it easier to analyze how each prompt type affects the language model's output.

  • System prompting

Table 3 contains a system prompt in which I additionally specified relevant information about how to return the output. I increased the temperature parameter to obtain a higher level of creativity, and specified a higher token limit. However, due to my explicit instructions on how the output should be returned, the model did not return extra text.

Goal Classify movie reviews as positive, neutral, or negative.
Model gemini-pro
Temperature 1 Token Limit 5
Top-K 40
Top-P 0.8
Prompt Classify movie reviews as positive, neutral or negative. Only return the label in uppercase. Review: “Her” is a disturbing study revealing the direction humanity is headed if AI is allowed to keep evolving, unchecked. It’s so disturbing I couldn’t watch it. Sentiment:
Output Negative

Table 3. Examples of system prompts

System prompts are very useful for generating output that meets specific requirements. The name 'system prompt' actually stands for 'providing additional tasks to the system'. For example, you can use a system prompt to generate code snippets compatible with a specific programming language, or you can use a system prompt to return a clear framework. See Table 4, where I returned the output in JSON format.

Name Content
Objective Classify movie reviews as positive, neutral, or negative, and return JSON.
Model gemini-pro
Temperature 1
Top-K 40
Token Limit 1024
Top-P 0.8
Prompt

Classify movie reviews as positive, neutral or negative. Return

valid JSON:

Review: “Her” is a disturbing study revealing the direction

humanity is headed if AI is allowed to keep evolving,

unchecked. It’s so disturbing I couldn’t watch it.

Schema:

“`

MOVIE:

{

“sentiment”: String “POSITIVE” | “NEGATIVE” | “NEUTRAL”,

“name”: String

}

MOVIE REVIEWS:

{

“movie_reviews”: [MOVIE]

}

“`

JSON Response:

Output

“`

{

“movie_reviews”: [

{

“sentiment”: “NEGATIVE”,

“name”: “Her”

}

]

}

“`

Table 4. Example of a system prompt using JSON format

Returning JSON objects to extract data from prompts has the following advantages. In practical applications, I do not need to manually create a JSON format, and can directly return sorted data (which is very convenient when handling datetime objects). Most importantly, by requiring the JSON format, the model can be forced to create structured output and limit hallucinations.

System prompts are also very useful for safety and content filtering. To control the output, simply add additional instructions in the prompt, for example: "Respond in a respectful manner."

  • Role prompting

Role prompting is a technique in prompt engineering that involves assigning a specific role to a generative AI model. This helps the model generate more relevant and informative output, because the model can tailor its response according to the assigned role.

For example, you can have a generative AI model play the role of a book editor, a kindergarten teacher, or a motivational speaker. Once the model has been assigned a role, you can give specific prompts related to that role. For example, you can prompt a teacher to create a lesson plan for them to review. See Table 5, where the model plays the role of a travel guide.

Parameter/Content Details
Objective Play the role of a travel guide and provide 3 travel suggestions
Model Gemini Pro
Temperature 1
Top-K 40
Token limit 1024
Top-P 0.8
Prompt I want you to act as a travel guide. I will write to you about my location and you will suggest 3 places to visit near me. In some cases, I will also give you the type of places I am on: “I am in Amsterdam and I want to visit only museums.”
Output Travel recommendations: 1. Rijksmuseum: A world-famous museum, known for the works of Dutch masters, similar to Rembrandt's "The Night Watch." Do not miss the incredible collection. Interactive facts about paintings and displays of Dutch art and history. 2. Van Gogh Museum: Immerse yourself in Vincent's fascinating works. The museum houses the largest collection of his paintings and drawings, including "The Starry Night" and "Sunflowers." 3. Stedelijk Museum Amsterdam: Explore modern and contemporary art from around the world. The museum's collection includes works by Picasso, Kandinsky, and Rietveld, housed in a striking modern building.

Table 5. Examples of role prompts

The above examples show scenarios in which AI is made to take on the role of a travel agent. When you change the role to a geography teacher, you will notice that the responses obtained will be different.

Defining a role perspective for an AI model is equivalent to providing it with a blueprint regarding tone, style, and area of expertise, thereby improving the quality, relevance, and effectiveness of the output.

The following are some styles you can choose from, and I think they are effective: adversarial, descriptive, direct, formal, humorous, influential, informal, motivational, persuasive.

Change the prompt in Table 6 to include a humorous and inspiring style.

Prompt I want you to act as a travel guide. I will write to you about my location and you will suggest 3 places to visit near me in a humorous style.

My suggestion: “I am in Manhattan.”

Travel Suggestions:

Output 1. Empire State Building: Experience a "King Kong"-like perspective (but without the giant banana). 2. Museum of Modern Art: Question the artistic value of your own stick figure drawings. 3. Fifth Avenue: A shopping experience that makes your wallet cry.

Table 6. Example role prompts with a humorous tone and style

  • Contextual Prompts

By providing contextual prompts, you can make AI interactions smoother and more efficient. As shown in the example in Table 7, this technique enables the model to understand requests faster and generate more accurate and relevant responses.

Goal Suggest some article ideas for a blog about retro games
Model Gemini Pro
Temperature 1
Top-K 40
Token limit 1024
Top-P 0.8
Prompt Context: You are writing for a blog about retro 80’s arcade video games. Suggest 3 topics to write an article about with a few lines of description of what this article should contain.
Output 1. The Evolution of Arcade Cabinet Design: This article will explore the evolution of arcade cabinet design, from the early wooden and metal cabinets of the 1970s to the sleek, neon-lit modern designs of the 1980s and beyond. 2. Nostalgic Classics: Iconic 80s Arcade Games: This article will take you on a journey through the history, impact, and legacy of some of the most iconic and influential 80s arcade games, including some of the most iconic and influential 80s arcade games, highlighting their innovations, popular mechanics, and enduring appeal. 3. The Rise of Pixel Art and the Retro Revival: This article will delve into the evolution of pixel art as a defining visual style tracing its roots to early arcade games, exploring its techniques, and discussing the revival of pixel art in modern games and digital art.

Table 7. An example of a context prompt

Step-back prompting

Step-back prompting is a technique that improves performance by prompting the LLM to first think about general questions related to the current specific task, and then feeding the answer to that general question into the subsequent specific task prompt. This step-back step allows the LLM to activate relevant background knowledge and reasoning processes before attempting to solve the specific problem.

By considering broader and more fundamental principles, the LLM can generate more accurate and insightful responses. Step-back prompting encourages the LLM to think critically and apply its knowledge in novel and creative ways. Compared to directly prompting the LLM to perform a task, this technique changes the way the final task is prompted by leveraging more untapped knowledge in the LLM's parameters.

By focusing on general principles rather than specific details, step-back prompting helps mitigate bias in LLM responses.

Let us understand through examples how step-back prompting improves results. First look at traditional prompting (Table 8), then compare it with step-back prompting (Table 9).

Goal Write a storyline for a level of a first-person shooter video game.
Model

gemini-pro

Temperature 1
Token Limit 1024
Top-K 40
Top-P 0.8
Prompt Write a one paragraph storyline for a new level of a first-person shooter video game that is challenging and engaging.
Output Acard,ePlayerof thecitydistrictsuffersanenemyhostileforce'sforces'sambushambush。playerplayersmustmustpassthroughintricatecomplexcomplexcomplex'sbackalleysandruinedruinedbuildingsbuildingscomplex,employusestealthstealthcombattacticsandprecisionprecisionshootingshootingeliminateeliminateenemy troopstroopsandavoidavoidexposureexposure。playersplayersneed tocleverlycleverlyuseusethe environmentenvironmentadvantagesadvantages——setsettrapstraps、findfindcovercover、carefullycarefullyplanplaneveryeveryeachactionactionin order toin order tosurvivesurvival。along the wayalong the wayobtainobtained'sintelligenceintelligenceShowsenemypersoniscurrentlyplanningningdestroydestructionnatureattackstrike,playplayermustmustcompeterace against timeseizesecondcollectgatherevidenceevidence,hurryatenemysideactactionbeforewillintelligenceintelligencetransmitbackheadquartersheadquarters。

Table 8. A traditional prompt before we compare it with the fallback prompt.

When the temperature parameter is set to 1, you may get a variety of creative storylines, but the output is often too random and lacks uniqueness. Therefore, we adopt fallback thinking:

Prompt Based on popular first-person shooter action games, what are 5 fictional key settings that contribute to a challenging and engaging level storyline in a first-person shooter video game?
Output

1. Abandoned military base: a vast post-apocalyptic military complex crawling with mutated soldiers and rogue robots, perfect for a re-equipped combat challenge. 2. Cyberpunk city: a neon-lit futuristic city environment with towering skyscrapers and dense alleyways, featuring electronically enhanced enemies and hacking mechanics. 3. Alien spacecraft: a massive alien spacecraft stranded on Earth, with eerie corridors, zero-gravity areas, and alien creatures to encounter. 4. Zombie-infested town: a desolate town overrun by hordes of zombies, with intense close-quarters combat and puzzle-solving to find a safe passage. 5. Underwater research facility: a water-filled deep-sea laboratory teeming with mutated aquatic creatures, requiring diving and underwater exploration skills to survive.

Table 9. An example of self-consistency prompting

Indeed, these themes are very suitable for developing a first-person perspective game. Now let us return to the original prompt, but this time add the answer derived from "step-back thinking" as contextual information, and observe how the model's output changes.

Prompt

Context: 5 engaging themes for a first person shooter video game:

  1. **Abandoned Military Base**: A sprawling, post-apocalyptic military complex crawling with mutated soldiers and rogue robots, ideal for challenging firearm combat.
  1. **Cyberpunk City**: A neon-lit, futuristic urban environment with towering skyscrapers and dense alleyways, featuring cybernetically enhanced enemies and hacking mechanics.
  1. **Alien Spaceship**: A vast alien vessel stranded on Earth, with eerie corridors, zero-gravity sections, and extraterrestrial creatures to encounter.
  1. **Zombie-Infested Town**: A desolate town overrun by hordes of aggressive zombies, featuring intense close-quarters combat and puzzle-solving to find safe passage.
  1. **Underwater Research Facility**: A deep-sea laboratory flooded with water, filled with mutated aquatic creatures, and requiring stealth and underwater exploration skills to survive.

Take one of the themes and write a one paragraph storyline for a new level of a first-person shooter video game that is challenging and engaging.

Output Deep in a gloomy abyss lies a dilapidated underwater research facility, a testament to human ambition and its catastrophic consequences. Shrouded in darkness, filled with the humming of malfunctioning machines, and echoing with the ghostly reverberations of the drowned, the facility has now become a breeding ground for deep-sea nightmares. The player is an elite diver equipped with advanced diving gear and experimental weapons, tasked with penetrating this terrifying underwater world. With unyielding perseverance and resourcefulness, they must navigate perilous corridors, solve mysterious puzzles, and engage in desperate battles with dreadful sea monsters lurking in the depths. From withstanding the immense pressure of the deep sea to outwitting cunning underwater predators, every moment in this unknown underwater world tests the limits of human endurance and courage.

Table 10. An example of self-consistency prompting

This game concept looks interesting! By using step-back prompting, you can significantly improve the precision of your prompts.

Chain of Thought (CoT)

Chain of Thought (CoT) is a technique that improves the reasoning ability of large language models (LLMs) by generating intermediate reasoning steps. This helps LLMs produce more accurate answers. You can combine it with few-shot prompting to achieve better results on more complex tasks that require reasoning to respond, as this is the challenge of zero-shot chain of thought.

CoT has many advantages. First, it is very effective with low effort, and it works well with off-the-shelf LLMs (so no fine-tuning is needed). You can also gain interpretability through CoT prompting, because you can learn from the LLM's response and see the reasoning steps that were followed. If a failure occurs, you will be able to identify it. Chain-of-thought also seems to improve robustness when moving between different LLM versions. This means that your prompt's performance should vary less across different LLMs than a prompt that does not use a reasoning chain. Of course, there are also some disadvantages, but they are fairly intuitive.

The LLM's response includes chain-of-thought reasoning, which means more output tokens, which means prediction is more expensive and takes longer.

To explain the following example in Table 11, let's first try to create a prompt that does not use CoT prompting, to show the shortcomings of large language models.

Prompt When I was 3 years old, my partner was 3 times my age. Now, I am 20 years old. How old is my partner?
Output 63 years old

Table 11. An example of a prompt that attempts to solve a math problem

Obviously the wrong answer. In fact, large language models often perform poorly on math tasks and may give wrong answers, even for simple tasks like multiplication. This is because they are trained on large amounts of text, and math may require a different approach. So let's see whether intermediate reasoning steps improve the output.

Prompt When I was 3 years old, my partner was 3 times my age. Now, I am 20 years old. How old is my partner? Let’s think step by step.
Output 1. Suppose my current age is "x" years old. 2. When I was 3 years old, my age was 3 years old. 3. At that time, my partner's age was 3 times mine, that is, my partner's age was 3 * 3 = 9 years old. 4. Now, I am 20 years old, which means my age has increased by 20 – 3 = 17 years, how many years have passed since I was 3 years old. 5. Since when I was 3 years old, my partner's age was 9 years old, and my age has increased by 17 years, my partner's age must also have increased by 17 years. 6. Therefore, my partner's current age is 9 + 17 = 26 years old. So, my partner is now 26 years old.

Table 12. An example of chain-of-thought prompting

Now the final answer is correct. This is because we explicitly instructed the large language model (LLM) to explain each step, rather than just return the answer. Interestingly, the model adopted the approach of adding the 17 increased years (17+3=20). My way of thinking was: first calculate the age difference between my partner and me, and then add (20+(9-3)). Let's help the model get closer to my way of thinking.

Table 12 is an example of 'zero-shot' chain-of-thought. When combined with one-shot or few-shot examples, chain-of-thought prompting can be very powerful, as you can see in Table 13.

Prompt Q: When my brother was 2 years old, I was double his age. Now I am 40 years old. How old is my brother? Let’s think step by step.

A: When my brother was 2 years, I was 2 * 2 = 4 years old.That’s an age difference of 2 years and I am older. Now I am 40 years old, so my brother is 40 – 2 = 38 years old. The answer is 38.

Q: When I was 3 years old, my partner was 3 times my age. Now,I am 20 years old. How old is my partner? Let’s think step by step.

A:

Output When I was 3 years old, my partner was 3 * 3 = 9 years old. That is an age difference of 6 years, and my partner is older than me. Now I am 20 years old, and my partner is now 26 years old. The answer is 26.

Table 13. Example of chain of thought with a single prompt

Chain of Thought (CoT) can be used in a variety of application scenarios. For example, in code generation, breaking down requirements into multiple steps and mapping those steps to specific lines of code. Or when creating synthetic data, based on seed information such as "the product name is XYZ", write an explanatory description that guides the model to make assumptions based on a given product title. In general, any task that can be solved through "step-by-step elaboration" is suitable for using chain of thought. If you can explain the steps to solve a problem, you can try using the chain of thought method.

Please refer to notebook10 in the GoogleCloudPlatform Github repository; this document will explain the chain of thought prompting technique in detail.

In the best practices section of this chapter, we will learn some best practices specific to chain of thought prompting.

Self-consistency

Although large language models (LLMs) have achieved remarkable success in various NLP tasks, their reasoning ability is still regarded as a limitation that cannot be overcome merely by scaling up model size. As we learned in the Chain of Thought prompting section earlier, the model can be prompted to generate reasoning steps just as humans do when solving problems. However, CoT uses a simple "greedy decoding" strategy, which limits its effectiveness. The self-consistency method combines sampling and a majority voting mechanism, improving the accuracy and coherence of LLM-generated responses by generating diverse reasoning paths and selecting the most consistent answer.

The self-consistency method is implemented through the following steps:

  • Generate diverse reasoning paths: provide the same prompt to the LLM multiple times, and by setting a higher temperature parameter, encourage the model to generate different reasoning paths and perspectives for the question.
  • Extract the answer from each generated response.
  • Select the answer that appears most frequently.

Let's look at an example of an email classification system that needs to classify emails as "important" or "not important". We will send a zero-shot chain of thought prompt to the LLM multiple times and observe whether the response differs after each submission. Note the friendly tone, word choices, and sarcastic expressions used in the emails, all of which may mislead the LLM.

You can use the above prompt to test whether it returns consistent classification results. Depending on the model used and the temperature parameter configuration, the system may return either "IMPORTANT" or "NOT IMPORTANT".

By generating multiple Chains of Thoughts and selecting the most frequently occurring answer ("IMPORTANT"), we can obtain a more consistent and correct answer from the large language model (LLM).

This example shows how self-consistency prompting improves the accuracy of LLM responses by considering multiple perspectives and selecting the most consistent answer.

Tree of Thoughts (ToT)

Now that we are familiar with chain of thought and self-consistency prompting, let us review the Tree of Thoughts (ToT). It generalizes the concept of chain of thought prompting because it allows the LLM to explore multiple different reasoning paths simultaneously, rather than following only a single linear chain of thought. This is shown in Figure 1.

Prompt Engineering

Figure 1. On the left is a visualization of chain-of-thought prompting, and on the right is a tree diagram of tree-of-thought prompting

This approach makes ToT particularly suitable for complex tasks that require exploration. It is implemented by maintaining a tree of thoughts, in which each thought represents a coherent language sequence that serves as an intermediate step toward solving the problem. The model can then explore different reasoning paths by branching out from different nodes in the tree.

There is a good note that introduces the Tree of Thought (ToT) method in detail, which is based on the paper "Tree of Thoughts: Deliberate Problem Solving with Large Language Models" (Large Language Model Guided Tree-of-Thought)。

ReAct (Reasoning and Acting)

Reasoning and Acting (ReAct) prompting is a paradigm that enables large language models (LLMs) to solve complex tasks by combining natural language reasoning with external tools (search, code interpreters, etc.), allowing the LLM to perform certain actions, such as interacting with external APIs to retrieve information, which is the first step toward agent modeling.

ReAct imitates how humans operate in the real world, that is, we reason through language and can take actions to obtain information. In various domains, ReAct outperforms other prompt engineering methods.

ReAct prompting works by combining reasoning and action into a "thought-action" loop. The LLM first reasons about the problem and generates an action plan, then executes the actions in the plan and observes the results. The LLM then uses these observations to update its reasoning and generate a new action plan. This process continues until the LLM finds a solution to the problem.

To see this process in practice, you need to write some code. In Code Snippet 1, I used Python's langchain framework, as well as VertexAI (google-cloud-aiplatform) and the google-search-results pip package.

To run this example, you must create a (free) SerpAPI key fromhttps://serpapi.com/manage-api-keyand set the environment variable SERPAPI_API_KEY。

Nextletus,writeapieceofcodesegmentPythoncodecode,tasktaskisto havelargelanguagelanguagemodelmodel(LLM)findfind:How many children have fathers who are members of the famous band Metallica?

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import VertexAI

prompt = "How many kids do the band members of Metallica have?"

llm = VertexAI(temperature=0.1)
tools = load_tools(["serpapi"], llm=llm)

agent = initialize_agent(tools, llm,
                        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run(prompt)

Code snippet 1. Creating a ReAct agent using LangChain and VertexAI

Code snippet 2 shows the result. Note that ReAct performed five consecutive searches. In effect, the LLM identified the band name by scraping Google search results, then listed the results as observations and chained the reasoning process for the next search.

> Entering new AgentExecutor chain...
Metallica has 4 members.
Action: Search
Action Input: How many kids does James Hetfield have?
Observation: three children
Thought: 1/4 Metallica band members have 3 children
Action: Search
Action Input: How many kids does Lars Ulrich have?
Observation: 3
Thought: 2/4 Metallica band members have 6 children
Action: Search
Action Input: How many kids does Kirk Hammett have?
Observation: Hammett has been married to his second wife Lani since 1998. They have two sons, Angel (b. September 29, 2006) and Vincenzo (b. June 28, 2008).
Thought: 3/4 Metallica band members have 8 children
Action: Search
Action Input: How many kids does Robert Trujillo have?
Observation: 2
Thought: 4/4 Metallica band members have 10 children
Final Answer: 18

Code snippet 2. Executing the ReAct agent in the terminal

Code snippet 2 first determines that the band Metallica has four members, then searches for each member to obtain their number of children and accumulates them, ultimately returning the total number of children as the answer.

In practical applications, the ReAct prompt needs to continuously resend the previous prompt/response (with pruning of additional generated content), configuring appropriate examples and instructions for the model.

For detailed implementation methods, refer to the notebook14 document in the GoogleCloudPlatform Github repository, which demonstrates the actual input-output process of the LLM through a more complete example.

Automatic Prompt Engineering

At this point you may have realized that writing prompts can be quite complex. Wouldn't it be great if this work could be automated (writing prompts that generate prompts)? In fact, such a method does exist: Automatic Prompt Engineering (APE). This method not only reduces the need for manual input but also improves the model's performance across various tasks.

You need to have the model generate more prompts. Evaluate these prompts and modify the ones that work well. Then repeat this process.

For example, when developing a chatbot for a merchandise T-shirt online store, automatic prompt engineering techniques can be used to collect various possible ways customers might express purchasing band merchandise T-shirts. The specific implementation steps are as follows:

  • Write a prompt that will generate output variants. In this example, I use gemini-pro to generate 10 instructions. See Table 15:
Prompt We have a band merchandise t-shirt webshop, and to train a chatbot we need various ways to order: “One Metallica t-shirt size S”. Generate 10 variants, with the same semantics but keep the same meaning.
Output
  1. I would like to buy a small Metallica T-shirt.
  2. Can I order a small Metallica T-shirt?
  3. I want to buy a small Metallica T-shirt.
  4. Please provide a small Metallica shirt.
  5. I want a small Metallica T-shirt.
  6. I would like to order a small Metallica T-shirt.
  7. Please provide a small Metallica T-shirt, just one.
  8. I am looking for a small Metallica T-shirt.
  9. Can you get me a small Metallica T-shirt?
  10. Please provide a small Metallica T-shirt.

Table 15. Using LLM to generate prompts

  • Score and evaluate all instruction candidates by selecting metrics, for example, you can use BLEU (Bilingual Evaluation Understudy) or ROUGE (Recall-Oriented Understudy for Gisting Evaluation).
  • Select the highest-scoring instruction candidate. This candidate will become the final prompt you can use in a software application or chatbot. You can also adjust the selected prompt and evaluate it again.

Code prompts

Gemini mainly focuses on text-based prompts, which also includes writing prompts used to return code. Let's go into Vertex AI Studio to test these prompts and look at some code examples.

  • Writing code prompts

Gemini can also act as a developer, helping you write code in the programming language of your choice. As a developer, this can accelerate your coding process.

Imagine you have a folder on your machine containing hundreds of files that need to be renamed. Renaming the files one by one would take a lot of time. You know some Bash commands and can write a script to automate it, but that might also take some time. So, let's write a prompt. You can write the prompt in the public Gemini chatbot, or if you are more concerned about confidentiality, you can open Vertex AI Studio in your Google Cloud account to write these prompts. The advantage of Vertex AI Studio is that you can configure parameters such as temperature.

Name 1.bash_rename_files_in_folder
Goal Writeaprompt,Requestgenerateforuse inrenamingfilesfolderinsidefiles'sBashscriptcodeCodecode。
Model gemini-pro
Temperature 0.1
Token limit 1024
Top-K N/A
Top-P 1
Prompt Write a code snippet in Bash, which asks for a folder name. Then it takes the contents of the folder and renames all the files inside by prepending the name draft to the file name.
Output

“`bash

#!/bin/bash

# Ask for the folder name

echo “Enter the folder name: “

read folder_name

# Check if the folder exists

if [ ! -d “$folder_name” ]; then

echo “Folder does not exist.”

exit 1

fi

# Get the list of files in the folder

files=( “$folder_name”/* )

# Rename each file by prepending “draft” to the file name

for file in “${files[@]}”; do

new_file_name=”draft_$(basename “$file”)”

mv “$file” “$new_file_name”

done

echo “Files renamed successfully.”

“`

Table 16: Writing code with Gemini

Thispiece ofcodecodelookscomesnotbad.Eventoalsohascomments!Howeveroverdue toatlargelargelanguagemodelmodeldoes notpossesshavetruegenuine'sreasoningreasoningcapabilityability,andwillrepeatrepeattrainingtrainingdatadata,thereforethereforemustmustfirstcarefullycarefullyreadreadandtesttestyouryourcodecode。

Let's try using a test folder containing just a few files that need to be renamed from filename.txt to draft_filename.txt.

  • Copy the output from Table 16 (excluding the "`bash “` text wrapper), and paste it into a new file named "rename_files.sh".
  • Open a terminal window and type: . rename_files.sh. It will ask for the folder name, for example test. Then press Enter.
  • The script runs correctly. You will see the message: File renamed successfully. When you look at the test folder, note that all files have been fully renamed to draft_filename.txt.
  • Explain the code prompt

As developers, in team collaboration we often need to read code written by others. Gemini can also help you in this regard. Taking the code output in Table 16 as an example, we first remove the comments from it, and then ask the large language model to explain the code logic, as shown in Table 17:

Name 1.bash_explain_the_code
Objective Write a prompt that explains Bash code
Model gemini-pro
Temperature 0.1
Token limit 1024
Top-K N/A
Top-P 1
Prompt

Explain to me the below Bash code:

“`

#!/bin/bash

echo “Enter the folder name: “

read folder_name

if [ ! -d “$folder_name” ]; then

echo “Folder does not exist.”

exit 1

fi

files=( “$folder_name”/* )

for file in “${files[@]}”; do

new_file_name=”draft_$(basename “$file”)”

mv “$file” “$new_file_name”

done

echo “Files renamed successfully.”

“`

Output

This Bash script performs the following operations:

  1. User input:
  • Useechoandreadcommands to prompt the user to enter a folder name; the entered folder name is stored infolder_namevariable
  1. Folder existence check:
  • Use[ ! -d "$folder_name" ]conditional check to determine whether the specified folder exists
  • If the folder does not exist, display an error message ("Folder does not exist.") and terminate the script with exit code 1
  1. File list retrieval:
  • Usefiles=("$folder_name"/*)command to list all files in the specified folder
  • Create an array namedfilescontaining the paths of all files in that folder
  1. File renaming:
  • Useforloop to iterate overfileseach file in the array
  • For each file, usenew_file_name="draft_$(basename "$file")"command to generate a new file name (add the "draft_" prefix before the original file name)
  • Usemv "$file" "$new_file_name"command to complete the file renaming operation
  1. Success message:
  • After completing the renaming of all files, display a success message ("Files renamed successfully.") indicating that the renaming operation has completed successfully

Table 17. Prompt for explaining code

  • Prompt for code translation

The Bash code in Table 16 looks like it runs well. But the script would be more reusable if it prompted for the file name, and ideally it should run as a standalone application with a UI. As a starting point, Python is better suited than Bash for developing (web) applications. Large language models can help with code conversion between different programming languages. See Table 18 for a concrete example:

Name 1.python_rename_files
Goal Write a prompt to translate Bash code into Python
Model gemini-pro
Temperature 0.1
Token limit 1024
Top-K N/A
Top-P 1
Prompt

Translate the below Bash code to a Python snippet.

“`bash

#!/bin/bash

echo “Enter the folder name: “

read folder_name

if [ ! -d “$folder_name” ]; then

echo “Folder does not exist.”

exit 1

fi

files=( “$folder_name”/* )

for file in “${files[@]}”; do

new_file_name=”draft_$(basename “$file”)”

mv “$file” “$new_file_name”

done

echo “Files renamed successfully.”

“`

Output

“`python

import os

import shutil

# Get the folder name from the user

folder_name = input(“Enter the folder name: “)

# Check if the folder exists

if not os.path.isdir(folder_name):

print(“Folder does not exist.”)

exit(1)

files = os.listdir(folder_name)

# Iterate over the files

for file in files:

# Create a new file name with the prefix “draft_”

new_file_name = f”draft_{file}”

# Move the file to the new name

shutil.move(os.path.join(folder_name, file),

os.path.join(folder_name, new_file_name))

# Print a success message

print(“Files renamed successfully.”)

“`

Table 18. Code translation prompt from Bash to Python

Read and review the code. Copy and paste the output generated by the prompt into a new file: file_renamer.py. Test the code by opening a terminal window and running the following command: python file_renamer.py.

Note: When requesting (Python) code in Vertex AI's Language Studio, you need to click the "Markdown" button. Otherwise you will get the code in plain text format, lacking the correct indentation needed to run Python.

  • Prompt for debugging and reviewing code

Let's manually make some edits to the code in Table 18. It should prompt the user for a file name prefix and write that prefix in uppercase. See the example code in Snippet 3, but now a Python error occurs!

import os
import shutil

folder_name = input("Enter the folder name: ")
prefix = input("Enter the string to prepend to the filename: ")
text = toUpperCase(prefix)

if not os.path.isdir(folder_name):
    print("Folder does not exist.")
    exit(1)

files = os.listdir(folder_name)
for file in files:
    new_filename = f"{text}_{file}"
    shutil.move(os.path.join(folder_name, file), os.path.join(folder_name, new_filename))

print("Files renamed successfully.")

Snippet 3: A buggy Python script

Thislookslikeabug:bug:

The below Python code gives an error:

Traceback (most recent call last):
  File "/Users/leeboonstra/Documents/test_folder/rename_files.py", line 7, in <module>
    text = toUpperCase(prefix)
NameError: name 'toUpperCase' is not defined

Snippet44:Python:PythoncodeexecutionexceptionOften

  • About multimodal prompting

Let's see if we can get a large language model to debug and review code. Please see Table 19:

Name 1_python_debug_code
Goal Write a prompt for debugging and reviewing Python code.
Model gemini-pro
Temperature 0.1
Token Limit 1024
Top-K N/A
Top-P 1
Prompt

The below Python code gives an error:

Traceback (most recent call last):

File “/

Users/leeboonstra/Documents/test_folder/rename_files.py”, line

7, in <module>

text = toUpperCase(prefix)

NameError: name ‘toUpperCase’ is not defined

Debug what’s wrong and explain how I can improve the code.

“`python

import os

import shutil

# Get the folder name from the user

folder_name = input(“Enter the folder name: “)

prefix = input(“Enter the string to prepend to the filename: “)

text = toUpperCase(prefix)

# Check if the folder exists

if not os.path.isdir(folder_name):

print(“Folder does not exist.”)

exit(1)

# Get a list of all files in the folder

files = os.listdir(folder_name)

# Iterate over the files

for file in files:

# Create a new file name with the prefix “draft_”

new_filename = f”{text}_{file}”

# Move the file to the new name

shutil.move(os.path.join(folder_name, file),

os.path.join(folder_name, new_file_name))

# Print a success message

print(“Files renamed successfully.”)

Output

The code calls the `toUpperCase` function to convert `pre x` to uppercase, but that function is undefined. To fix this issue, you can use the`upper()` method. A string class that converts a given string to uppercase. The modified code is shown below:

“`python

import os

import shutil

# Get the folder name from the user

folder_name = input(“Enter the folder name: “)

prefix = input(“Enter the string to prepend to the filename: “)

text = prefix.upper()

# Check if the folder exists

if not os.path.isdir(folder_name):

print(“Folder does not exist.”)

exit(1)

# Get a list of all files in the folder

files = os.listdir(folder_name)

# Iterate over the files

for file in files:

# Create a new file name with the prefix “draft_”

new_filename = f”{text}_{file}”

# Move the file to the new name

shutil.move(os.path.join(folder_name, file),

os.path.join(folder_name, new_filename))

# Print a success message

print(“Files renamed successfully.”)

“`

Additionally, there are a few other improvements that can be made to the code:

  1. The file extension of the new filenames is not kept. It’s better to extract the

extension from the original filename and append it to the new filename.

  1. The code assumes that there are no spaces in the folder name. However,

it is a good practice to handle spaces gracefully by replacing them with

underscores or hyphens.

  1. Using the `f` string syntax for string interpolation is more readable and

concise than the traditional `+` operator.

  1. The code doesn’t handle errors that might occur during the renaming process.

It would be better to wrap the `shutil.move` call in a `try…except` block to

catch any potential errors.

Here is the improved code with these suggestions:

“`python

import os

import shutil

# Get the folder name from the user

folder_name = input(“Enter the folder name: “)

prefix = input(“Enter the string to prepend to the filename: “)

# Check if the folder exists

if not os.path.isdir(folder_name):

print(“Folder does not exist.”)

exit(1)

# Get a list of all files in the folder

files = os.listdir(folder_name)

# Iterate over the files

for file in files:

# Get the file extension

ext = os.path.splitext(file)[1]

# Create a new file name with the prefix and the file extension

new_filename = f”{prefix}_{os.path.splitext(file)[0]}{ext}”

# Build the full paths for the original and new files

old_path = os.path.join(folder_name, file)

new_path = os.path.join(folder_name, new_filename)

# Try to move the file

try:

shutil.move(old_path, new_path)

except Exception as e:

print(f”An error occurred while moving the file

{file}: {e}”)

# Print a success message

print(“Files renamed successfully.”)

“`

These improvements make the code more robust and flexible, while also improving readability and understandability... (The response was truncated because the token limit was reached. For a complete answer, please try increasing the token limit.)

Table 19. Prompts for debugging and reviewing Python code

Great. It not only told me how to solve the problem, but also found more errors in my code and how to fix them. The last part of the prompt gave general suggestions for improving the code.

  • About multimodal prompting

Code prompting still uses conventional large language models. Multimodal prompting is a different concept; it refers to the technique of using multiple input formats (not just text) to guide a large language model. Depending on the model's capabilities and the specific task requirements, this may include a combination of text, images, audio, code, or other formats.

Best practices

Finding the right prompt requires repeated debugging. Language Studio in Vertex AI is an ideal environment for testing prompts, where you can validate them using different models.

Follow these best practices, and you will become a prompt engineering expert:

Provide examples

The most important best practice is to include examples (one-shot/few-shot) in the prompt. This approach is very effective because it serves as a powerful teaching tool. These examples show the desired output or similar responses, enabling the model to learn from them and adjust its generated content accordingly. It is like providing the model with a reference target, thereby improving the accuracy, style, and tone of its responses to better match your expectations.

Keep the design simple

Prompts should be concise, clear, and easy to understand (both for you and for the model). As a rule of thumb, if you find it confusing yourself, the model will likely be confused too. Try to avoid complex language and do not provide unnecessary information.

Example:

  • Before rewriting:"I am currently traveling in New York and want to learn about some good places to go. I have two 3-year-old children with me. Where should we go on vacation?"
  • Rewritten: "Play the role of a travel guide. Recommend tourist attractions in Manhattan, New York suitable for 3-year-old children."

It is recommended to use action verbs:

Act, analyze, classify, contrast, compare, create, describe, define, evaluate, extract, find, generate, identify, list, measure, organize, parse, select, predict, provide, sort, recommend, return, retrieve, rewrite, choose, display, rank, summarize, translate, write.

Specify output requirements

Be specific about the expected output. Concise instructions may not provide enough guidance for a large language model, or may be too general. Providing specific details in the prompt (through system prompts or contextual prompts) can help the model focus on relevant content and improve overall accuracy.

Example:

  • Correct approach: "Generate a 3-paragraph blog post introducing the top 5 video game consoles. The article should be informative, engaging, and written in a conversational style."
  • Incorrect approach: "Generate a blog post about video game consoles."

Prefer instructions over constraints

In prompt engineering, instructions and constraints work together to guide the output of large language models (LLMs):

  • Instructions: Clearly require the format, style, or specific content that the response should follow. Their role is to guide the model on "how to generate" the content.
  • Constraints: Set the boundaries and prohibitions for the response content. Their role is to restrict the scope of content the model "must not involve."

A growing body of research shows that in prompt engineering, focusing on positive guidance is more effective than relying excessively on constraints. This approach aligns with the human psychological trait of preferring positive guidance over lists of prohibitions.

Guidance directly conveys the desired outcome, whereas constraints may leave the model guessing what is permitted. It provides flexibility within defined boundaries and encourages creativity, whereas constraints may limit the model's potential. In addition, lists of constraints may conflict with one another.

Constraints still have value in certain situations, such as when it is necessary to prevent the model from generating harmful or biased content, or when a strict output format or style is required.

Where possible, use positive guidance: rather than telling the model what not to do, tell it what it should do. This avoids confusion and improves output accuracy.

  • Correct approach: Generate a blog paragraph about the top 5 video game consoles. Discuss only the consoles, manufacturers, release years, and total sales.
  • Incorrect approach: Generate a blog paragraph about the top 5 video game consoles. Do not list game names.

As a best practice, you should first prioritize instructions, clearly stating what you want the model to do, and use constraints only when necessary for safety, clarity, or specific requirements. Experiment and iterate, testing different combinations of instructions and constraints to find the approach that best suits your specific task, and record this information.

Controlthe maximumtokenlengthTo

TocontrolLLMthegeneratedresponse'slength,,inthe configuration,setthe maximumlimittokenrestriction,orinthe promptexplicitlyrequestaspecificspecificlengthlength。

For exampleFor example: “Useasingletweetlengthoflengthlengthto explainexplainquantumquantumphysicsphysicsphysics。“

Use variables in prompts

To reuse prompts and make them more dynamic, you can use variables in prompts, which can be changed based on different inputs. For example, as shown in Table 20, a prompt that provides city-related information. Instead of hardcoding the city name in the prompt, use a variable. By using variables, you can avoid repetitive work, thereby saving time and effort. If you need to use the same information in multiple prompts, you can store it in a variable and then reference that variable in each prompt. This practice makes a lot of sense when integrating prompts into your own applications.

Prompt

VARIABLES

{city} = “Amsterdam”

PROMPT

You are a travel guide. Tell me a fact about the city: {city}

Output Amsterdam is a beautiful city with canals, bridges, and narrow streets. It is an excellent tourist destination with rich history, deep culture, and abundant nightlife.

Table 20. Using variables in prompts

Try different input formats and writing styles

Different models, model configurations, prompt formats, wording choices, and submission methods may produce different results. Therefore, it is necessary to experiment with prompt attributes, including style, wording, and prompt type (zero-shot, few-shot, system prompt).

For example, to generate text about the revolutionary game console Sega Dreamcast, it can be expressed in the following different forms, thereby producing different outputs:

  • Question form: What is the Sega Dreamcast? Why is it a revolutionary game console?
  • Statement form: The Sega Dreamcast is a sixth-generation game console released by Sega in 1999. It...
  • Instruction form: Write a paragraph describing the Sega Dreamcast game console and explain why it is so revolutionary.

Tips for few-shot prompting classification tasks

For few-shot prompting classification tasks, samples from different categories should be mixed.

Generally speaking, the order of few-shot examples has little effect. But in classification tasks, make sure to mix different response categories in the few-shot examples. Otherwise, the model may overfit to a specific example order. By mixing the possible response categories, you can ensure that the model learns to recognize the key features of each category, rather than simply memorizing the example order. This will make the model more robust and generalizable on unseen data.

A good rule of thumb is to start with 6 few-shot examples and test the accuracy.

Adapt to model updates

You must stay up to date with model architecture changes, new data, and feature updates. Try using newer model versions and adjust your prompts to better leverage the new model's features. Tools like Vertex AI Studio are great for storing, testing, and recording different versions of prompts.

Try different output formats

In addition to the input format of the prompt, you should also try different output formats. For non-creative tasks such as data extraction, selection, parsing, sorting, ranking, or classification, you can try having the output returned in a structured format (such as JSON or XML).

Returning JSON objects from prompts has the following advantages: in real applications, there is no need to manually create the JSON format, and data can be returned directly in sorted order (especially convenient when handling date-time objects). Most importantly, by requiring JSON format, you can force the model to generate structured output, reducing the generation of hallucinated content.

In summary, the benefits of using JSON as the output format:

  • Always return data in a consistent format
  •  Precisely focus on the target data content
  • ReduceReduce 
  • Maintai 
  • nAutomaticallyObtainDataDataTypes 
  • SupportSortingSortingSortingSortingSorting

In the few-shot prompting section, Table 4 shows an example of how to return structured output.

JSON Repair

Although returning data in JSON format has many advantages, it also has some drawbacks. While the structured nature of JSON is beneficial for parsing and application integration, it consumes more tokens than plain text, which leads to increased processing time and higher costs. In addition, the verbosity of JSON can easily fill up the entire output window, and this problem is especially prominent when the generated content is abruptly truncated due to token limits. Such truncation often results in invalid JSON format—missing key closing braces or brackets—making the output unusable. Fortunately, tool libraries like json-repair (available via PyPI) are very useful in this situation. This library can intelligently attempt to automatically repair incomplete or malformed JSON objects, making it an important tool when handling JSON data generated by large language models, and it is especially effective in dealing with possible truncation issues.

Usage Patterns

As mentioned many times in this article, using structured JSON as output is a great solution. But what about input? While JSON is very suitable for structuring the output generated by LLMs, it is equally useful for structuring the input data you provide. This is where JSON Schema comes into play. JSON Schema defines the expected structure and data types of your input JSON data. By providing a schema, you give the LLM a clear data blueprint, helping it focus on relevant information and reducing the risk of misunderstanding the input. In addition, the schema can help establish relationships between different pieces of data, and even give the LLM a sense of "time awareness" by including date or timestamp fields in specific formats.

A simple example: let's assume you want to use a large language model (LLM) to generate descriptions for products in an e-commerce catalog. In addition to providing a text description of the product, you can also use a JSON schema to define the product's attributes:

{
  "type": "object",
  "properties": {
    "name": { "type": "string", "description": "Product name" },
    "category": { "type": "string", "description": "Product category" },
    "price": { "type": "number", "format": "float", "description": "Product price" },
    "features": {
      "type": "array",
      "items": { "type": "string" },
      "description": "Key features of the product"
    },
    "release_date": { "type": "string", "format": "date", "description": "Date the product was released" }
  }
}

Code snippet 5. Definition of the structured output schema

Then, you can provide actual product data that conforms to this schema as a JSON object:

{
  "name": "Wireless Headphones",
  "category": "Electronics",
  "price": 99.99,
  "features": ["Noise cancellation", "Bluetooth 5.0", "20-hour battery life"],
  "release_date": "2023-10-27"
}

Code Snippet 6. Formatted Output of the LLM

By preprocessing the data and providing only the schema and data rather than the full document, you can explicitly show the large language model each attribute of the product (including the release date), thereby greatly improving the accuracy and relevance of the generated description. This structured input approach precisely guides the large language model to focus on key fields, which is especially important when processing massive amounts of data or integrating the large language model into complex applications.

Prompt Engineer Collaborative Experimentation Protocol

When high-quality prompts need to be developed, it is recommended to form a multi-person collaborative team. Provided that all members follow the best practices in this chapter, you will observe performance differences among different prompt approaches.

CoT Best Practices

The answer must be placed after the reasoning process, because the generation of the reasoning process changes the tokens the model receives when predicting the final answer.

When using CoT and self-consistency methods, it is necessary to be able to extract the final answer from the prompt and separate it from the reasoning process.

For CoT prompting, the temperature parameter should be set to 0.

Chain-of-thought prompting is based on a greedy decoding strategy, that is, predicting the next word in the sequence according to the highest probability assigned by the language model. Generally speaking, when reasoning is used to arrive at a final answer, there is very likely only one correct answer. Therefore the temperature parameter should always be set to 0.

Record Prompt Attempts in Detail

Although this was mentioned earlier in this chapter, we must emphasize its importance again: record your prompt attempts fully and in detail, so that you can continuously understand which methods work and which do not.

Prompt outputs may differ across different models, different sampling settings, and different versions of the same model. In addition, even with the same prompt on the same model, there may be subtle differences in the sentence structure and word choice of the output. (For example, as mentioned earlier, if two tokens have the same predicted probability, the tie may be broken randomly. This may affect subsequent predicted tokens.)

We recommend creating a Google Sheet for recording according to the template in Table 21. The advantage of this approach is that when you inevitably need to revisit your prompt engineering work (whether to continue this work in the future, test prompt performance across different model versions, or debug errors that arise in the future), you will have a complete record, and you will be surprised to find how many details you forget even after only a brief interruption.

In addition to the fields in the table, fields for tracking prompt versions (iterations), recording whether the results are OK/NOT OK/SOMETIMES OK, and recording feedback are also very helpful. If you use VertexAI Studio, save your prompts (using the same names and versions listed in the document), and track the hyperlinks to the saved prompts in the table. This way, you can rerun your prompts with just one click.

When working with a retrieval augmented generation system, you should also capture the specific aspects of the RAG system that affect how content is inserted into the prompt, including the query, chunk settings, chunk output, and other information.

As prompts mature, they should be migrated to the project codebase. In the codebase, prompts should be stored separately from the business code for maintainability. Ultimately, the ideal prompt should become part of an operational system, and as a prompt engineer, you should rely on automated testing and evaluation processes to verify the prompt's ability to generalize to the task.

Prompt engineering is an iterative process. You need to continuously design and test different prompts, analyze and record the results, refine the prompts based on model performance, and keep experimenting until you get the desired output. When changing models or adjusting configurations, you should retest the prompt approaches you used previously.

Name [ Your prompt name and version ]
Model [Brief description of the goal of this prompt engineering effort]
Temperature [value between 0 – 1]
Top-K [ Number ]
Token limit [ Number ]
Top-P [ Number]
Prompt [Write out the full prompt]
Output [ output or multiple outputs ]

Table 21. Template for recording prompts

Summary

This whitepaper discussed prompt engineering. We learned about various prompting techniques, such as:

  • Zero-shot prompting
  • Few-shot prompting
  • System prompting
  • Role prompting
  • Contextual prompting
  • Step-back prompting
  • Chain of Thought
  • Self-Consistency
  • Tree of Thoughts
  • ReAct

We even studied how to automate prompting methods.

The whitepaper then discusses the challenges of generative AI, such as the problems that can arise when your prompts are insufficient. We conclude with best practices on how to become a better prompt engineer.

References

  1. Google, 2023, "Gemini: Google's Multimodal AI System" Online access:https://gemini.google.com
  2. Google, 2024, "Gemini Prompting Guide in Google Workspace" Online access: https://inthecloud.withgoogle.com/gemini-for-google-workspace-prompt-guide/dl-cd.html
  3. Google Cloud, 2023, "Introduction to Prompt Engineering Guide" Online access: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/introduction-prompt-design
  4. Google Cloud, 2023, "Text Model Request Body: Top-P and top-K Sampling Methods" Online access: https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text#request_body
  5. Wei, J. et al., 2023, "Zero-Shot Learning: Zero-Shot Capabilities of Fine-Tuned Language Models" Online access: https://arxiv.org/pdf/2109.01652.pdf
  6. Google Cloud, 2023, "Google Cloud Model Garden" Online access:https://cloud.google.com/model-garden
  7. Brown, T. et al., 2023, "Few-Shot Learning: Few-Shot Capabilities of Language Models" Online access: https://arxiv.org/pdf/2005.14165.pdf
  8. Zheng, L. et al., 2023, "Take a Step Back: Eliciting Reasoning in Large Language Models through Abstraction" Online access: https://openreview.net/pdf?id=3bq3jsvcQ1
  9. Wei, J. et al., 2023, "Chain-of-Thought Prompting Method" Online access:https://arxiv.org/pdf/2201.11903.pdf
  10. Google Cloud Platform, 2023, "Chain of Thought and ReAct in Practice" Online access:https://github.com/GoogleCloudPlatform/generative-ai/blob/main/language/prompts/examples/chain_of_thought_react.ipynb
  11. Wang, X. et al., 2023, "Self-Consistency Improves Chain-of-Thought Reasoning in Language Models" Online access: https://arxiv.org/pdf/2203.11171.pdf
  12. Yao, S. et al., 2023, "Tree of Thoughts: Systematic Problem Solving with Large Language Models" Online access: https://arxiv.org/pdf/2305.10601.pdf
  13. Yao, S. et al., 2023, "ReAct: Synergizing Reasoning and Acting in Language Models" Online access: https://arxiv.org/pdf/2210.03629.pdf
  14. Google Cloud Platform, 2023, "Advanced Prompting Techniques: Chain of Thought and ReAct" Online access: https://github.com/GoogleCloudPlatform/applied-ai-engineering-samples/blob/main/genaion-vertex-ai/advanced_prompting_training/cot_react.ipynb
  15. Zhou, C. et al., 2023, "Automatic Prompt Engineering: Human-Level Prompt Generation Capabilities of Large Language Models" Online access: https://arxiv.org/pdf/2211.01910.pdf
CakeGrowth QR code

Get"Prompt Engineering" Whitepaper  Original PDF file, scan the QR code, follow, and reply: 20250411