AI: Prompt 工程

最后更新:2026-08-26

"Prompt 工程"听起来像是玄学——同样一个 AI,换个说法输出质量天壤之别。但 Prompt 工程的核心并不神秘:它是一套让 AI 理解你意图、按照你期望格式输出内容的设计方法。本章从设计原则出发,带你掌握零样本、少样本、思维链提示策略,理解 System Prompt 与角色设定,并用 Python 构建可复用的结构化 Prompt 模板。

1. 你将学到


2. 故事:一个 Prompt 的距离

(1) 痛点:AI 的"废话文学"

Bob 需要一份市场分析报告,他打开 ChatGPT 输入:

"写一份市场分析报告"

结果 AI 输出了一段四平八稳的空泛文字:"市场规模持续增长……机遇与挑战并存……建议密切关注市场动态。"——正确但毫无信息量。

(2) Alice 的 Prompt 改造

Alice 拿过键盘,重新输入:

"你是一名资深市场分析师,有 15 年电动汽车行业经验。请分析 2025 年全球电动汽车市场,包含:3 个关键趋势、2 个主要风险、1 个投资建议。用 Markdown 表格呈现趋势部分。"

AI 这次输出了条理清晰、数据翔实的分析报告——同样的模型,同样的能力,唯一的区别是 Prompt。

(3) 收益:Prompt 就是"说明书"

Bob 感叹:"原来 AI 不是不行,是我没说清楚!"Alice 点头:"Prompt 工程的本质就是——给 AI 一份精确的'任务说明书'。"


3. Prompt 设计原则

(1) 三大核心原则

原则 含义 反面例子
明确 任务目标无歧义,AI 不需要猜测 "分析一下市场"
具体 提供足够的细节、约束和上下文 "写个报告"
结构化 用编号、分点、模板组织 Prompt 大段自由文本

好的 Prompt 让 AI 的工作从"自由发挥"变成"按图索骥"。

(2) 好的 Prompt vs 坏的 Prompt 对比表

维度 坏的 Prompt 好的 Prompt
目标 "帮我写点东西" "写一封 200 词的商务邮件,邀请客户参加产品发布会"
角色 "你是一名资深公关经理"
格式 "输出 Markdown 格式,包含标题、正文、签名"
约束 "不超过 200 词,语气正式但不生硬"
示例 附带 1-2 个期望输出的片段
评估 "重点突出时间、地点、亮点"

(3) Prompt 设计的"6 要素"框架

一个完整的 Prompt 通常包含以下要素(不必全部包含,但越多越精确):

  1. Role — 角色设定:"你是一名……"
  2. Task — 明确任务:"请完成……"
  3. Context — 背景信息:"目标读者是……"
  4. Format — 输出格式:"用 JSON / 表格 / Markdown 输出"
  5. Constraint — 约束条件:"不超过 300 词 / 只用小学词汇"
  6. Example — 示例(Few-shot):"如下例所示……"

用 Python 字符串模板来表示就是:

PYTHON
PROMPT_TEMPLATE = """
[Role] You are a {role}.
[Task] Please {task}.
[Context] {context}
[Format] Output in {format}.
[Constraints] {constraints}
[Example] {example}
"""

4. 提示策略:零样本 / 少样本 / 思维链

(1) 零样本提示(Zero-Shot)

零样本提示不给 AI 任何示例,直接描述任务——依赖模型已有的知识和理解能力。

▶ 示例:零样本提示与输出(难度⭐)

PYTHON
# Zero-shot prompt: classify sentiment without examples
prompt = """
Classify the sentiment of the following review as Positive or Negative:

Review: "The battery life is amazing, lasted 12 hours on a single charge!"
Sentiment:
"""

# Expected output: Positive

零样本适合简单、明确的任务。但当任务较复杂或需要特定格式时,输出往往不稳定。

(2) 少样本提示(Few-Shot)

少样本提示在 Prompt 中提供几个"输入→输出"的示例,让 AI 通过类比学习你期望的模式。

▶ 示例:少样本提示改善输出(难度⭐)

PYTHON
# Few-shot prompt: classify sentiment with examples
prompt = """
Classify the sentiment of each review as Positive or Negative.

Review: "Love the screen quality!" -> Positive
Review: "Terrible customer service." -> Negative
Review: "Decent product, nothing special." -> Neutral
Review: "Best purchase I have made this year!" -> Positive

Review: "The price is too high for what you get." ->
"""

# Expected output: Negative

少样本的关键:示例要有代表性,覆盖不同情况;格式要统一,让 AI 学到模式而非混乱。

(3) 思维链提示(Chain-of-Thought, CoT)

思维链提示要求 AI "一步一步思考",将推理过程显式化。这对数学推理、逻辑分析等任务效果显著。

▶ 示例:CoT 提示解决数学题(难度⭐⭐)

PYTHON
# Chain-of-Thought prompt: solve a math problem step by step
prompt = """
Solve the following problem step by step.

Problem: A store buys a laptop for $800 and sells it for $1,050.
What is the profit margin as a percentage?

Step-by-step solution:
"""

# Expected output:
# Step 1: Calculate profit = 1050 - 800 = $250
# Step 2: Calculate margin = (250 / 800) * 100% = 31.25%
# Answer: The profit margin is 31.25%

CoT 的两种用法:

(4) 三种提示策略对比表

维度 零样本(Zero-Shot) 少样本(Few-Shot) 思维链(CoT)
是否需要示例 是(2-5 个) 是(含推理步骤)
Token 消耗
适用场景 简单分类、格式化 格式/风格需对齐 数学/逻辑/多步推理
输出稳定性
准确率 依赖模型能力 显著提升 显著提升
典型用法 Classify: ... A->X, B->Y, C->? "Step by step..."

5. 系统提示与角色设定

(1) System Prompt 是什么

在 Chat API 中,消息分为三种角色:

角色 作用 类比
system 设定 AI 的行为规则和身份 "员工手册"
user 用户的实际提问或指令 "客户需求"
assistant AI 的回复 "员工响应"

System Prompt 在整个对话中持续生效,是控制 AI 行为最强大的工具。

(2) 角色设定的力量

角色设定不仅改变 AI 的"语气",更改变了它调用的知识范围和推理方式:

▶ 示例:System Prompt 角色设定(难度⭐)

PYTHON
# Define a system prompt for a technical interviewer role
system_prompt = """
You are a senior software engineer conducting a technical interview.
Rules:
1. Ask one question at a time
2. Wait for the candidate answer before asking the next
3. If the answer is wrong, give a hint instead of the correct answer
4. Cover topics: data structures, algorithms, system design
5. Rate each answer on a scale of 1-5
"""

user_message = "I am ready for the interview. Please start."

# The AI will behave as a structured interviewer,
# not a generic chatbot

(3) System Prompt 最佳实践

  1. 先写规则,再写身份:规则比身份更容易被 AI 遵守
  2. 用编号列出规则:比自然语言段落更不容易被 AI 忽略
  3. 设定负面约束:"不要做什么"比"做什么"有时更有效
  4. 测试边界:故意违反规则看 AI 是否纠正

6. 输出格式控制

(1) 为什么需要格式控制

当你需要 AI 的输出被程序解析(而非人阅读)时,格式控制就至关重要——JSON、表格、特定分隔符等。

(2) 输出格式控制方式对比

方式 优点 缺点 适用场景
自然语言描述 简单 AI 可能不遵守 非结构化输出
Markdown 模板 可读性好 解析需额外处理 报告/文档
JSON Schema 机器可解析 Token 消耗高 API 集成
分隔符标记 精确控制 需设计分隔符 抽取特定字段
Few-shot 格式 AI 模仿力强 示例占 Token 复杂格式对齐

▶ 示例:JSON 格式输出控制(难度⭐⭐)

PYTHON
# Prompt that enforces JSON output with a schema
prompt = """
Extract product information from the text below.
Output ONLY valid JSON matching this schema:

{
  "name": "string",
  "price": "number",
  "currency": "string",
  "features": ["string"]
}

Text: "The UltraWidget Pro costs $49.99 and comes with waterproof casing,
solar charging, and a 5-year warranty."

JSON:
"""

# Expected output:
# {
#   "name": "UltraWidget Pro",
#   "price": 49.99,
#   "currency": "USD",
#   "features": ["waterproof casing", "solar charging", "5-year warranty"]
# }

(3) JSON 输出的可靠性保障

在实际工程中,AI 生成的 JSON 可能格式错误。推荐用 Pydantic 做二次校验:

PYTHON
from pydantic import BaseModel
from typing import List

class ProductInfo(BaseModel):
    name: str
    price: float
    currency: str
    features: List[str]

# Validate AI output
try:
    product = ProductInfo.model_validate_json(ai_output)
    print(f"Valid: {product.name} - {product.currency}{product.price}")
except Exception as e:
    print(f"Invalid JSON: {e}")

7. Prompt 工程流程

(1) 迭代优化流程

Prompt 工程不是一次性的——它是一个"设计→测试→评估→迭代"的循环:

100%
graph TB
    A[Requirements] --> B[Template Design]
    B --> C[Test Run]
    C --> D{Evaluate Output}
    D -- Unsatisfied --> E[Diagnose]
    E --> F[Revise Prompt]
    F --> C
    D -- Satisfied --> G[Freeze Template]
    G --> H[Deploy]

(2) 评估输出质量的标准

维度 评估方法 工具
准确性 与人工标注对比 LLM-as-Judge
格式合规 Schema 校验 Pydantic / JSON Schema
完整性 检查必填字段 自定义脚本
一致性 多次运行对比 统计方差
相关性 与任务目标对齐 人工评分

8. 常见 Prompt 陷阱与调试

(1) 五大常见陷阱

陷阱 表现 修复
模糊指令 AI 输出方向偏离 明确任务目标 + 输出格式
信息过载 Prompt 过长,AI 忽略关键部分 分段组织,关键信息放末尾
格式漂移 输出格式不稳定 提供示例 + Schema 约束
角色冲突 System 与 User 指令矛盾 System 优先级最高,统一指令
过度约束 约束太多导致 AI 无法输出 保留核心约束,删除冗余

(2) Prompt 调试策略对照表

策略 操作 适用场景
A/B 对比 只改一个变量,对比输出 找出哪个要素影响最大
逐步简化 从完整 Prompt 逐步删减 找出最小有效 Prompt
逐步增强 从最简 Prompt 逐步添加 确认每个要素的贡献
输出审查 逐句检查 AI 输出 定位具体问题
边界测试 输入极端/边界情况 测试鲁棒性
温度调节 调低 temperature 减少随机性 需要确定性输出时

(3) 调试实操:一个 Prompt 的诊断过程

PYTHON
# Bad: vague prompt
bad_prompt = "Analyze the electric vehicle market."

# Step 1: Add role
step1 = "You are a senior EV market analyst. Analyze the EV market."

# Step 2: Add structure
step2 = """You are a senior EV market analyst.
Analyze the 2025 global EV market with:
1. Three key trends
2. Two major risks
3. One investment recommendation"""

# Step 3: Add format constraint
step3 = """You are a senior EV market analyst with 15 years of experience.
Analyze the 2025 global EV market with:
1. Three key trends (present in a Markdown table)
2. Two major risks (with probability assessment)
3. One investment recommendation (with expected ROI range)

Output in Markdown format with clear headers."""

9. 综合示例:结构化产品分析 Prompt 模板

▶ 示例:完整的产品分析 Prompt 系统(难度⭐⭐⭐)

构建一个可复用的产品分析 Prompt 模板,包含 System Prompt、User Prompt 模板和输出解析:

PYTHON
from string import Template
from pydantic import BaseModel
from typing import List, Optional

# Step 1: System Prompt - define the role
SYSTEM_PROMPT = """You are a senior product analyst with expertise in
market research, competitive analysis, and user experience evaluation.
You produce structured, data-driven product analysis reports.

Rules:
1. Always base analysis on concrete evidence and data points
2. Highlight both strengths and weaknesses objectively
3. Provide actionable recommendations with priority levels
4. Use specific numbers and metrics whenever possible
5. Format output as valid Markdown
"""

# Step 2: User Prompt template with all 6 elements
USER_PROMPT_TEMPLATE = Template("""
[Task] Analyze the following product and produce a comprehensive report.

[Product Info]
- Name: $product_name
- Category: $category
- Price: $price
- Target Users: $target_users

[Report Structure]
Please include the following sections:
1. **Product Overview** - Brief description and positioning
2. **Strengths** - Top 3 advantages with evidence
3. **Weaknesses** - Top 3 limitations with examples
4. **Market Position** - Competitive landscape analysis
5. **Recommendations** - Prioritized improvement suggestions

[Format] Output as Markdown with headers and a summary table.
[Constraints] Maximum 500 words. Be concise and specific.
[Example]
Product Overview
The ProductX is a mid-range smartphone targeting young professionals...

Summary Table
| Aspect | Rating | Key Insight |
|--------|--------|-------------|
| Design | 4/5 | Premium feel at mid-range price |
""")

# Step 3: Fill template and call API (pseudo-code)
def analyze_product(product_name: str, category: str,
                    price: str, target_users: str) -> str:
    user_prompt = USER_PROMPT_TEMPLATE.substitute(
        product_name=product_name,
        category=category,
        price=price,
        target_users=target_users
    )
    # In real usage, call your LLM API here
    # response = client.chat.completions.create(
    #     model="gpt-4",
    #     messages=[
    #         {"role": "system", "content": SYSTEM_PROMPT},
    #         {"role": "user", "content": user_prompt}
    #     ],
    #     temperature=0.3
    # )
    # return response.choices[0].message.content
    return user_prompt  # Return the prompt for demo

# Step 4: Use the template
result = analyze_product(
    product_name="EcoBike S3",
    category="Electric Bicycle",
    price="$1,299",
    target_users="Urban commuters aged 25-40"
)
print(result[:300] + "...")

关键设计点:System Prompt 定义角色和通用规则,User Prompt 模板处理具体任务,两者分离让模板可复用。


❓ 常见问题

Q Prompt 工程是不是就是"跟 AI 说话"?
A 不完全是。日常跟 AI 聊天是随意的,Prompt 工程是系统化的设计——它有明确的原则(明确/具体/结构化)、策略选择(零样本/少样本/CoT)、格式约束和迭代流程。就像"说话"和"演讲"都用语言,但后者需要精心设计。
Q 为什么同样的任务不同 Prompt 结果差这么多?
A LLM 是概率模型,它根据 Prompt 中的每个 Token 来预测后续内容。模糊的 Prompt 让模型在巨大的可能性空间中随机采样;精确的 Prompt 则大幅缩小了有效输出范围——差距可达数个数量级。
Q 思维链提示什么时候用?
A 当任务涉及多步推理(数学计算、逻辑分析、复杂决策)时使用 CoT。对于简单分类、格式转换等单步任务,CoT 反而浪费 Token 且不提升效果。一个判断标准:如果人也需要"想一下"才能回答的问题,就该用 CoT。
Q System Prompt 和 User Prompt 有什么区别?
A System Prompt 设定 AI 的身份和行为规则,在整个对话中持续生效,优先级最高;User Prompt 是每次的具体任务或提问,只在当前轮次生效。类比:System Prompt 是"员工手册",User Prompt 是"客户需求"。
Q 能用 Prompt 替代微调吗?
A 在很多场景下可以——少样本提示就能让模型适应新任务格式。但 Prompt 有长度限制,无法注入大量领域知识;微调则能改变模型参数,深度内化知识。经验法则:如果 5-10 个示例就能搞定,用 Prompt;如果需要几百个样本或专业知识,考虑微调。

📖 小节

本章知识点 核心要点
设计原则 明确、具体、结构化——6 要素框架
零样本提示 无示例,适合简单任务
少样本提示 2-5 个示例,对齐格式与风格
思维链提示 "Step by step",适合多步推理
System Prompt 控制角色与规则,优先级最高
格式控制 JSON Schema / Markdown 模板 / Few-shot
调试方法 A/B 对比、逐步增强/简化、边界测试

下一章预告:我们将深入 RAG(检索增强生成),学习如何让 AI 结合外部知识库回答问题,突破模型知识的时间边界。


📝 作业

基础(⭐)

设计 3 个不同质量的 Prompt 完成同一任务(翻译一段英文为中文),对比输出质量:

PYTHON
# Task: Translate English to Chinese

# Bad prompt
prompt_v1 = "Translate this: The quick brown fox jumps over the lazy dog."

# Better prompt (add context and constraints)
prompt_v2 = "Translate the following English sentence to natural, fluent Chinese. Preserve the original tone and meaning.\n\nThe quick brown fox jumps over the lazy dog."

# Best prompt (add role, format, and example)
prompt_v3 = """You are a professional English-Chinese translator.

Rules:
- Translate to natural, idiomatic Chinese
- Preserve the original tone and nuance
- If the sentence has cultural references, add a brief note

Example:
EN: "Break a leg!"
CN: "Break a leg! (English idiom for wishing good luck before a performance)"

Now translate:
The quick brown fox jumps over the lazy dog."""

# TODO: Run each prompt through an LLM and compare outputs

进阶(⭐⭐)

用少样本提示让 LLM 做 5 条评论的情感分类(Positive / Negative / Neutral):

PYTHON
# Few-shot sentiment classification
prompt = """Classify the sentiment of each review.

Review: "Absolutely love this product! Five stars!" -> Positive
Review: "Waste of money, broke after one week." -> Negative
Review: "It works as expected, nothing more." -> Neutral
Review: "The design is gorgeous but battery drains fast." -> ?

Now classify these 5 reviews:
1. "Best coffee maker I have ever owned!"
2. "Delivery was late and the box was damaged."
3. "Average quality for the price, decent but not impressive."
4. "Customer support resolved my issue in 10 minutes, amazing!"
5. "The instructions are confusing but the product works fine."
"""

# TODO: Run through an LLM and verify accuracy

挑战(⭐⭐⭐)

设计一个 System Prompt 让 LLM 扮演技术面试官,并实现多轮对话流程:

PYTHON
# Technical interviewer system
SYSTEM_PROMPT = """You are a senior backend engineer conducting a coding interview.
Rules:
1. Ask one question at a time about Python/data structures/algorithms
2. Evaluate each answer: rate 1-5 and give brief feedback
3. If wrong, provide a hint, not the full answer
4. After 5 questions, give an overall assessment
5. Difficulty should gradually increase
"""

# Simulated multi-turn conversation
conversation = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": "I am ready for the interview."},
]

# TODO: Implement a loop that:
# 1. Sends conversation to LLM
# 2. Prints the interviewer question
# 3. Takes user input as answer
# 4. Appends both to conversation
# 5. Repeats until interview ends
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏