896. Tree of Thoughts breadth-first search
Why it matters Search over reasoning steps (ToT, beam search over plans, best-of-n with a verifier) is a core agent pattern. The control loop is plain BFS with pruning.
Paper: "Tree of Thoughts: Deliberate Problem Solving with Large Language Models", Yao et al., 2023 (NeurIPS 2023), arXiv 2305.10601.
Tree of Thoughts lets a model propose several next "thoughts", score them, and keep only the best few at each step (breadth-first search with a beam of size b). Here the model calls are replaced by lookup tables so the search is deterministic.
Write tot_bfs(root, children, values, breadth, depth).
- children: dict mapping a state (str) to the list of states the model proposes from it. Missing key means no children.
- values: dict mapping a state to its value (float). Every proposed state has a value.
- Start with the frontier [root]. For each of depth steps: collect the children of every frontier state, in frontier order and then child order, dropping repeats (keep the first). If there are none, stop early. Otherwise keep the breadth states with the highest value; ties keep the earlier one in that collected order. That list, sorted by value high to low with the same tie rule, is the new frontier.
- At the end, best is the first state of the final frontier (root if no step ran).
Return a dict {"best": str, "frontiers": list of lists of str, one per step that ran}.
def tot_bfs(root, children, values, breadth, depth)Example 1
Input: tot_bfs('s', {'s': ['a', 'b', 'c'], 'a': ['a1'], 'b': ['b1', 'b2']}, {'a': 0.2, 'b': 0.9, 'c': 0.5, 'a1': 0.1, 'b1': 0.4, 'b2': 0.95}, 2, 2)
Output: {'best': 'b2', 'frontiers': [['b', 'c'], ['b2', 'b1']]}
Example 2
Input: root = 's', children = {}, values = {}, breadth = 3, depth = 5
Output: {'best': 's', 'frontiers': []}
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Build the candidate list in frontier order, skipping repeats with a set.
Hint 2
Sort indices by (-value, position) and keep the first breadth.
Hint 3
Stop early when there are no candidates.
Common mistakes
- Sorting with Python's sort on values only and losing the tie rule.
- Keeping the root in later frontiers.
- Expanding states more than once.
Understand the idea
Each step expands every kept state, scores the proposals and keeps the top b. A beam of 1 is greedy: in the fourth test it picks b (0.2) over a (0.1) and never sees c (0.9). A wider beam keeps more options alive at the cost of more model calls. Deduplication matters because different thoughts can lead to the same state.
Shapes and data flow
Dicts in, dict out.