Prompt工程进阶:思维链、自一致性与推理增强技术
超越零样本的推理增强 Prompt工程已从简单的指令编写进化为一门系统化的方法论。在需要复杂推理的任务中,恰当的推理增强技术可以将模型准确率提升30-50%。 思维链(Chain-of-Thought) 基本CoT 思维链的核心思想是让模型"展示推理过程"。通过在prompt中加入"让我们一步步思考"或提供推理示例: Q: 一个商店有23个苹果,卖了17个后又进了8个,现在有多少苹果? A: 让我们一步步思考。 初始数量:23 卖出17个后:23 - 17 = 6 又进了8个后:6 + 8 = 14 答案:14 CoT对数学推理、逻辑推理和多步规划任务效果显著。在GSM8K数学基准上,CoT将GPT-4的准确率从约75%提升到92%。 Zero-shot CoT 最简单的CoT只需在prompt末尾添加: 让我们一步步思考。 这五个字的魔力在于:它激活了模型在预训练阶段学到的"推理模式",使模型生成中间推理步骤而非直接跳到答案。 Few-shot CoT 提供2-4个带有推理过程的示例,效果更好但消耗更多token。关键是示例的推理过程要正确且简洁——过长的推理链反而会降低性能。 自一致性(Self-Consistency) 核心思想 CoT的一个问题是:同一条推理路径可能系统性偏向错误答案。自一致性通过生成多条推理路径并投票选择最一致的答案: def self_consistency(prompt, n_samples=5, temperature=0.7): responses = [] for _ in range(n_samples): response = llm.generate( prompt + "\n让我们一步步思考。", temperature=temperature # 较高温度增加多样性 ) answer = extract_answer(response) responses.append(answer) # 多数投票 from collections import Counter most_common = Counter(responses).most_common(1)[0] return most_common[0] 在GSM8K上,自一致性将准确率从92%进一步提升到96%+。代价是推理成本增加5倍。 采样策略 温度:0.5-0.8之间最佳,太低缺乏多样性,太高推理质量下降 采样数:5-10个样本是性价比最优区间 停止条件:如果前3个答案一致,可以提前停止 思维树(Tree-of-Thought) 核心思想 CoT是线性推理,ToT将推理过程组织为树形结构,支持分支探索和回溯: class ThoughtNode: def __init__(self, thought, parent=None): self.thought = thought self.parent = parent self.children = [] self.value = 0 评估值 self.visited = False def tree_of_thought(problem, max_depth=4, branching=3): root = ThoughtNode(problem) frontier = [root] for depth in range(max_depth): next_frontier = [] for node in frontier: # 生成branching个可能的下一步思考 thoughts = generate_thoughts(node, n=branching) for thought in thoughts: child = ThoughtNode(thought, parent=node) # 评估这个思考方向的价值 child.value = evaluate_thought(thought, problem) node.children.append(child) next_frontier.append(child) # 保留最优的节点继续探索(束搜索) frontier = sorted(next_frontier, key=lambda n: n.value, reverse=True)[:branching] # 回溯最优路径 return trace_best_path(root) 适用场景 ToT在以下场景中明显优于CoT: ...