提示词工程
few-shot、CoT、system prompt、structured output。
35 分钟
提示词工程
提示词不是「魔法咒语」,而是 把任务、约束与输出格式写进上下文,让 LLM 在有限窗口内做对事。AI 工程师要会 system prompt 设计、few-shot、CoT 与 structured output——对应 ai-engineer 的 prompt-engineering 节点。
学习目标
- 分层设计 system / developer / user 消息
- 用 few-shot 与 CoT 提升复杂推理与格式稳定度
- 强制 JSON / schema 输出,便于下游解析与测试
消息分层
messages = [
{"role": "system", "content": SYSTEM}, # 角色、红线、输出格式
{"role": "user", "content": FEW_SHOT_EXAMPLES}, # 可选:示例对
{"role": "user", "content": user_query},
]
| 层级 | 放什么 | 避免 |
|---|---|---|
| system | 任务定义、拒答规则、cite 要求 | 塞入整库文档(应走 RAG) |
| few-shot | 2–5 个输入输出样例 | 样例与真实分布不一致 |
| user | 当前问题与变量 | 与 system 矛盾的指令 |
站内讲义场景:system 写「仅依据检索片段;无则拒答;链接用 /tracks/... 格式」,与 ai-engineering-essentials 内容规范一致。
Few-shot 与 Chain-of-Thought
Few-shot:给模型看「输入 → 期望输出」样例,适合分类、抽取、固定模板。
CoT:要求「先逐步推理,再给最终答案」,适合多步算术、规则判定、调试分析。
用户:这段 RAG 为何仍幻觉?
助手(CoT):
1. 检查检索 top_k 是否命中相关 chunk
2. 检查 system 是否允许无片段时自由发挥
3. 结论:…
CoT 增加 token 与延迟;生产可对 简单意图 跳过,对 高价值链 开启。
Structured Output
下游 Agent、评测脚本需要 可解析 结果:
schema = {
"type": "object",
"properties": {
"answer": {"type": "string"},
"citations": {"type": "array", "items": {"type": "string"}},
"confidence": {"type": "number"},
},
"required": ["answer", "citations"],
}
# OpenAI response_format / Gemini JSON mode / 本地 json_repair 兜底
失败策略:解析失败 → 重试一次(temperature=0)→ 仍失败则返回错误码,勿静默吞掉。与 testing-essentials 的断言思维一致。
与 RAG / Agent 的配合
- RAG:system 写 grounded 规则;user 里拼
{{retrieved_chunks}} - :system 写工具使用顺序与终止条件(见 aen-agents)