Play with prompt engineering: a practical manual for making AI understand human language

Master AI dialogue skills and improve the efficiency of AI interaction.
Core content:
1. Three musketeers of model parameter adjustment: practical application of temperature, Top-K and Top-P
2. Comparison of prompt word formats: the impact of different questioning methods on AI answers
3. Three prompt modes: tips and cases for system, role and context prompts
1. Three Keys to Model Parameter Adjustment
1. Temperature
Low temperature (0.1): "The sky is __" → "Blue" (high certainty) High temperature (0.9): "The sky is __" → "A canvas strewn with stars" (high creativity)
2. Top-K & Top-P
Practical parameter settings:
Exact answer tasks: temperature=0, top_k=1
(Strict prediction mode)Creative copywriting tasks: temperature=0.9, top_k=40, top_p=0.95
(Divergent thinking mode)General question-answering tasks: temperature=0.2, top_k=30, top_p=0.8
(Balanced Mode)
2. Comparison of prompt word formats
The same needs, different questioning methods, and different results:
# Experiment with three types of questions
prompts = [
# Question type
"What is the Sega Dreamcast and why is it considered a revolutionary gaming console?" ,
# Declarative
"Sega Dreamcast is the sixth generation game console released in 1999..." ,
# Command type
"Write a paragraph about the Sega Dreamcast and why it is revolutionary in the history of video game consoles."
]
# Output three different results for comparison
for prompt in prompts:
response = model.predict(prompt, temperature= 0.7 )
print( f"Prompt type: {prompt[: 10 ]} ...\nOutput: {response} \n---" )
3. The Secrets of the Three Prompt Modes
1. System Prompting
# Movie review classifier
prompt = """
Classify movie reviews as positive, neutral, or negative.
Only uppercase tags are returned.
Review: Her is a disturbing film about where artificial intelligence is headed.
It was so painful for me to watch that I couldn't bear to watch it.
emotion:
"""
2. Role Prompting
# Travel Advisor Role
prompt = """
I want you to play a travel consultant.
I will tell you where I am and you need to recommend me 3 places with a humorous style.
My request: "I'm in Manhattan"
"""
# Output: The Empire State Building, MoMA, and Fifth Avenue will be introduced in a humorous tone
3. Contextual Prompting
# Retro Gaming Blog
prompt = """
Context: You're writing for a blog about 80s arcade games.
Suggest 3 article topics, each with an accompanying brief description.
"""
# Output: Evolution of arcade cabinet design, iconic 80s games, the rise and resurgence of pixel art
4. Advanced Thinking Skills
1. Chain of Thought (CoT) Practice
Wrong example : "When Xiaoming was 3 years old, his sister was 3 times his age. Now Xiaoming is 20 years old. How old is his sister?" → Wrong answer: 63 years old
Correct posture :
Please think in steps:
1. When Xiao Ming was 3 years old, his sister’s age was: 3 × 3 = 9 years old
2. Age difference: 9 - 3 = 6 years old
3. Xiao Ming is now 20 years old, and his sister is: 20 + 6 = 26 years old
2. Step-back Prompting
# Step 1: Take a step back and think about more general issues
response1 = model.predict( "Which scenes are suitable for level design of first-person shooter games?" )
# Output: Abandoned military base, cyberpunk city, alien spaceship, zombie town, underwater research facility...
# Step 2: Based on the general answer, return to the specific question
prompt2 = f"""
Consider the following scenario:
{response1}
Now, design a compelling level story for a first-person shooter game.
"""
response2 = model.predict(prompt2)
# Output: A game level design with more depth and detail
3. Tree of Thoughts
Let’s take an example:
4. Self-consistency
# Use multiple inferences to verify the answer
responses = []
for i in range( 5 ): # Run the same problem 5 times
response = model.predict(
"To determine whether the content of an email is important or not, you need to think in steps:\n[email content]\nJudgement result:" ,
temperature = 0.8 # Use high temperature to produce diverse results
)
responses.append(response)
# Count the most results
import collections
result = collections.Counter([r.split( "Conclusion:" )[ -1 ].strip() for r in responses]).most_common( 1 )[ 0 ][ 0 ]
print( f"Final judgment: {result} " )
5. ReAct mode (reasoning + action)
from langchain.agents import load_tools
from langchain.agents import initialize_agent
# Initialize the search tool
tools = load_tools([ "serpapi" ], llm=llm)
agent = initialize_agent(
tools,
llm,
agent= "zero-shot-react-description" ,
verbose= True
)
# Execute multi-step query
agent.run( "How many children do the members of the band Metallica have?" )
Execution process:
Thoughts: Metallica has 4 members
Action: Search for "How many kids does James Hetfield have?"
Observation: three children
Thinking: 1/4 of the members have 3 children
Action: Search for "How many kids does Lars Ulrich have?"
Observations: 3
Thinking: 2/4 members have 6 children
...Final answer: 10
5. Code Tips Expert Tips
1. Generate code
prompt = """
Write a Bash script that asks for a folder name and copies all the files in that folder to
Rename by adding 'draft_' prefix to the original file name.
"""
2. Debugging Code
prompt = """
The following Python code has an error:
```Python
import os
import shutil
folder_name = input("Please enter the folder name: ")
prefix = input("Please enter a prefix: ")
text = toUpperCase(prefix) # Error here
...
Please diagnose the problem and provide the correct solution. """
## 6. Structured Output Black Technology
```json
{
"Movie Reviews" : {
"Sentimental orientation" : "POSITIVE" ,
"Reasons" : [ "Excellent acting" , "Compact plot" ],
"Recommendation Index" : 4.5
}
}
Advantages :
Reduced hallucination content by 30%.[3] Force the model to answer by structure Easy backend processing and integration
7. A complete collection of practical reminder word templates
# Role Playing Template
As [professional role], please [perform tasks], requesting [specific requirements].
Example: As a financial advisor, analyze the key indicators of the following quarterly report, focusing on profit growth points.
# Step decomposition template
Please follow the steps below to complete [task]:
1. First of all...
2. Next...
3. Finally...
# Comparative analysis template
Please compare the similarities and differences between [A] and [B] in the following aspects:
- Cost-effective
- Difficulty of implementation
- Long-term value
8. Pitfall Avoidance Guide
Few samples suggest to mix types:
Good example:
Positive example: "This restaurant has great service!" → POSITIVE
Counterexample: "The food was cold" → NEGATIVE
Neutral: "The food was served at an average speed" → NEUTRAL
Use directives instead of restrictions :
✅ Good example: "Generate a paragraph about Sega DC, only discussing hardware specifications and release date"
❌ Bad example: "Generate a paragraph about Sega DC, don't mention games or prices"
Record prompt experimental results :
| Prompt Name | Target | Model | Temperature | Top-K | Top-P | Prompt Content | Output Result |
|--------|------|-----|-----|-------|------|--------|--------|
| Game review v1 | Analysis of game features | gemini-pro | 0.2 | 40 | 0.8 | ... | ...