title: Prompt Engineering Basics: A Complete Guide to Large Model Instruction Design and Optimization | Daoman PythonAI description: In-depth study of the core technology of Prompt Engineering, mastering advanced techniques such as Zero-shot, Few-shot, Chain-of-Thought, and complete practical methods of structured prompt word design and system prompt word optimization. keywords: [Prompt Engineering, large model prompt words, LLM, instruction design, artificial intelligence, machine learning, natural language processing, thinking chain, CoT, prompt word optimization]

Prompt Engineering Basics: A Complete Guide to Large Model Instruction Design and Optimization

Table of contents

Prompt Engineering Overview

Prompt Engineering is the core technology for dealing with large language models. You don't need to retrain the model. Just by adjusting the text instructions, you can let the same model complete various tasks such as translation, writing, classification, reasoning, etc.

Simply put, Prompt Engineering can be summarized as:

Well-designed instructions + relevant context + output constraints = high-quality model output

Through the combination of these three elements, we can maximize the capabilities of the model.

We can compare poor prompt words with good prompt words and feel the difference:

QualityExamples
❌ Bad prompt words翻译(The model has no idea what to translate)
✅ Good prompt words请将下面的英文句子翻译成中文,只输出翻译结果: Hello, how are you today?

Good prompt words make the task goal, input content, and output format clear at a glance, and there is almost no "error room" for the model to perform. This is exactly the effect we are pursuing.

Why is Prompt Engineering so important?

  • Cost Friendly: No expensive fine-tuning and retraining required
  • Highly flexible: The same model can be changed from "customer service" to "code reviewer" by changing the prompt word
  • High controllability: You can precisely constrain the language style, length, and format of the output
  • Quick Trial and Error: Changing a line of text is much faster than retraining the model

Common prompt word types

This article will focus on the first three most commonly used technologies:

  • Zero‑shot Prompting: Directly assign tasks without giving examples
  • Few‑shot Prompting: Give a few examples to let the model "imitate cats and draw tigers"
  • Chain‑of‑Thought (CoT): guides the model to reason step by step
  • Role Play Tip: Give your model an identity and tone
  • System Prompt: Inject global rules before the conversation starts

Zero-shot Prompting detailed explanation

Zero‑shot is the most straightforward usage, without giving any examples, just tell the model what you want it to do. Its confidence lies in the fact that the large model has read a large amount of text in the pre-training stage, and a lot of knowledge has already been internalized. You just need to "activate" it with clear instructions.

When to use Zero‑shot?

  • Simple text classification (sentiment analysis, news categories)
  • General translation tasks
  • Basic summarization and generation
  • Factual Q&A

Practical examples

Sentiment Analysis

判断下面评论的情绪是正面、负面还是中性,只输出一个词。

评论:这个产品真好用,物流也快。

Output:正面

Text Classification

将下面的新闻分到“体育”“科技”“财经”“娱乐”中的一个类别,只输出类别名称。

新闻:苹果公司发布了新一代自研芯片。

Output:科技

translate

把下面的话翻译成英文,只输出英文句子。

今天阳光真好。

Output:The sunshine is really nice today.

Zero‑shot’s shortcomings

  • It is easy to overturn when encountering problems that require multi-step reasoning
  • The output format is not stable and sometimes comes with redundant explanations
  • I am sensitive to wording. If I say the same thing differently, the result may be different.

But don’t worry, the Few‑shot and Chain‑of‑Thought we are going to talk about below can solve these problems.

Few-shot Prompting Practice

By inserting a few "examples" into the prompts, the model will act like a student imitating the examples, and the accuracy can often be greatly improved. **The key point is: there don’t need to be many examples, but they should be typical, clear, and consistent in format. **

How Few‑shot works

  1. Prepare 2‑5 representative (input → output) examples
  2. Maintain consistent layout and separators for all examples
  3. The model will automatically infer the task mode when reading the example.
  4. Then apply this pattern to the last input to be solved

Practical examples

Idiom Translation

请把下面的成语翻译成英文,保持格式为:成语 → 英文解释。

塞翁失马,焉知非福 → A loss may turn out to be a gain.
纸上谈兵 → To talk idly about theoretical matters.
亡羊补牢 → Better late than never.
破镜重圆 → 

Sentiment Analysis

判断评论的情绪,选项:正面 / 负面 / 中性。

评论:物流快,包装也很用心。
情绪:正面

评论:东西收到了,但质量太差了,失望。
情绪:负面

评论:还行吧,没太大感觉。
情绪:中性

评论:虽然贵了点,但用起来确实舒服。
情绪:

Few-shot design tips

  • Easy first, then difficult: put simple examples first to help build confidence in the model
  • Wrong examples sometimes work: Occasionally adding an example of "wrong answer + correction" can help the model learn to avoid common pitfalls
  • Keep your formatting strict: It’s best to use delimiters (such as arrows, dashes, numbers) consistently, don’t switch them around

Chain-of-Thought thinking chain technology

For some tasks, such as math problems and logic puzzles, asking for answers directly is ineffective. At this time, we can use Chain‑of‑Thought (CoT) technology to let the model write out the reasoning process step by step**.

The current approach is no longer "question → answer", but:

Question → First step of reasoning → Second step of reasoning → … → Final answer

This not only improves the accuracy, but also allows us to see clearly what the model is thinking.

Two CoT implementation methods

  1. Few‑shot CoT
    Give several examples containing reasoning steps in the prompts, and the model will imitate this "slow thinking" style after reading them.
问题:桌上有 8 支笔,收走 3 支,又放了 5 支,现在有几支?
推理:起始 8 支,收走 3 支剩 5 支,再放 5 支得 10 支。
答案:10 支

问题:一包饼干有 12 块,小明吃了 3 块,妹妹吃了 2 块,还剩几块?
推理:
  1. Zero‑shot CoT
    If you are too lazy to write an example, just add a sentence让我们一步一步思考, many models can also miraculously switch to inference mode.
一个长方形长 8 米,宽 5 米,它的面积是多少平方米?
让我们一步一步思考。

More "insurance" - self-consistency strategy

Let the model infer multiple times with the same question (you can adjust the temperature parameters slightly), and then select the answer with the highest frequency, which can further improve stability. While this consumes a few more API calls, it's well worth it for mission-critical tasks.

Advanced prompt design skills

Role play, let the model "enter the play"

Give the model a clear identity, and the content it produces will immediately take on the tone and professionalism of that character.

RolePrompt Fragment Example
Senior Engineer"You are a Python backend expert who is good at writing clear, modular code."
Patient Teacher"You are a teacher who explains mathematics to primary school students. Please explain in the simplest language."
Security Reviewer"You are a code security reviewer, please identify potential risks in the script below."

The output format is clear and simple

Just say "only output JSON". Sometimes the model will add a bunch of polite words to you. At this time, "templating" the format requirements is very useful.

Force JSON output

请严格按照下面的 JSON 格式回答,不要多一个字:
{
  "answer": "...",
  "confidence": 0.0-1.0
}

Structured Template

【答案】
(你的答案)

【理由】
(简要说明为什么这么认为)

【置信度】
(高/中/低)

Precision of constraints

  • Length Constraints:请用不超过 80 个字回答
  • Domain Constraints:请只基于上面提供的材料来判断,不要引入外部知识
  • Tone Constraints:请使用正式、礼貌的商务中文

Structured Prompt design

In actual development, we often need to dynamically splice prompt words. At this time, a clear Prompt template can avoid confusion.

【任务描述】
你要做什么

【背景信息】
相关的上下文或文档

【输入数据】
待处理的内容

【输出要求】
格式、长度、语气等

【示例】(可选)
输入:… 输出:…

【当前输入】
具体需要处理的新内容

Dynamically build Prompt with code

Splitting each part into reusable modules will make project maintenance much easier.

class PromptBuilder:
    def __init__(self):
        self.sections = []

    def add_header(self, title, content):
        self.sections.append(f"【{title}\n{content}\n")
        return self

    def build(self):
        return "\n".join(self.sections)

# 快速搭建一个情感分析 prompt
builder = PromptBuilder()
prompt = (builder
    .add_header("任务", "进行情感分析,输出正面/负面/中性")
    .add_header("当前输入", "这个咖啡味道不错,还会回购")
    .build())
print(prompt)

System Prompt

System Prompt is like the "personality set" of the model. It is injected at the beginning of the conversation and plays a decisive role in the tone, behavior, and safety boundaries of the entire conversation.

What does System Prompt mainly do?

  • Defined Role: Who are you and what is your background?
  • Drawing boundaries: What to say and what not to say
  • Embedded knowledge: Load the model with basic rules in professional fields
  • Control style: formal/casual, concise/detailed, enthusiastic/calm

Several typical System Prompts

  • Programming Assistant: "You are a senior Python developer. When answering questions, just write the code directly, with brief comments, and no additional greetings."
  • Customer Service Assistant: "You are the official customer service of the mall. Your tone is friendly and professional. If you encounter problems that cannot be solved, please guide users to submit work orders."
  • Learning Coach: "You explain complex concepts in simple words, just like giving lectures to junior high school students, and give more examples from life."

How it looks like when used in the API

System Prompt is usually placed inmessagesAt the front of the array, the role is labeled"system"

import openai

response = openai.ChatCompletion.create(
    model="gpt-4o-mini",
    messages=[
        {
            "role": "system",
            "content": "你是一个专业的Python编程助手,提供简洁高效的代码解决方案。"
        },
        {
            "role": "user",
            "content": "写一个合并两个有序数组的函数"
        }
    ],
    temperature=0.2
)

Prompt optimization strategy

Writing a prompt is rarely done in one step. Most of it requires a cycle of "actualization-analysis-adjustment".

Find the best version with A/B testing

  1. Set evaluation indicators (accuracy rate, format compliance rate, relevance, etc.)
  2. Prepare a fixed test data set
  3. Generate 2‑3 Prompts with different wordings for the same task
  4. Compare their performance on the test set
  5. Keep the best one and consider further fine-tuning.

Only change one variable at a time, the effect is clear and easy to attribute.

Iterative four-step method

  • Establish baseline: Record the performance of the current Prompt as the "starting line"
  • Positioning problems: Find those cases where errors occur frequently and summarize the error types
  • Targeted modifications: If the format is wrong, emphasize the format; if the reasoning is stuck, add CoT examples.
  • Verification effect: Run it once with the test set and compare it with the baseline to decide whether to go online.

Practical application cases

Below are two Prompt templates that can be "checked in" directly. You can modify them slightly according to the actual business.

Customer Service Scenario

【角色】你是一家电商平台的客服代表,需保持友好、专业、高效。
【核心理念】
- 先理解并共情客户的问题
- 给出具体可行的解决方案
- 结尾主动询问是否需要其他帮助

【回复格式】
1. 一句理解/共情的话
2. 清晰的解决步骤
3. 结尾关心语

【客户问题】
{查询内容}

Content generation scenario

【任务】写一篇关于 {主题} 的博客文章
【读者】{初级/中级/高级} 技术人员
【文章要求】
- 字数:800~1200 字
- 语言通俗,少用术语,多打比方
- 结构清晰:开头吸引人、中间分点展开、结尾有总结建议

【输出格式】
1. 自然醒目的标题
2. 引言段
3. 3~5 个内容小节
4. 总结与建议
Prompt Engineering is a craft. It is recommended to start with Zero‑shot and first understand “how the model will move according to the instructions”, and then slowly add Few‑shot and CoT. Do more, observe more, and summarize more, and slowly you will be able to see the "parameter adjustment space" of Prompt at a glance.

Summarize

  1. The foundation must be stable: Zero‑shot, Few‑shot, and CoT are the three most core moves.
  2. Design in a structured manner: Good prompt = clear task + high-quality examples + strong constraint format
  3. Advanced skills: Role playing, System Prompt, and output forced templates will all take your product experience to the next level.
  4. Optimization relies on iteration: Set indicators, do A/B testing, and only adjust one variable at a time
  5. Scenario is King: There is no silver bullet prompt, and realistic scene design is the way to go.

💡 Core formula: Excellent prompt = clear task description + appropriate context + clear format requirements + appropriate constraints


🔗 Extended reading

📂 Stage: Stage 5 - Ladder to Large Model (LLM) 🔗 Related chapters: GPT系列演进 · 指令微调(Instruction Tuning)