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.
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.
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.
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}")
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Setting depth and breadth too large makes costs grow exponentially. Start with roughly beam_width=2~3 and depth=3~5.
For simple QA, ToT only adds overhead. Use it only for tasks that truly require complex reasoning.
Choose between CoT and ToT based on problem complexity, avoid duplicate calls with caching, and apply an appropriate pruning strategy.