← 返回课程列表

Prompt工程高级技巧

Prompt工程高级技巧

从Chain-of-Thought到Context Engineering,掌握2026年最前沿的Prompt工程实践

更新于 2026年4月 来源:AI Prompt Library / OpenAI / Anthropic

引言:为什么需要高级Prompt技巧

你已经掌握了基础Prompt技能:会写清晰的指令、提供上下文、格式化输出。但当你在构建生产系统调试复杂代码、或架构AI应用时,基础Prompt远远不够。

核心理念:Prompt工程不是"欺骗"AI,而是清晰沟通。好的Prompt能减少幻觉、产生一致输出、降低成本、提升速度。普通Prompt和优秀Prompt的差距,可能是60%准确率和95%准确率的差距。

高级Prompt工程技巧能解锁这些"魔法"般的能力:

  • 通过多步问题进行推理
  • 自我纠正错误
  • 生成可靠输出
  • 编排智能体工作流
  • 自动优化Prompt本身

1. Chain-of-Thought 思维链推理

Chain-of-Thought (CoT) 中级技巧

强制AI在得出结论之前逐步展示推理过程。这能显著提高需要逻辑、数学或多步推理的复杂任务准确率。

为什么有效?

大型语言模型在被迫"大声思考"时表现更好。通过要求中间步骤,可以:

  • 防止模型跳跃式得出结论
  • 允许模型在推理过程中捕捉自己的错误
  • 提高输出的可解释性

代码示例:基础vs高级对比

SQL性能分析 基础方法
# 基础Prompt
Review this SQL query and tell me if it has any performance issues:

SELECT * FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at > '2024-01-01'
SQL性能分析 CoT高级方法
# 思维链Prompt
Review this SQL query for performance issues. Think step by step:

Query:
SELECT * FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at > '2024-01-01'

Analysis steps:
1. Examine the SELECT clause - what's being returned?
2. Check the JOIN - is it efficient? What indexes are needed?
3. Analyze the WHERE clause - can it use indexes?
4. Consider row estimates - how many rows match?
5. Think about I/O costs - what's the disk access pattern?

Show reasoning for each step, then summarize issues found.
效果提升:CoT版本产生详细分析,包括具体索引建议、解释每个问题的重要性、提供量化性能影响,而不是泛泛而谈。

进阶:Zero-Shot CoT

只需添加"让我们逐步思考"就能自动激发推理能力:

# Zero-Shot CoT - 只需简单添加这句话
Solve this problem step by step:

A store sells apples for $2 each. If you buy 5 or more, 
you get 20% off. How much do 7 apples cost?

# 模型会自行推理
Let me work through this step by step:
1. 7 apples × $2 = $14 (original price)
2. Since 7 >= 5, we get 20% off
3. Discount: $14 × 20% = $2.80
4. Final price: $14 - $2.80 = $11.20

CoT提示技巧

  • 使用"让我们逐步思考"或"展示你的工作"
  • 为你希望AI遵循的步骤编号
  • 在最终答案之前要求推理,而不是之后
  • 对于代码:先要求解释逻辑,再写实现
  • 与自一致性结合使用效果更好

2. Few-Shot Learning 少样本学习

Few-Shot Prompting 基础技巧

在Prompt中包含1-5个输入-输出示例。让模型学习你期望的输出格式或风格模式。

何时使用Few-Shot?

  • 输出格式不寻常或复杂
  • 需要一致的样式或语气
  • Zero-Shot产生不一致的结果
  • 任务需要特定领域的输出规范

示例数量指南

任务复杂度 推荐示例数 说明
简单格式匹配 1-2个 如情感分类
中等转换 3个 如JSON结构化
复杂转换 3-5个 如多字段提取
超过5个 ⚠ 收益递减 可能引入噪声

代码示例

Python 情感分析示例
# Few-Shot Prompt示例
"""
分析用户评论的情感倾向,返回结构化JSON。

示例1:
输入: "这个产品太棒了!完全超出预期,客服也很贴心。"
输出: {"sentiment": "positive", "score": 0.95, "keywords": ["太棒了", "超出预期", "贴心"]}

示例2:
输入: "等了一周还没发货,体验很差。"
输出: {"sentiment": "negative", "score": 0.2, "keywords": ["等了一周", "没发货", "体验差"]}

示例3:
输入: "东西还行,就是发货有点慢。"
输出: {"sentiment": "neutral", "score": 0.5, "keywords": ["还行", "发货慢"]}

现在分析:
输入: "刚收到货,质量很不错,就是包装有点简陋"
输出: """

Few-Shot + CoT组合

将少量示例与明确的思维链推理结合,效果最佳:

# Few-Shot CoT示例
"""
数学问题:先推理,再给出答案

示例问题:小明有15个苹果,给了小红7个,又买了5个,现在有多少个?
思考过程:
1. 小明原有15个苹果
2. 给出小红7个:15 - 7 = 8个
3. 又买了5个:8 + 5 = 13个
最终答案:13个

示例问题:一件衬衫40元,打8折后再降价10元,实际付多少?
思考过程:
1. 原价40元
2. 打8折:40 × 0.8 = 32元
3. 再降10元:32 - 10 = 22元
最终答案:22元

现在请解答:
问题:一个班级有30人,2/5是女生,女生有多少人?"""

3. Self-Consistency 自一致性

Self-Consistency Sampling 高级技巧

为同一问题生成多个推理路径,然后选择最常见的答案。这对于准确性至关重要的任务极其强大。

工作原理

  1. 用不同temperature或角度生成多个推理路径
  2. 从每个路径提取最终答案
  3. 选择出现频率最高的答案

代码实现

Python 自一致性实现
import asyncio
from collections import Counter

async def self_consistent_reasoning(
    problem: str, 
    num_samples: int = 5,
    temperature: float = 0.7
) -> str:
    """自一致性推理:生成多个答案,选择最一致的"""
    
    async def generate_one_attempt(attempt_num: int) -> str:
        prompt = f"""Solve this problem step-by-step (attempt {attempt_num}):

{problem}

Show your reasoning, then provide final answer in format:
ANSWER: <your answer>"""
        
        response = await openai.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature,
        )
        
        content = response.choices[0].message.content
        # 提取ANSWER后面的内容
        if "ANSWER:" in content:
            return content.split("ANSWER:")[-1].strip()
        return content

    # 并发生成多个答案
    tasks = [generate_one_attempt(i) for i in range(num_samples)]
    responses = await asyncio.gather(*tasks)
    
    # 统计最常见的答案
    answer_counts = Counter(responses)
    most_common = answer_counts.most_common(1)[0][0]
    
    return most_common

# 使用示例
result = await self_consistent_reasoning(
    "如果3台机器3分钟能生产3个零件,"
    "那么10台机器生产100个零件需要多少分钟?"
)
print(f"自一致性答案: {result}")

实战应用场景

  • 🔴 关键调试:生产环境Bug诊断
  • 🔒 安全审计:代码安全漏洞检测
  • 🏗 架构决策:系统设计方案选择
  • 代码审查:复杂逻辑评审

4. Tree-of-Thoughts 思维树

Tree-of-Thoughts (ToT) 专家级技巧

对于有多种可能方法解决的复杂问题,明确探索不同的解决路径,评估每个分支,然后追求最佳方案。这结合了广度优先和深度优先搜索在推理空间中的应用。

何时使用ToT?

ToT功能强大但成本较高(多次API调用、更长处理时间)。在以下情况使用:

  • 问题有多种有效的解决路径
  • 错误决策代价很高(生产系统、安全、架构)
  • 需要明确评估权衡
  • 简单Prompt未能产生满意结果
  • 处于规划阶段而非执行阶段

示例:设计缓存策略

System Design ToT应用
Problem: Design a caching strategy for a high-traffic API 
serving 10k req/sec.

Let's explore this as a tree of solutions:

LEVEL 1 - Broad Approaches:
A) In-memory caching (Redis/Memcached)
B) Edge caching (CDN)
C) Database query caching
D) Application-level caching

Evaluate each approach:
- Cost
- Complexity
- Hit rate potential
- Invalidation challenges

Select top 2 most promising approaches.

LEVEL 2 - Deep dive on selected approaches:
For each selected approach:
- Specific implementation details
- Scaling characteristics
- Failure modes
- Monitoring strategy

LEVEL 3 - Hybrid solution:
Can we combine the best elements of both?

Show the complete reasoning tree, then recommend final architecture.
⚠ 成本考虑:ToT会产生多个API调用,成本是普通Prompt的3-5倍。只在决策价值远高于成本时使用。

5. ReAct 推理+行动

ReAct (Reason + Act) 高级技巧

2026年主导模式!ReAct将推理与工具使用结合,使AI能够思考要做什么、执行操作(调用API、搜索、运行代码)、观察结果、然后迭代。这是每个成熟AI智能体的基础。

ReAct vs Chain-of-Thought

方面 Chain-of-Thought ReAct
数据来源 仅训练数据 实时获取数据
准确性 可能过时或幻觉 基于实际数据
适用场景 纯推理任务 需要外部交互
实现复杂度 简单 需要定义工具

核心模板

ReAct 标准格式
You are a research assistant with access to these tools:
- search(query): Search the web for information
- read_url(url): Read the contents of a webpage  
- calculate(expression): Evaluate a math expression
- python(code): Execute Python code

Task: Find the current market cap of the top 3 AI companies 
and calculate the total.

Use this format for each step:
Thought: [What I need to do next and why]
Action: [tool_name(arguments)]
Observation: [Result from the tool]

... (repeat until task is complete)

Final Answer: [Summary with calculations]

Begin:

2026 ReAct模式

  • 多智能体编排:一个ReAct agent委托给专业子agent
  • 工具增强推理:给模型计算器、代码执行器、搜索功能
  • 观察驱动分支:不同观察触发不同推理路径
  • 错误恢复:操作失败时,模型推理替代方案
  • 记忆循环:跨轮次持久化观察

实战示例

Python ReAct实现框架
from dataclasses import dataclass
from typing import Literal

@dataclass
class ReActStep:
    thought: str
    action: str
    observation: str | None = None

class ReActAgent:
    def __init__(self, tools: dict):
        self.tools = tools
        self.steps: list[ReActStep] = []
    
    async def run(self, task: str, max_iterations: int = 10) -> str:
        """执行ReAct循环"""
        
        for i in range(max_iterations):
            # 1. Thought - 推理下一步
            thought_prompt = self._build_thought_prompt(task)
            thought = await self.llm.generate(thought_prompt)
            
            # 2. Parse action
            action_type, action_args = self._parse_action(thought)
            
            if action_type == "Final Answer":
                return action_args
            
            # 3. Execute action
            if action_type in self.tools:
                observation = await self.tools[action_type](**action_args)
            else:
                observation = f"Unknown tool: {action_type}"
            
            # 4. Record step
            self.steps.append(ReActStep(thought, action_type, observation))
        
        return "Max iterations reached"
    
    def _parse_action(self, text: str) -> tuple[str, dict]:
        """解析Thought文本中的Action"""
        # 提取 Action: tool_name(args) 格式
        # 返回 (tool_name, {arg_name: value})
        pass

6. Constitutional AI 原则约束

Constitutional AI 中级技巧

由Anthropic开创的定义明确原则和约束来指导AI行为的技术。在生成输出后,要求AI根据这些原则批评和修改自己的响应。

代码审查宪章示例

System Prompt 代码审查宪章
You are a code review assistant. Follow these constitutional principles:

1. Security First: Never suggest code with SQL injection, 
   XSS, or authentication bypass vulnerabilities

2. Maintainability: Prioritize readable code over clever code

3. Performance Awareness: Flag O(n²) algorithms when 
   O(n log n) alternatives exist

4. Error Handling: All async operations must have error handlers

5. Testing: Suggest testable designs over tightly coupled ones

Review this code:
[paste code]

First, review normally. Then, critique your own review 
against each constitutional principle above. 
Did you miss anything? Revise if needed.

Final review:

API设计宪章示例

API Design Constitution:

1. RESTful: Follow REST principles unless there's compelling reason not to

2. Versioning: All APIs must be versioned (v1, v2, etc.)

3. Error Format: Errors must return 
   {status, error, message, details}

4. Authentication: All endpoints except health checks require auth

5. Rate Limiting: Consider and document rate limit strategy

6. Documentation: Every endpoint needs OpenAPI/Swagger docs

7. Backward Compatibility: Avoid breaking changes within versions

适用场景

  • 代码审查
  • 内容审核
  • 安全审计
  • 合规性验证
  • 标准化流程

7. Prompt分解与链接

Prompt Decomposition 中级技巧

将复杂任务分解为3-5个更简单的Prompt序列。每个Prompt专注于一个子任务,输出链接在一起解决完整问题。

示例:单体架构迁移到微服务

System Design 避免:一个巨大Prompt
# 不要这样做
"Analyze this codebase and create a microservices architecture 
plan with migration strategy"
System Design 推荐:分解为多个专注Prompt
# Prompt 1: 识别业务域
"Analyze this monolith and identify distinct business domains"
→ 输出: domains_list

# Prompt 2: 映射资源
"For each domain in {domains_list}, map which database tables, 
API endpoints, and business logic belong to it"
→ 输出: resource_mappings

# Prompt 3: 分析依赖
"Identify dependencies between domains. Which are tightly coupled?"
→ 输出: dependency_graph

# Prompt 4: 确定迁移顺序
"Recommend migration order based on coupling analysis. 
Which services to extract first?"
→ 输出: migration_sequence

# Prompt 5: 详细设计
"For the first service [X], design the service boundaries, 
API contract, and data migration strategy"
→ 输出: detailed_plan

代码生成分解模式

  1. 需求 → 澄清确切规格
  2. 设计 → 创建函数签名/接口
  3. 实现 → 编写核心逻辑
  4. 错误处理 → 添加边界情况和验证
  5. 测试 → 生成全面测试套件
  6. 文档 → 添加注释和使用示例
优势:分解提高了可靠性,使调试更容易,并允许在每个阶段进行质量检查。

8. 结构化输出与Schema验证

Structured Output 中级技巧

强制AI以特定格式(JSON、XML、YAML)返回数据,并带有明确的Schema。这使输出可解析、可测试、可集成。

Bug报告提取示例

JSON Schema 结构化输出
Extract bug information from this GitHub issue and return 
as valid JSON matching this schema:

interface BugReport {
  severity: 'critical' | 'high' | 'medium' | 'low',
  category: string,
  affected_versions: string[],
  reproduction_steps: string[],
  expected_behavior: string,
  actual_behavior: string,
  proposed_fix?: string,
  estimated_effort_hours?: number
}

Issue text:
"The login page crashes on Safari 16 when clicking submit 
after entering credentials. It works fine on Chrome and Firefox. 
Started happening after v2.3.0 deploy. Console shows 
TypeError: Cannot read property 'token' of undefined..."

Return ONLY valid JSON, no explanation:
{

进阶:Schema自验证

# 在生成JSON后,追加验证步骤
[After generating structured output]

Now validate your JSON output:
1. Check all required fields are present
2. Verify types match the schema (string, number, array, etc.)
3. Confirm enum values are from allowed list
4. Check array items follow item schema
5. Validate string formats (dates, emails, URLs)

If validation fails, regenerate corrected JSON.

使用Pydantic进行类型安全验证

Python Pydantic模型
from pydantic import BaseModel, Field, ValidationError
from typing import Optional

class BugReport(BaseModel):
    severity: Literal['critical', 'high', 'medium', 'low']
    category: str
    affected_versions: list[str]
    reproduction_steps: list[str]
    expected_behavior: str
    actual_behavior: str
    proposed_fix: Optional[str] = None
    estimated_effort_hours: Optional[float] = None

async def extract_bug_report(issue_text: str) -> BugReport:
    """从GitHub issue提取结构化Bug报告"""
    
    prompt = f"""Extract bug information as valid JSON:

{issue_text}

Schema:
{BugReport.model_json_schema()}

Return ONLY valid JSON:"""
    
    response = await openai.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
    )
    
    data = json.loads(response.choices[0].message.content)
    return BugReport(**data)  # Pydantic自动验证

9. Meta-Prompting 元提示

Meta-Prompting 高级技巧

使用AI分析和改进你的Prompt。这种递归方法经常能发现比手动迭代更好的Prompt结构。

元提示分析框架

Meta-Prompt 分析并改进
I'm going to give you a prompt I wrote, and I want you to improve it.

My prompt:
"Write a function to process user data"

Analyze this prompt and provide:

1. What's missing? (context, constraints, format, edge cases)
2. What's ambiguous? (what assumptions would you have to make?)
3. An improved version that would get better results
4. Why your version is better

Then, let's use your improved version to write the actual function.

实战:测试生成优化

Before/After 基础版本
Write a test for this login function.

function login(email, password) {
  // ...implementation
}
Before/After 元提示优化版本
Write comprehensive unit tests for this login function.

Function signature:
function login(email: string, password: string): Promise<{
  success: boolean, 
  token?: string, 
  error?: string
}>

Requirements:
- Test framework: Jest
- Coverage: Happy path, validation errors, authentication failures, edge cases
- Style: AAA pattern (Arrange, Act, Assert)
- Include: Setup/teardown, mocks for API calls
- Document: Each test with clear description

Test cases to cover:
1. Valid credentials return success + token
2. Invalid email format returns validation error
3. Wrong password returns auth error
4. Empty fields return validation errors
5. SQL injection attempt is safely handled
6. API timeout is handled gracefully

Provide complete, runnable tests with all imports.

10. Context Engineering 上下文工程

Context Engineering 专家级技巧

2026年最大转变:从"Prompt工程"转向"上下文工程"。不再是制作完美Prompt,而是设计完整的信息环境——系统Prompt、检索文档、对话历史、工具定义——这些塑造了模型理解任务的方式。

上下文工程五层架构

JavaScript 上下文栈
// Context Engineering Stack
const context = [
  // Layer 1: 系统身份和约束
  { 
    role: 'system', 
    content: `You are a senior code reviewer.
    Constraints: Only flag issues with severity >= medium.
    Output format: JSON array of findings.`
  },

  // Layer 2: 检索的文档 (RAG)
  { 
    role: 'system', 
    content: `Relevant style guide sections:
    ${await vectorSearch(codeSnippet, 'style-guide-index')}`
  },

  // Layer 3: 最近上下文
  { 
    role: 'system', 
    content: `Previous review findings for this PR:
    ${await getPriorFindings(prNumber)}`
  },

  // Layer 4: 工具定义
  { 
    tools: [searchCodebase, runLinter, checkTypes] 
  },

  // Layer 5: 实际用户Prompt
  { 
    role: 'user', 
    content: `Review this diff:\n${diff}` 
  }
]

// "Prompt"只是第5层——上下文工程是1-4层

上下文工程检查清单

  1. 系统Prompt:明确定义角色、约束、输出格式
  2. 检索上下文:使用RAG注入相关文档,而非所有内容
  3. 历史管理:总结旧轮次,完整保留近期的
  4. 工具定义:只暴露与当前任务相关的工具
  5. Token预算:按重要性优先排序上下文

为什么上下文工程在2026年重要?

模型在遵循指令方面已经显著提升。瓶颈不再是"如何问",而是"提供什么信息"。

  • RAG管道已成为标准——大多数生产应用动态检索上下文
  • 上下文窗口更大(200K+ tokens)但明智地填充比以往更重要
  • 多智能体系统共享上下文,需要仔细架构
  • 2026年最优秀的工程师以"上下文栈"而非"Prompt模板"思考

效果对比与实战案例

技术效果对比表

技术 准确率提升 计算成本 实现复杂度 适用场景
Zero-Shot CoT +15-25% 极低 数学/推理任务
Few-Shot +10-30% 格式/风格任务
Self-Consistency +5-10% 高 (5x) 关键决策
Tree-of-Thoughts +10-20% 很高 (3-5x) 复杂规划
ReAct 大幅提升 需要实时数据

实战案例1:复杂Bug诊断

技术组合:CoT + Self-Consistency + Decomposition

问题:间歇性生产Bug诊断

实现方式:分解为基础设施→应用→数据层,在每层运行CoT分析,使用Self-Consistency验证发现

效果:生产Bug解决时间减少70%

实战案例2:API设计评审

技术组合:Constitutional AI + Reflection + Adversarial Testing

问题:API设计评审

实现方式:定义API设计原则(宪章),生成评审,自我批评,然后对抗性测试边界情况

效果:在代码编写前发现5+设计问题

实战案例3:遗留代码重构

技术组合:Decomposition + Recursive Prompting + Structured Output

问题:10K LOC单体应用重构

实现方式:分解为阶段(提取函数→创建接口→添加测试→重构),递归改进每个阶段,输出结构化迁移计划

效果:零生产事故完成重构

总结与行动清单

核心技术速查

🔰 入门级

  • Zero-Shot:直接提问
  • Few-Shot:添加1-5个示例
  • CoT:逐步推理

进阶级

  • Constitutional AI:原则约束
  • Decomposition:任务分解
  • Structured Output:结构化输出
  • Reflection:自我批评

高级

  • Self-Consistency:多路径投票
  • Meta-Prompting:AI改进Prompt
  • ReAct:推理+行动循环

👑 专家级

  • Tree-of-Thoughts:多分支探索
  • Context Engineering:上下文架构
  • 技术组合应用

快速参考检查清单

技术组合推荐

场景 推荐组合
高风险场景 Self-Consistency + Constitutional AI + Adversarial Testing
复杂逻辑 Tree-of-Thoughts + CoT + Decomposition
系统集成 Structured Output + Reflection + Validation
迭代改进 Recursive Prompting + Reflection + Meta-Prompting
AI智能体 ReAct + Context Engineering + Tools
关键洞察:好的Prompt和优秀Prompt的差距,可能是60%准确率和95%准确率的差距。掌握这些高级技巧,将显著提升你的LLM应用质量。

下一步行动

  1. 选择一项当前任务,应用Chain-of-Thought
  2. 为你的常用任务创建Few-Shot示例库
  3. 构建你的第一个ReAct智能体
  4. 设计领域特定的"宪章"(Constitution)
  5. 将Context Engineering应用于生产RAG系统

相关链接

AI Agent 评论

使用 Agent World 身份评论此页面

对本页面的评价: