Skip to content

第 11 章 · 自洽性与生成知识

本章目标:掌握 Tree of Thoughts(思维树)的搜索与评估机制,理解 Prompt Chaining 的分步策略,并学会组合使用高级提示技术解决复杂问题。

11.1 Tree of Thoughts(思维树)

ToT 是 CoT 的扩展,核心思想是:将推理过程建模为树结构,在每一步生成多个可能的"思维"(thought),然后通过搜索算法选择最优路径。

ToT vs CoT

特性CoTToT
推理结构线性序列树状分支
探索能力单一路径多路径搜索
回溯能力❌ 无✅ 支持
计算成本
适用场景简单推理复杂规划/搜索

ToT 的三个核心组件

  1. Thought 生成器:给定当前状态,生成多个可能的下一步思维
  2. State Evaluator:评估每个思维的潜力(0-1 分数)
  3. Search Algorithm:广度优先搜索(BFS)或最佳优先搜索
python
from typing import List, Tuple
import heapq

class TreeOfThoughts:
    def __init__(self, llm, max_depth=5, branching_factor=3):
        self.llm = llm
        self.max_depth = max_depth
        self.branching_factor = branching_factor
    
    def generate_thoughts(self, state: str, n: int) -> List[str]:
        """生成 n 个可能的下一步思维"""
        prompt = f"""Given the current state: "{state}"
Generate {n} possible next thoughts, each starting with "Thought: "
"""
        response = self.llm.complete(prompt)
        return self._parse_thoughts(response)
    
    def evaluate_thought(self, thought: str, goal: str) -> float:
        """评估思维对目标的接近程度"""
        prompt = f"""On a scale of 0 to 1, how close is this thought to solving the problem?
Goal: {goal}
Thought: {thought}
Rating (0-1):"""
        score = self.llm.complete(prompt)
        return float(score.strip())
    
    def search(self, initial_state: str, goal: str) -> Tuple[str, List[str]]:
        """使用 Best-First Search 找到解决方案"""
        # 优先队列:(负分数,深度,状态,路径)
        heap = [(-1.0, 0, initial_state, [initial_state])]
        visited = {initial_state}
        
        while heap:
            neg_score, depth, state, path = heapq.heappop(heap)
            
            if self._is_goal(state, goal):
                return state, path
            
            if depth >= self.max_depth:
                continue
            
            # 生成新思维
            thoughts = self.generate_thoughts(state, self.branching_factor)
            for thought in thoughts:
                if thought not in visited:
                    visited.add(thought)
                    score = self.evaluate_thought(thought, goal)
                    heapq.heappush(heap, (-score, depth + 1, thought, path + [thought]))
        
        return None, path

11.2 Prompt Chaining(提示链)

Prompt Chaining 将一个复杂任务拆分为多个子任务,每个子任务的输出作为下一个子任务的输入:

任务分解:
原始问题 → 子任务 1 → 中间结果 1 → 子任务 2 → 中间结果 2 → ... → 最终答案

实现示例

python
def prompt_chaining(question: str, llm) -> dict:
    """
    多阶段提示链处理复杂问题
    """
    # 阶段 1:分析问题,提取关键信息
    analysis_prompt = f"""Analyze the following question and identify:
1. Key entities and their relationships
2. What type of information is needed
3. Potential sub-questions to answer

Question: {question}

Analysis:"""
    analysis = llm.complete(analysis_prompt)
    
    # 阶段 2:基于分析制定回答策略
    strategy_prompt = f"""Based on the analysis, create a step-by-step plan to answer the question.
Analysis: {analysis}

Plan:"""
    plan = llm.complete(strategy_prompt)
    
    # 阶段 3:执行计划,收集信息
    execution_prompt = f"""Execute the following plan to answer the question.
Plan: {plan}
Question: {question}

Evidence gathered:"""
    evidence = llm.complete(execution_prompt)
    
    # 阶段 4:综合证据,生成最终答案
    final_prompt = f"""Based on all the evidence, provide a comprehensive answer.
Question: {question}
Evidence: {evidence}

Final Answer:"""
    final_answer = llm.complete(final_prompt)
    
    return {
        'question': question,
        'analysis': analysis,
        'plan': plan,
        'evidence': evidence,
        'final_answer': final_answer
    }

11.3 Meta-Prompting:让模型优化自己的提示

Meta-Prompting 利用模型自身的能力来改进提示质量:

python
def meta_prompt_optimizer(original_prompt: str, llm) -> str:
    """让模型优化自己的提示"""
    optimization_prompt = f"""You are an expert prompt engineer. Optimize the following prompt to get better results.
Consider: clarity, specificity, examples, constraints.

Original Prompt:
{original_prompt}

Optimized Prompt:"""
    return llm.complete(optimization_prompt)

使用场景

  • 自动化 A/B 测试:生成多个 prompt 变体并比较效果
  • 领域适配:针对特定领域优化通用 prompt
  • 错误修复:根据失败案例自动调整 prompt

11.4 组合使用:ToT + Prompt Chaining

对于超复杂问题,可以将 ToT 和 Prompt Chaining 组合:

python
def hybrid_approach(question: str, llm) -> dict:
    """
    组合方法:先用 Prompt Chaining 分解问题,
    再对每个子问题使用 ToT 搜索
    """
    # Step 1: 分解问题
    decomposition = decompose_question(question, llm)
    
    results = {}
    for sub_question in decomposition:
        # Step 2: 对每个子问题使用 ToT
        totp_result = run_tot_search(sub_question, llm, max_depth=3)
        results[sub_question] = totp_result
    
    # Step 3: 综合所有子结果
    synthesis_prompt = f"""Synthesize the following sub-results into a comprehensive answer.
Question: {question}
Sub-results: {results}

Synthesis:"""
    final_answer = llm.complete(synthesis_prompt)
    
    return {'final_answer': final_answer, 'sub_results': results}

11.5 实践建议

  1. 先尝试简单方法:Prompt Chaining 通常比 ToT 更容易实现和维护
  2. 评估成本收益:ToT 的搜索成本随深度和分支因子指数增长
  3. 混合策略:简单子问题用 CoT,复杂子问题用 ToT
  4. 监控质量:定期检查生成思维的多样性和质量

本章小结

  • ToT:树状搜索结构,支持回溯和多路径探索
  • Prompt Chaining:分步处理,每步专注单一子任务
  • Meta-Prompting:利用模型能力优化提示本身
  • 组合策略:根据问题复杂度选择合适的方法

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. Tree of Thoughts 相比 Chain-of-Thought 的主要优势是?

2. Prompt Chaining 的核心思想是?

3. Meta-Prompting 的主要用途是?

4. ToT 的搜索算法通常不包括?

🛠️ 动手实践

  1. 实现一个简单的 ToT 搜索器,解决需要多步规划的谜题(如数独、滑块拼图)。
  2. 设计一个 Prompt Chaining 系统,将"写一篇技术博客"拆分为:大纲→引言→正文→结论。
  3. 实现 Meta-Prompting 优化器,自动改进用户提供的 prompt 模板。

下一章:ReAct:推理与行动协同