πŸ€– AI/ML

Tree-of-Thought

ToT / Tree of Thoughts

An advanced prompting technique that explores multiple reasoning paths in a tree structure. Greatly improves LLM performance on complex problem solving.

πŸ“– Detailed Explanation

Tree-of-Thought (ToT) is a prompting technique that extends Chain-of-Thought (CoT), letting an LLM explore and evaluate multiple reasoning paths rather than a single one to find the best answer. It resembles how humans solving a complex problem consider several possibilities and choose the most promising path.

ToT was introduced in 2023 by researchers at Princeton and Google DeepMind. Whereas Chain-of-Thought allows only linear reasoning, ToT applies search algorithms such as BFS (breadth-first search) or DFS (depth-first search) to find better solutions. It showed large performance gains over CoT on tasks such as "Game of 24" and creative writing.

ToT has three core components. First, it decomposes a "thought" into intermediate steps. Second, the LLM self-evaluates the value of each thought. Third, it explores promising paths first and backtracks from dead ends. This overcomes the limitations of greedy decoding.

In practice, ToT is effective for tasks that require complex reasoning, such as solving math problems, code generation, strategy games, and planning. However, because it explores multiple paths, you must consider the increase in API call costs. Features such as extended thinking in Claude 3.5 Sonnet incorporate the ToT concept internally.

πŸ’» Code Example

An example implementation of Tree-of-Thought using LangChain.

from openai import OpenAI
import json
from typing import List, Dict

client = OpenAI()

def generate_thoughts(problem: str, current_state: str, n_thoughts: int = 3) -> List[str]:
    """ν˜„μž¬ μƒνƒœμ—μ„œ κ°€λŠ₯ν•œ λ‹€μŒ 생각듀을 생성"""
    prompt = f"""문제: {problem}

ν˜„μž¬ μ§„ν–‰ 상황: {current_state}

κ°€λŠ₯ν•œ λ‹€μŒ 단계λ₯Ό {n_thoughts}κ°€μ§€ μ œμ•ˆν•˜μ„Έμš”.
각 λ‹¨κ³„λŠ” ν•œ μ€„λ‘œ κ°„κ²°ν•˜κ²Œ μž‘μ„±ν•˜μ„Έμš”.
ν˜•μ‹: 1. [단계] 2. [단계] 3. [단계]"""

    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7
    )

    # 생각듀 νŒŒμ‹±
    text = response.choices[0].message.content
    thoughts = [t.strip() for t in text.split("\n") if t.strip()]
    return thoughts[:n_thoughts]

def evaluate_thought(problem: str, thought: str) -> float:
    """각 μƒκ°μ˜ μœ λ§λ„λ₯Ό 0-1 μ‚¬μ΄λ‘œ 평가"""
    prompt = f"""문제: {problem}

μ œμ•ˆλœ 접근법: {thought}

이 접근법이 문제 해결에 μ–Όλ§ˆλ‚˜ μœ λ§ν•œμ§€ 0μ—μ„œ 10 사이 점수둜 ν‰κ°€ν•˜μ„Έμš”.
점수만 숫자둜 λ‹΅ν•˜μ„Έμš”."""

    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.1
    )

    try:
        score = float(response.choices[0].message.content.strip()) / 10
        return min(max(score, 0), 1)
    except:
        return 0.5

def tree_of_thought_solve(problem: str, max_depth: int = 3, beam_width: int = 2) -> str:
    """Tree-of-Thought둜 문제 ν•΄κ²° (Beam Search 방식)"""

    # 초기 μƒνƒœ
    beams = [{"path": [], "score": 1.0}]

    for depth in range(max_depth):
        new_beams = []

        for beam in beams:
            current_state = " -> ".join(beam["path"]) if beam["path"] else "μ‹œμž‘"

            # λ‹€μŒ κ°€λŠ₯ν•œ 생각듀 생성
            thoughts = generate_thoughts(problem, current_state)

            for thought in thoughts:
                # 각 생각 평가
                score = evaluate_thought(problem, thought)

                new_beams.append({
                    "path": beam["path"] + [thought],
                    "score": beam["score"] * score
                })

        # μƒμœ„ beam_width개만 μœ μ§€ (κ°€μ§€μΉ˜κΈ°)
        new_beams.sort(key=lambda x: x["score"], reverse=True)
        beams = new_beams[:beam_width]

        print(f"Depth {depth + 1}: Top beam score = {beams[0]['score']:.3f}")

    # μ΅œμ’… λ‹΅ 생성
    best_path = " -> ".join(beams[0]["path"])
    final_prompt = f"""문제: {problem}

μΆ”λ‘  κ³Όμ •: {best_path}

μœ„ 좔둠을 λ°”νƒ•μœΌλ‘œ μ΅œμ’… 닡을 μ œμ‹œν•˜μ„Έμš”."""

    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[{"role": "user", "content": final_prompt}]
    )

    return response.choices[0].message.content

# μ‚¬μš© μ˜ˆμ‹œ
problem = "8, 3, 1, 6 λ„€ 숫자λ₯Ό μ‚¬μΉ™μ—°μ‚°μœΌλ‘œ μ‘°ν•©ν•˜μ—¬ 24λ₯Ό λ§Œλ“œμ„Έμš”."
solution = tree_of_thought_solve(problem)
print(f"\nμ΅œμ’… λ‹΅:\n{solution}")

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"Simple CoT only got us 60% accuracy, but after switching to Tree-of-Thought it rose to 85%. API costs tripled, but it was worth it for a task where quality matters."
πŸ’¬ In an Interview
"I applied ToT to a complex code generation task. I had it explore multiple implementation options and pick the best code through self-evaluation, and the bug rate dropped by 40%."
πŸ’¬ In a Technical Discussion
"The key to ToT is the quality of self-evaluation. If the LLM can't evaluate its own reasoning accurately, it goes down the wrong path. Adding a separate critic model is one way to handle that."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌

API cost explosion

Setting depth and breadth too large makes costs grow exponentially. Start with roughly beam_width=2~3 and depth=3~5.

❌

Over-applying it to simple problems

For simple QA, ToT only adds overhead. Use it only for tasks that truly require complex reasoning.

βœ…

The right way

Choose between CoT and ToT based on problem complexity, avoid duplicate calls with caching, and apply an appropriate pruning strategy.

πŸ”— Related Terms

πŸ“š Learn More