提示工程(Prompt Engineering)实战指南

提示:下面的流程图使用 Mermaid 绘制,您可以在支持的 Markdown 渲染器中直接查看。

graph TD
    User[用户需求] --> Prompt[构造 Prompt]
    Prompt --> Model[LLM 推理]
    Model --> Response[模型输出]
    Response --> Refine[结果评估与改进]
    Refine --> Prompt

基本技巧

  1. 明确指令:使用清晰的动词,如 请解释请生成
  2. 提供上下文:在 Prompt 中加入必要的背景信息。
  3. 示例示范(Few‑Shot):给出几组输入‑输出示例,引导模型学习格式。
  4. 链式思考(Chain‑of‑Thought):让模型一步步推理,提升逻辑准确性。

示例代码(Python)


_36
from transformers import pipeline
_36
_36
# 使用小模型演示(速度快)
_36
generator = pipeline("text-generation", model="gpt2")
_36
_36
# 1. 零样本 Prompt(Zero‑Shot)
_36
prompt_zero = "用中文解释什么是注意力机制(Attention)"
_36
print(generator(prompt_zero, max_new_tokens=80)[0]["generated_text"])\n
_36
# 2. Few‑Shot 示例
_36
few_shot_prompt = """
_36
示例 1:
_36
Q: 什么是机器学习?
_36
A: 机器学习是一种让计算机通过数据自动改进性能的技术。
_36
_36
示例 2:
_36
Q: 什么是注意力机制?
_36
A: 注意力机制是一种让模型在处理序列时聚焦重要信息的技术。
_36
_36
现在请解释什么是梯度下降(Gradient Descent)。
_36
"""
_36
print(generator(few_shot_prompt, max_new_tokens=120)[0]["generated_text"])\n
_36
# 3. Chain‑of‑Thought(一步步思考)
_36
cot_prompt = """
_36
请一步步解释如何使用梯度下降训练线性回归模型:
_36
1. 定义损失函数
_36
2. 计算梯度
_36
3. 更新参数
_36
"""
_36
print(generator(cot_prompt, max_new_tokens=150)[0]["generated_text"])\n```
_36
_36
> **运行提示**:确保已安装 `transformers` 与 `torch`(`pip install transformers torch`)。
_36
_36
## 小结
_36
_36
- 通过明确指令、提供上下文、Few‑Shot 示例和 Chain‑of‑Thought,可以显著提升 LLM 的输出质量。
_36
- 练习不同的 Prompt 结构,观察模型响应的变化,逐步形成自己的 Prompt 工程技巧库。

Discussion4

Join the conversation

Sign in to share your thoughts and connect with others.

Sign In with GitHub
Michael Chang
Michael Chang·20h ago
The section on Context Windows vs RAG was really illuminating. I've been debating which approach to take for our internal knowledge base. Do you think the 1M+ context windows in newer models will eventually make RAG obsolete?
Sarah Chen
Sarah ChenAuthor·18h ago
Great question, Michael! I don't think RAG is going away anytime soon. Even with huge context windows, RAG offers better latency, cost-efficiency, and most importantly - the ability to cite sources explicitly.
Priya Patel
Priya Patel·Dec 22, 2025
I finally understand how Positional Encodings work! The visual analogy with the clock hands was brilliant. 👏
DevOps Ninja
DevOps Ninja·Dec 22, 2025
Any chance you could cover Quantization (GGUF/GPTQ) in a future post? trying to run these locally on my MacBook and it's a bit of a jungle out there.