概念定义

思维树(Tree of Thoughts, ToT)是一种将大语言模型的推理过程组织成树形结构,通过系统性探索、评估和回溯来解决需要复杂规划和搜索的问题的高级推理框架。

详细解释

思维树由普林斯顿大学和谷歌DeepMind在2023年提出,是对思维链(CoT)的重大升级。ToT不再局限于线性推理路径,而是构建了一个思维的树形结构,其中每个节点代表一个中间推理状态,边代表推理步骤。这种结构允许模型进行前瞻性探索、自我评估,并在必要时回溯到之前的状态。 ToT的核心创新在于将经典的搜索算法(如深度优先搜索DFS、广度优先搜索BFS、束搜索Beam Search)与大语言模型的生成和评估能力相结合。2024年的最新进展包括不确定性思维树(TouT)、强化学习集成的ToT控制器,以及简化的单提示ToT实现。 在需要非平凡规划的任务上,ToT展现了显著优势。例如,在”24点游戏”中,GPT-4配合CoT的成功率仅为4%,而使用ToT后成功率飙升至74%。这种巨大的性能提升证明了结构化搜索在复杂推理任务中的价值。

工作原理

思维树的核心机制:
  1. 思维生成:在每个节点生成多个候选思维
  2. 状态评估:对每个思维的价值进行评分
  3. 搜索决策:选择最有前途的分支继续探索
  4. 回溯机制:遇到死胡同时返回之前的状态

实际应用

基础实现框架

ToT系统架构
class TreeOfThoughts:
    def __init__(self, llm, search_algorithm="bfs", max_depth=5):
        self.llm = llm
        self.search_algorithm = search_algorithm
        self.max_depth = max_depth
        self.memory = []  # 存储搜索历史
        
    def generate_thoughts(self, state, k=4):
        """生成k个候选思维"""
        prompt = f"""
        当前状态:{state}
        请生成{k}个不同的下一步思维:
        """
        thoughts = self.llm.generate_multiple(prompt, n=k)
        return thoughts
    
    def evaluate_thought(self, thought):
        """评估思维的价值"""
        prompt = f"""
        评估以下思维的价值(0-10分):
        {thought}
        考虑:正确性、进展、可行性
        """
        score = self.llm.evaluate(prompt)
        return score
    
    def search(self, problem):
        """执行树搜索"""
        if self.search_algorithm == "bfs":
            return self.breadth_first_search(problem)
        elif self.search_algorithm == "dfs":
            return self.depth_first_search(problem)
        elif self.search_algorithm == "beam":
            return self.beam_search(problem)

具体应用示例

24点游戏求解
def solve_24_game(numbers):
    """使用ToT解决24点游戏"""
    tot = TreeOfThoughts(llm, search_algorithm="beam")
    
    initial_state = {
        "numbers": numbers,
        "operations": [],
        "target": 24
    }
    
    # 定义思维生成规则
    def generate_step(state):
        thoughts = []
        nums = state["numbers"]
        
        # 生成所有可能的运算组合
        for i, j in combinations(range(len(nums)), 2):
            for op in ['+', '-', '*', '/']:
                thought = f"{nums[i]} {op} {nums[j]}"
                thoughts.append(thought)
        
        return thoughts
    
    # 执行搜索
    solution = tot.search_with_custom_generator(
        initial_state, 
        generate_step,
        is_goal=lambda s: len(s["numbers"]) == 1 and s["numbers"][0] == 24
    )
    
    return solution

创意写作应用

def creative_writing_tot(prompt, constraints):
    """使用ToT进行创意写作"""
    
    class StoryNode:
        def __init__(self, text, coherence_score, creativity_score):
            self.text = text
            self.coherence = coherence_score
            self.creativity = creativity_score
            self.children = []
    
    def generate_story_branches(node, num_branches=3):
        """为故事节点生成多个可能的延续"""
        branches = []
        for _ in range(num_branches):
            continuation = llm.generate(
                f"继续这个故事:{node.text}\n"
                f"约束:{constraints}"
            )
            # 评估连贯性和创意性
            scores = evaluate_story_quality(continuation)
            branches.append(StoryNode(
                continuation, 
                scores['coherence'],
                scores['creativity']
            ))
        return branches
    
    # 构建故事树并选择最佳路径
    root = StoryNode(prompt, 1.0, 1.0)
    best_story = beam_search_story(root, beam_width=3, depth=5)
    
    return best_story

2024年创新应用

不确定性思维树(TouT)
class TreeOfUncertainThoughts(TreeOfThoughts):
    """集成不确定性量化的ToT"""
    
    def evaluate_with_uncertainty(self, thought):
        """评估思维并量化不确定性"""
        # 多次采样获得分布
        scores = []
        for _ in range(5):
            score = self.llm.evaluate(thought, temperature=0.7)
            scores.append(score)
        
        mean_score = np.mean(scores)
        uncertainty = np.std(scores)
        
        return {
            'score': mean_score,
            'uncertainty': uncertainty,
            'confidence': 1 / (1 + uncertainty)
        }
    
    def risk_aware_search(self, problem, risk_tolerance=0.5):
        """考虑风险的搜索策略"""
        # 在高风险决策点要求更高确定性
        # 在低风险探索阶段允许更多不确定性
        pass

性能对比

任务GPT-4 + CoTGPT-4 + ToT提升幅度
24点游戏4%74%+1750%
创意写作41分68分+65.9%
迷你填字游戏16%78%+387.5%

相关概念

延伸阅读