Chapter 6 · Prompt Engineering
Chapter goals: Systematically master methods for improving model output through prompt engineering — from basic prompt elements to Chain-of-Thought, Tree-of-Thought reasoning, and finally constrained sampling and output validation.
6.1 Preparation
💡 NOTE: Running the examples in this chapter requires a GPU. If using Google Colab, switch to Runtime > Change runtime type > Hardware accelerator > GPU > GPU type > T4.
In Colab (or other cloud environments), you need to uncomment and run the code block below to install the dependencies for this chapter:
# %%capture
# !pip install langchain>=0.1.17 openai>=1.13.3 langchain_openai>=0.1.6 transformers>=4.40.1 datasets>=2.18.0 accelerate>=0.27.2 sentence-transformers>=2.5.1 duckduckgo-search>=5.2.2
# !CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python6.2 Loading the Model
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
# Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
"microsoft/Phi-3-mini-4k-instruct",
device_map="cuda",
torch_dtype="auto",
trust_remote_code=False,
)
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
# Create a pipeline
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
return_full_text=False,
max_new_tokens=500,
do_sample=False,
)Test model generation with a simple prompt:
# Prompt
messages = [
{"role": "user", "content": "Create a funny joke about chickens."}
]
# Generate the output
output = pipe(messages)
print(output[0]["generated_text"])Inspect what the actual prompt text looks like after the chat template is applied:
# Apply prompt template
prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False)
print(prompt)Try sampling with a higher temperature:
# Using a high temperature
output = pipe(messages, do_sample=True, temperature=1)
print(output[0]["generated_text"])Then try a higher top_p:
# Using a high top_p
output = pipe(messages, do_sample=True, top_p=1)
print(output[0]["generated_text"])6.3 Introduction to Prompt Engineering
Basic Elements of a Prompt
A well-structured prompt is typically composed of several "elements": persona, instruction, context, data format, audience, and tone — the complex prompt in the next section demonstrates each of these elements in turn.
6.4 Advanced Prompt Engineering
Complex Prompt
The example text below for summarization is borrowed from https://jalammar.github.io/illustrated-transformer/ :
# Text to summarize which we stole from https://jalammar.github.io/illustrated-transformer/ ;)
text = """In the previous post, we looked at Attention – a ubiquitous method in modern deep learning models. Attention is a concept that helped improve the performance of neural machine translation applications. In this post, we will look at The Transformer – a model that uses attention to boost the speed with which these models can be trained. The Transformer outperforms the Google Neural Machine Translation model in specific tasks. The biggest benefit, however, comes from how The Transformer lends itself to parallelization. It is in fact Google Cloud's recommendation to use The Transformer as a reference model to use their Cloud TPU offering. So let's try to break the model apart and look at how it functions.
The Transformer was proposed in the paper Attention is All You Need. A TensorFlow implementation of it is available as a part of the Tensor2Tensor package. Harvard's NLP group created a guide annotating the paper with PyTorch implementation. In this post, we will attempt to oversimplify things a bit and introduce the concepts one by one to hopefully make it easier to understand to people without in-depth knowledge of the subject matter.
Let's begin by looking at the model as a single black box. In a machine translation application, it would take a sentence in one language, and output its translation in another.
Popping open that Optimus Prime goodness, we see an encoding component, a decoding component, and connections between them.
The encoding component is a stack of encoders (the paper stacks six of them on top of each other – there's nothing magical about the number six, one can definitely experiment with other arrangements). The decoding component is a stack of decoders of the same number.
The encoders are all identical in structure (yet they do not share weights). Each one is broken down into two sub-layers:
The encoder's inputs first flow through a self-attention layer – a layer that helps the encoder look at other words in the input sentence as it encodes a specific word. We'll look closer at self-attention later in the post.
The outputs of the self-attention layer are fed to a feed-forward neural network. The exact same feed-forward network is independently applied to each position.
The decoder has both those layers, but between them is an attention layer that helps the decoder focus on relevant parts of the input sentence (similar what attention does in seq2seq models).
Now that we've seen the major components of the model, let's start to look at the various vectors/tensors and how they flow between these components to turn the input of a trained model into an output.
As is the case in NLP applications in general, we begin by turning each input word into a vector using an embedding algorithm.
Each word is embedded into a vector of size 512. We'll represent those vectors with these simple boxes.
The embedding only happens in the bottom-most encoder. The abstraction that is common to all the encoders is that they receive a list of vectors each of the size 512 – In the bottom encoder that would be the word embeddings, but in other encoders, it would be the output of the encoder that's directly below. The size of this list is hyperparameter we can set – basically it would be the length of the longest sentence in our training dataset.
After embedding the words in our input sequence, each of them flows through each of the two layers of the encoder.
Here we begin to see one key property of the Transformer, which is that the word in each position flows through its own path in the encoder. There are dependencies between these paths in the self-attention layer. The feed-forward layer does not have those dependencies, however, and thus the various paths can be executed in parallel while flowing through the feed-forward layer.
Next, we'll switch up the example to a shorter sentence and we'll look at what happens in each sub-layer of the encoder.
Now We're Encoding!
As we've mentioned already, an encoder receives a list of vectors as input. It processes this list by passing these vectors into a 'self-attention' layer, then into a feed-forward neural network, then sends out the output upwards to the next encoder.
"""
# Prompt components
persona = "You are an expert in Large Language models. You excel at breaking down complex papers into digestible summaries.\n"
instruction = "Summarize the key findings of the paper provided.\n"
context = "Your summary should extract the most crucial points that can help researchers quickly understand the most vital information of the paper.\n"
data_format = "Create a bullet-point summary that outlines the method. Follow this up with a concise paragraph that encapsulates the main results.\n"
audience = "The summary is designed for busy researchers that quickly need to grasp the newest trends in Large Language Models.\n"
tone = "The tone should be professional and clear.\n"
text = "MY TEXT TO SUMMARIZE" # Replace with your own text to summarize
data = f"Text to summarize: {text}"
# The full prompt - remove and add pieces to view its impact on the generated output
query = persona + instruction + context + data_format + audience + tone + dataInspect what the assembled full prompt looks like after the chat template is applied:
messages = [
{"role": "user", "content": query}
]
print(tokenizer.apply_chat_template(messages, tokenize=False))# Generate the output
outputs = pipe(messages)
print(outputs[0]["generated_text"])In-Context Learning: Providing Examples
Guide the model with a single example of "using a made-up word in a sentence":
# Use a single example of using the made-up word in a sentence
one_shot_prompt = [
{
"role": "user",
"content": "A 'Gigamuru' is a type of Japanese musical instrument. An example of a sentence that uses the word Gigamuru is:"
},
{
"role": "assistant",
"content": "I have a Gigamuru that my uncle gave me as a gift. I love to play it at home."
},
{
"role": "user",
"content": "To 'screeg' something is to swing a sword at it. An example of a sentence that uses the word screeg is:"
}
]
print(tokenizer.apply_chat_template(one_shot_prompt, tokenize=False))# Generate the output
outputs = pipe(one_shot_prompt)
print(outputs[0]["generated_text"])Chain Prompting: Breaking the Problem Apart
Step 1: create a name and slogan for a product:
# Create name and slogan for a product
product_prompt = [
{"role": "user", "content": "Create a name and slogan for a chatbot that leverages LLMs."}
]
outputs = pipe(product_prompt)
product_description = outputs[0]["generated_text"]
print(product_description)Step 2: generate a sales pitch based on the name and slogan from the previous step:
# Based on a name and slogan for a product, generate a sales pitch
sales_prompt = [
{"role": "user", "content": f"Generate a very short sales pitch for the following product: '{product_description}'"}
]
outputs = pipe(sales_prompt)
sales_pitch = outputs[0]["generated_text"]
print(sales_pitch)6.5 Reasoning with Generative Models
Chain-of-Thought: Think Before Answering
Direct answering without explicit reasoning (as a baseline):
# # Answering without explicit reasoning
# standard_prompt = [
# {"role": "user", "content": "Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?"},
# {"role": "assistant", "content": "11"},
# {"role": "user", "content": "The cafeteria had 25 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have?"}
# ]
# # Run generative model
# outputs = pipe(standard_prompt)
# print(outputs[0]["generated_text"])Guide the reasoning process using chain-of-thought examples:
# Answering with chain-of-thought
cot_prompt = [
{"role": "user", "content": "Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?"},
{"role": "assistant", "content": "Roger started with 5 balls. 2 cans of 3 tennis balls each is 6 tennis balls. 5 + 6 = 11. The answer is 11."},
{"role": "user", "content": "The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have?"}
]
# Generate the output
outputs = pipe(cot_prompt)
print(outputs[0]["generated_text"])Zero-shot Chain-of-Thought
No examples — just add "Let's think step-by-step" to the prompt:
# Zero-shot Chain-of-Thought
zeroshot_cot_prompt = [
{"role": "user", "content": "The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have? Let's think step-by-step."}
]
# Generate the output
outputs = pipe(zeroshot_cot_prompt)
print(outputs[0]["generated_text"])Tree-of-Thought: Exploring Intermediate Steps
Have multiple "experts" answer step by step and discuss with each other:
# Zero-shot Chain-of-Thought
zeroshot_tot_prompt = [
{"role": "user", "content": "Imagine three different experts are answering this question. All experts will write down 1 step of their thinking, then share it with the group. Then all experts will go on to the next step, etc. If any expert realises they're wrong at any point then they leave. The question is 'The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have?' Make sure to discuss the results."}
]# Generate the output
outputs = pipe(zeroshot_tot_prompt)
print(outputs[0]["generated_text"])6.6 Output Validation
Constraining Output Format with Examples
Zero-shot: no format examples provided:
# Zero-shot learning: Providing no examples
zeroshot_prompt = [
{"role": "user", "content": "Create a character profile for an RPG game in JSON format."}
]
# Generate the output
outputs = pipe(zeroshot_prompt)
print(outputs[0]["generated_text"])One-shot: provide the exact output structure template:
# One-shot learning: Providing an example of the output structure
one_shot_template = """Create a short character profile for an RPG game. Make sure to only use this format:
{
"description": "A SHORT DESCRIPTION",
"name": "THE CHARACTER'S NAME",
"armor": "ONE PIECE OF ARMOR",
"weapon": "ONE OR MORE WEAPONS"
}
"""
one_shot_prompt = [
{"role": "user", "content": one_shot_template}
]
# Generate the output
outputs = pipe(one_shot_prompt)
print(outputs[0]["generated_text"])Constrained Sampling (Grammar-Constrained)
First free up the GPU memory occupied earlier:
import gc
import torch
del model, tokenizer, pipe
# Flush memory
gc.collect()
torch.cuda.empty_cache()Switch to loading Phi-3's GGUF quantized version via llama.cpp:
from llama_cpp.llama import Llama
# Load Phi-3
llm = Llama.from_pretrained(
repo_id="microsoft/Phi-3-mini-4k-instruct-gguf",
filename="*fp16.gguf",
n_gpu_layers=-1,
n_ctx=2048,
verbose=False
)Force the model to output JSON via response_format:
# Generate output
output = llm.create_chat_completion(
messages=[
{"role": "user", "content": "Create a warrior for an RPG in JSON format."},
],
response_format={"type": "json_object"},
temperature=0,
)['choices'][0]['message']["content"]Format the output for easier inspection:
import json
# Format as json
json_output = json.dumps(json.loads(output), indent=4)
print(json_output)Chapter Summary
- A complex prompt is assembled from elements such as persona, instruction, context, data_format, audience, tone, and data; removing or adding elements lets you observe their impact on output;
- Temperature and top_p control sampling randomness; with
do_sample=Falsethe decoding is deterministic greedy; - In-Context Learning teaches the model to handle uncommon tasks by providing examples (one-shot) in the prompt; chain prompting breaks a large problem into multiple smaller calls, with the output of one step feeding into the next;
- Chain-of-Thought examples with explicit reasoning steps significantly improve performance on math-type problems; zero-shot CoT only needs the phrase "Let's think step-by-step"; Tree-of-Thought has multiple "experts" discuss step by step;
- llama.cpp's
response_format={"type": "json_object"}guarantees the output is valid JSON through grammar-constrained sampling at the token level — more reliable than prompt-only constraints.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. In this chapter's "complex prompt", what is the role of the persona element?
2. What is the key practice of zero-shot Chain-of-Thought?
3. What is the core idea of chain prompting?
4. Compared with relying only on prompt text to request JSON output, what is the advantage of llama.cpp's grammar-constrained sampling?
🛠️ Hands-on Practice
- In the complex prompt from Section 6.4, sequentially remove the persona, context, and data_format elements one at a time and run the summarization task; compare the three outputs against the full-prompt output and record which element has the greatest impact on output quality.
- Restore and run the commented-out
standard_prompt(without chain-of-thought) in Section 6.5; compare its result withcot_promptto verify the effect of the CoT example on arithmetic problems like "23 apples." - Following Section 6.6, use llama.cpp's
response_formatto constrain the model to output an RPG character object containingname,class, andlevelfields; verify the output is indeed valid JSON usingjson.loads().