Skip to content
ImagineWorld

Tree-of-Thoughts Prompting

node_idnode-book_llm-design-patterns_chapter-20-tree-of-thoughts-prompting
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num20
chapter_titleTree-of-Thoughts Prompting
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Tree-of-thoughts (ToT) prompting is a technique that was developed to enhance the problem-solving capabilities of LLMs by enabling more structured exploration of different reasoning paths.

The formal ToT approach was introduced in a 2023 research paper titled Tree of Thoughts: Deliberate Problem Solving with Large Language Models by Yao et al. (researchers from Princeton University, Google DeepMind, and Google Research). Also visit https://arxiv.org/abs/2305.10601.

The primary inspiration for ToT came from how humans approach complex problems—we often consider multiple possible solution paths, evaluate their promise, backtrack when necessary, and explore alternatives. Traditional prompting techniques such as CoT (see Chapter 20) allowed step-by-step reasoning but lacked the ability to explore multiple paths or reconsider earlier steps.

ToT builds on several techniques:

  • CoT prompting, which enables step-by-step reasoning
  • Self-consistency methods that generate multiple reasoning paths
  • Human problem-solving approaches that involve exploration and backtracking

The key innovation of ToT is treating thinking as a tree search problem, where at each step, the model can generate and evaluate multiple “thoughts” (intermediate reasoning steps) and then select the most promising paths to continue exploring. This allows for more sophisticated problem-solving that includes exploration, evaluation, and backtracking capabilities.

In this chapter, you’ll learn how to implement ToT prompting to tackle complex reasoning tasks with your LLMs.

In this chapter, we’ll be covering the following topics:

  • Designing ToT prompts
  • Search strategies
  • Pruning and evaluation
  • Applying ToT to solve a multi-step problem
  • Challenges in implementation
  • Future directions

To create effective ToT prompts, you should do the following:

  1. Encourage branching thoughts: This creates a non-linear exploration process where multiple possible solution paths can be considered simultaneously. By explicitly asking the model to generate several different initial approaches or perspectives, you prevent it from committing too early to a single line of reasoning that might lead to suboptimal results.
  2. Provide a clear problem statement: A well-defined problem statement gives the model a concrete goal and constraints to work within. This clarity helps the model understand exactly what it needs to solve and provides the foundation for generating relevant thought branches. Without this, the branching process could become unfocused and inefficient.
  3. Guide the model to explore alternative paths: This ensures the model doesn’t prematurely converge on an apparently promising but ultimately suboptimal solution. By explicitly requesting the exploration of different approaches, you help the model overcome potential bias in its reasoning and discover novel solutions it might otherwise miss.
  4. Include evaluation mechanisms: This component enables the model to assess the quality of different branches and make informed decisions about which paths to pursue further. Without evaluation criteria, the model would have no systematic way to determine which branches are most promising, potentially wasting computational resources on unpromising paths.

ToT is particularly powerful for complex reasoning tasks because it mimics human problem-solving approaches where we often mentally explore multiple possibilities before committing to a solution. The explicit branching and evaluation structure helps language models overcome limitations in their sequential reasoning abilities.

Here’s an example of implementing a basic ToT prompt:

def tot_prompt(question, num_branches=3):
prompt = f"""Solve the following problem using a Tree-of-Thoughts approach:
Problem: {question}
Let's explore multiple reasoning paths:
Path 1:
1) First, we could...
2) Then, we might...
3) This leads us to...
Path 2:
1) Alternatively, we could start by...
2) Following this approach...
3) This results in...
Path 3:
1) Another perspective is...
2) If we consider this...
3) The outcome would be...
Now, let's evaluate these paths and determine the most promising solution:
Evaluation:
1) Path 1: ...
2) Path 2: ...
3) Path 3: ...
Based on this evaluation, the most promising solution is...
Therefore, the final answer is...
Now, apply this Tree-of-Thoughts approach to solve the given problem:
{question}
Let's explore multiple reasoning paths:
"""
return prompt
Let's look at an example usage:
problem = "What is the most efficient way to sort a list of a million integers?"
prompt = tot_prompt(problem)
print(prompt)

This function generates a ToT prompt for a given problem ("What is the most efficient way to sort a list of a million integers?"), providing a structure for exploring and evaluating multiple reasoning paths.

This code creates a ToT prompt template by implementing four key principles: it encourages branching thoughts through explicit path structures with different starting phrases and numbered steps, ensuring the model explores multiple distinct solution approaches; it provides clarity by framing the problem twice to establish context and refocus attention before solution generation; it guides exploration of alternative approaches through contrasting language and separate reasoning paths; and it facilitates evaluation through a dedicated comparison section with prompts for selecting the most promising solution. The overall structure creates a cognitive scaffold that helps language models overcome linear thinking tendencies by forcing them to generate, develop, and critically compare multiple solution paths before reaching a conclusion—mimicking how humans tackle complex problems through divergent thinking followed by critical evaluation.

Implementing effective search strategies is crucial for navigating the ToT. Let’s check out two of them in the following section.

We have two commonly used search strategies:

  • Depth-first search (DFS): This is a graph traversal algorithm that explores as far as possible along each branch before backtracking. In the context of a tree of thoughts, DFS systematically dives deep into one path, exploring each thought or branch completely before moving to the next. It works by starting at the root, pushing each node’s children onto a stack, and then recursively exploring the deepest node first. This approach is particularly useful when you want to fully explore a line of reasoning or investigate the most profound or complex thoughts before branching out, making it valuable for problem-solving, decision-making, and understanding complex conceptual landscapes.
  • Breadth-first search (BFS): In contrast to DFS, BFS explores the tree of thoughts by systematically examining all neighboring nodes at the present depth before moving to nodes at the next depth level. Using a queue data structure, BFS starts at the root and explores all immediate connections before going deeper. In the context of thought exploration, BFS is particularly effective when you want to get a broad, panoramic view of different ideas and their immediate interconnections. This strategy is ideal for understanding the width and diversity of thoughts, finding the shortest path between concepts, or when you need to explore multiple potential reasoning paths simultaneously before diving deep into any single branch (see Figure 21*.1*).

Figure 21.1 – DFS versus BFS

As an example, let’s implement a simple DFS strategy:

from transformers import AutoModelForCausalLM, AutoTokenizer
def dfs_tot(model, tokenizer, problem, max_depth=3, max_branches=2):
def explore_branch(current_thought, depth):
if depth == max_depth:
return current_thought
prompt = f"{current_thought}\n\nLet's explore further:\n"
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(
inputs, max_length=len(prompt) + 100,
num_return_sequences=max_branches
)
branches = [
tokenizer.decode(
output[len(inputs['input_ids'][0]):],
skip_special_tokens=True
) for output in outputs
]
results = []
for branch in branches:
results.append(
explore_branch(
current_thought + branch, depth + 1
)
)
return max(
results, key=lambda x: evaluate_thought(x)
) # Select the best branch
initial_prompt = tot_prompt(problem)
return explore_branch(initial_prompt, 0)
def evaluate_thought(thought):
# Implement logic to evaluate the quality of a thought
# This could involve coherence, relevance, depth of reasoning, etc.
pass

This code implements a DFS algorithm to explore a ToT generated by a language model. It starts with an initial problem and then uses the model to generate multiple potential continuations (branches). The code recursively explores each branch, extending the “thought” until it reaches a maximum depth. At each step, generated text is turned into model inputs, and the model outputs are decoded back into text.

The evaluate_thought function, which is a key part of the selection process, is intended to score the quality of each generated thought. The code utilizes this scoring to decide which branches to explore further, effectively navigating the ToT toward a potentially optimal solution. The final result is the highest-scoring thought found during the DFS.

Here’s an example usage of the preceding code snippet:

model_name = "gpt2-large" # Replace with your preferred model
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
problem = "What are the potential long-term effects of artificial intelligence on employment?"
solution = dfs_tot(model, tokenizer, problem)
print(solution)

This code snippet demonstrates how to use a pre-trained GPT-2 LLM to generate a solution to a given problem using the previously described dfs_tot function. First, it specifies the model to be used ("gpt2-large") and loads both the model and its associated tokenizer using AutoModelForCausalLM and AutoTokenizer from the transformers library. This ensures the text is correctly processed for the model.

Then, it defines the problem as a question about the long-term effects of AI on employment. The dfs_tot function is called with the loaded model, tokenizer, and the problem as input, initiating the depth-first search for a solution. The returned solution, which represents the model’s generated response after exploring various “thoughts”, is finally printed to the console.

Next, we will discuss pruning and evaluation within the ToT framework to improve efficiency and focus the search. Pruning is essential for managing the computational cost associated with exploring numerous thought branches, while evaluation provides the criteria for deciding which branches to discard.

Pruning in the ToT approach is an effective mechanism for managing cognitive complexity by systematically reducing the search space. The process involves selectively eliminating less promising thought branches through intelligent evaluation techniques, using heuristic scoring methods that assess each potential path’s likelihood of leading to an optimal solution. By dynamically filtering out low-potential thoughts and focusing computational resources on the most promising reasoning trajectories, ToT pruning enables more efficient and targeted problem solving, balancing exploration breadth with reasoning depth.

  1. Let’s implement a basic pruning strategy by defining a simple
    def pruning_tot(
    model, tokenizer, problem, max_depth=3,
    max_branches=3, prune_threshold=0.5
    ):
    def explore_and_prune(current_thought, depth):
    if depth == max_depth:
    return current_thought
    prompt = f"{current_thought}\n\nLet's explore further:\n"
    inputs = tokenizer(prompt, return_tensors="pt")
    outputs = model.generate(
    inputs, max_length=len(prompt) + 100,
    num_return_sequences=max_branches
    )
    branches = [
    tokenizer.decode(
    output[len(inputs['input_ids'][0]):],
    skip_special_tokens=True
    ) for output in outputs
    ]
    The core of the logic is in the explore_and_prune function, which handles the recursive search through the reasoning tree. The code works by generating multiple possible continuations (branches) from the current thought using LLM. The function is designed to explore the reasoning tree up to a specified maximum depth, with each level containing a controlled number of branches. When the maximum depth is reached, the code returns the current thought as the final result. The pruning mechanism is illustrative and should not be used for production.
  2. Once we’ve defined our function, we evaluate and
    evaluated_branches = [
    (branch, evaluate_thought(current_thought + branch))
    for branch in branches
    ]
    pruned_branches = [
    b for b, score in evaluated_branches
    if score > prune_threshold
    ]
    if not pruned_branches:
    return current_thought # If all branches are pruned, return current thought
    results = []
    for branch in pruned_branches:
    results.append(
    explore_and_prune(current_thought + branch,
    depth + 1)
    )
    return max(results, key=lambda x: evaluate_thought(x))
    initial_prompt = tot_prompt(problem)
    return explore_and_prune(initial_prompt, 0)
    First, the code evaluates each generated branch by pairing it with a score from the evaluate_thought function, which assesses the quality of the reasoning path. It then filters out low-quality branches by keeping only those scoring above the defined threshold. If all branches are pruned (none meet the threshold), the algorithm returns the current thought without further exploration. For the remaining promising branches, the code recursively explores each one by calling the same function at an increased depth level. Finally, it selects the best overall reasoning path by returning the result with the highest evaluation score from all explored paths. The outer function initializes the search with a formatted prompt containing the original problem statement.
  3. Define an evaluate_thought function. This function evaluates a given thought or branch of reasoning by scoring it based on its complexity (length) and linguistic diversity (the number of unique words used), returning a normalized score between 0 and 1:
    def evaluate_thought(branch, threshold=0.5):
    """
    Simple evaluation function for ToT branch assessment
    Args:
    branch (str): The branch/thought to evaluate
    threshold (float): Minimum score for considering a branch viable
    Returns:
    float: Evaluation score
    """
    # Basic heuristics for evaluation
    complexity_score = len(branch.split()) / 20 # Reward moderate complexity
    uniqueness_score = len(
    set(branch.split())) / len(branch.split()
    ) # Reward unique words
    # Combined score, normalized
    score = (complexity_score + uniqueness_score) / 2
    return min(1.0, max(0.0, score))
  4. Let’s look at
    problem = "What are the ethical implications of genetic engineering in humans?"
    solution = pruning_tot(model, tokenizer, problem)
    print(solution)

This implementation adds a pruning step to remove low-quality branches, focusing the search on the most promising paths.

Now, let’s apply ToT to solve a multi-step problem.

Applying ToT to solve a multi-step problem

Section titled “Applying ToT to solve a multi-step problem”

ToT can be particularly effective for complex reasoning tasks. Let’s implement a ToT approach for multi-step problem solving:

def multi_step_tot(model, tokenizer, problem_steps):
full_solution = ""
for step, question in enumerate(problem_steps):
prompt = f"""Step {step + 1} of the problem:
{question}
Previous steps solution:
{full_solution}
Let's use Tree-of-Thoughts to solve this step:
"""
step_solution = pruning_tot(model, tokenizer, prompt)
full_solution += (
f"\n\nStep {step + 1} Solution:\n"
f"{step_solution}"
)
return full_solution
# Example usage
problem_steps = [
"What are the main factors contributing to climate change?",
"How do these factors interact with each other?",
"What are potential solutions to mitigate climate change?",
"What are the challenges in implementing these solutions?"
]
solution = multi_step_tot(model, tokenizer, problem_steps)
print(solution)

This code implements a multi-step problem solver using the ToT reasoning approach. The multi_step_tot function breaks down complex problems into sequential steps and solves them one at a time, building upon previous solutions.

For each step in the provided problem sequence, the function creates a prompt that includes the current question, the accumulated solutions from previous steps, and instructions to use ToT reasoning. It then calls the previously defined pruning_tot function to generate a solution for that specific step. Each step’s solution is appended to a growing full_solution string, creating a comprehensive answer that maintains continuity of thought across the entire problem. The example demonstrates how this approach could be applied to analyze climate change through a sequence of progressively deeper questions, from identifying causes to exploring implementation challenges of potential solutions.

While powerful, ToT faces several challenges:

  • Computational complexity: Exploring multiple paths can be computationally expensive
  • Evaluation difficulty: Determining the quality of different thought paths can be challenging
  • Coherence across branches: Ensuring consistency when combining insights from different branches
  • Prompt design complexity: Creating effective ToT prompts requires careful consideration

To address the computational complexity, consider implementing a parallel processing approach. Parallel processing can improve the ToT reasoning approach by addressing its inherent computational bottlenecks. The following code implements concurrent exploration of multiple reasoning branches simultaneously rather than sequentially, which can dramatically reduce the total computation time for complex problems:

import concurrent.futures
def parallel_tot(model, tokenizer, problem, max_workers=3):
def explore_branch(branch):
return pruning_tot(model, tokenizer, branch)
initial_branches = generate_initial_branches(problem, max_workers)
with concurrent.futures.ThreadPoolExecutor(
max_workers=max_workers
) as executor:
futures = [
executor.submit(explore_branch, branch)
for branch in initial_branches
]
results = [
f.result()
for f in concurrent.futures.as_completed(futures)
]
return max(results, key=lambda x: evaluate_thought(x))
def generate_initial_branches(problem, num_branches):
# Implement logic to generate initial branches for the problem
pass
# Example usage
problem = "What are the potential implications of quantum computing on cryptography?"
solution = parallel_tot(model, tokenizer, problem)
print(solution)

In the preceding code, the implementation uses Python’s concurrent.futures module with a ThreadPoolExecutor to distribute the workload across multiple workers. Each worker independently explores a different initial branch of the reasoning tree, effectively searching multiple promising paths in parallel. This approach is particularly valuable for ToT reasoning since the branching nature of the algorithm creates numerous independent subproblems that can be solved concurrently without dependencies on each other’s intermediate results. The final step consolidates these parallel explorations by selecting the highest-quality solution from all completed branches.

This implementation uses parallel processing to explore multiple branches simultaneously, potentially reducing computation time for complex ToT problems.

As ToT continues to evolve, several promising directions emerge:

  • Dynamic tree structures: Adapting the tree structure based on the problem complexity.
  • Hybrid ToT-CoT approaches: Combining the strengths of both techniques (https://arxiv.org/html/2409.17433v1).
  • Meta-learning for ToT: Training LLMs to generate effective ToT structures automatically. This approach has not been explored by anyone yet.
  • Incorporating external knowledge: Integrating domain-specific knowledge into ToT reasoning (https://arxiv.org/html/2407.00653v1).

Here’s a conceptual implementation of a dynamic ToT structure:

def dynamic_tot(model, tokenizer, problem, max_depth=5):
def adapt_structure(current_thought, depth):
if depth == max_depth:
return current_thought
complexity = assess_complexity(current_thought)
num_branches = determine_branches(complexity)
branches = generate_branches(
model, tokenizer, current_thought, num_branches
)
results = []
for branch in branches:
results.append(
adapt_structure(
current_thought + branch, depth + 1
)
)
return max(results, key=lambda x: evaluate_thought(x))
def assess_complexity(thought):
# Implement logic to assess the complexity of the current thought
pass
def determine_branches(complexity):
# Determine the number of branches based on complexity
return max(2, min(5, int(complexity 10)))
def generate_branches(model, tokenizer, thought, num_branches):
# Generate branches using the model
pass
initial_prompt = tot_prompt(problem)
return adapt_structure(initial_prompt, 0)

The preceding code implements a dynamic ToT approach that adapts its exploration strategy based on the complexity of the current reasoning path. The core function adapt_structure recursively builds a solution by examining the complexity of the current thought at each step and dynamically determining how many branches to explore. Unlike fixed branching strategies, this adaptive approach allocates more computational resources (more branches) to complex reasoning paths that might benefit from broader exploration, while using fewer branches for simpler concepts. The implementation includes helper functions to assess thought complexity, determine the appropriate number of branches, and generate new thought continuations using the language model. The algorithm terminates when reaching the maximum depth and returns the highest-scoring complete reasoning path.

Here’s an example of how to use the preceding code to solve a problem such as “ How might advancements in nanotechnology impact medicine in the next decade?”:

problem = "How might advancements in nanotechnology impact medicine in the next decade?"
solution = dynamic_tot(model, tokenizer, problem)
print(solution)

This dynamic ToT approach adapts the tree structure based on the assessed complexity of each thought, allowing the more flexible and efficient exploration of complex problem spaces.

In this chapter, you learned how to design and implement ToT prompts for LLMs, including strategies for managing the branching thought processes. We covered search techniques and methods for pruning and evaluating different reasoning paths. By implementing the strategies and considerations discussed here, you can significantly enhance your LLM’s ability to handle ambiguous, multi-faceted problems and generate more robust and insightful solutions.

Revisiting Chapter 20, which focuses on CoT, let’s compare CoT and ToT from a use case perspective. Use CoT prompting when the task involves linear, sequential reasoning that can be decomposed into intermediate steps with a single, dominant solution path. CoT is particularly effective in math word problems, deductive reasoning, basic logical puzzles, and step-by-step procedural tasks. It works well when the problem has low branching complexity and does not require exploration of multiple alternatives. CoT is computationally cheaper because it produces a single chain of reasoning in a forward, deterministic manner. This technique is most helpful when the LLM needs a scaffold to “think aloud” and make its intermediate steps explicit to prevent hallucinations or faulty leaps in logic.

Use ToT prompting when the task involves multi-step reasoning with branching decision points, especially where multiple solution paths are possible and need to be evaluated in parallel. ToT is suited for creative problem-solving, planning tasks, theorem proving, code synthesis, and decision-making under uncertainty. It becomes advantageous when the problem space can be structured as a search tree, where intermediate reasoning nodes can be revisited, evaluated, and compared. ToT often incorporates strategies such as self-consistency sampling, lookahead evaluation, and value-based selection among branches. It is computationally more intensive because it maintains and expands multiple reasoning paths in parallel, potentially involving rollouts, backtracking, or node scoring.

If the problem is constrained and well-formed (e.g., SAT-style questions or straightforward derivations), CoT is usually sufficient and more efficient. If the problem is open-ended, has multiple conflicting goals, or if optimal solutions require comparing alternative paths (as in planning routes, game moves, or formal proofs), ToT yields better performance by simulating exploration and deliberation.

In practice, CoT can serve as a base technique, while ToT builds on it by orchestrating multiple chains. For example, ToT nodes may each use CoT internally to generate coherent thoughts. Therefore, the two are not mutually exclusive but hierarchically related in terms of complexity and structure.

In the upcoming chapter, we will explore the Reasoning and Acting (ReAct) pattern, which is commonly used in many agentic AI applications.

Get This Book's PDF Version and Exclusive Extras