Tree-of-Thought (ToT) helps agents compare possible plans before acting. It generates options, checks them and drops weak branches. Set limits from the start: a trial might allow 20 candidates and £0.50 per attempt - but these are sample limits, not proven targets.
More search does not guarantee better results. A useful ToT planner needs:
- Clear checks: test plans against facts, permissions and task constraints - not model confidence alone.
- Execution gates: keep planning separate from tool use, with human approval for high-impact actions.
- Measured results: compare verified completion, cost, latency and recovery with a simpler, single-path planner.
ToT can work alongside tool use and plan review. The deciding rule is simple: use extra search only when measured gains justify its cost and risk.
::: @figure
{Tree-of-Thought Planning: Search, Gate, Verify}
:::
49. Tree of Thoughts in AI Agents
How Agents Generate, Evaluate and Search
Inside the planner, ToT runs a search loop over structured states.
Define the State and Generate Next Steps
Each node represents a structured task state: the objective, known facts, completed actions, current resources, dependencies, unresolved risks and measurable success criteria.
A “thought” is an auditable proposed action, sub-goal or plan segment - not a private reasoning transcript. Generate a small set of candidates, each with prerequisites, an expected resulting state and a way to validate it. Keep expected outcomes marked as unverified until evidence confirms them. Branching factor (b) and depth (d) determine the search size: (1 + b + … + b^d).[2][3]
Score Options, Prune Branches and Backtrack
Score candidates on feasibility, progress, risk, cost, factual support and time. Hard constraints override scores: a missing permission or rollback path rules out a branch, regardless of its score.
Remove equivalent states using normalised fields, such as version and migration status. If a later check fails, return to the last viable simulated state and try another path.[2][3]
Breadth-first search checks states level by level. Depth-first search follows one branch before returning to alternatives. Best-first search expands the highest-scoring state.
Stop only when checks pass or the search limit is reached - not when the model claims confidence. A verified plan is a candidate for execution, not proof of success.[2][3]
A deployment plan shows how these rules work.
Hypothetical Example: Plan a SaaS Deployment
Consider the hypothetical task: deploy version 4.2 within a 22:00–23:00 UK maintenance window and preserve customer data. Starting candidates are A: verify backups and dependencies; B: deploy directly to production; C: deploy to a canary environment. Reject B if direct production deployment violates policy, then expand A and C. These are proposed sequences - not deployment commands.[2][3]
Validate migration compatibility, backup availability, dependency health and rollback readiness. A failed compatibility check sends the planner back to revise the sequence. A selected sequence could then proceed through canary deployment, monitoring agreed metrics and staged rollout, with a recorded rollback trigger. Before approval, verify that rollout and rollback fit the window, data-protection rules hold, and health and error thresholds are met. Without that evidence, the branch remains unverified and must not trigger production changes.[2][3]
Where ToT Fits in an Agent Architecture
ToT sits inside the agent pipeline as the planning layer. It turns a goal into candidate actions, checks them against the current state and constraints, then passes only approved actions to execution.
Short-term state tracks the current task. Long-term memory supplies reusable policies and past outcomes. Retrieved material should include its source and how up to date it is. The planner should return a proposed action with its rationale, inputs, expected outcome and estimated confidence.
The boundary is clear: the planner proposes; execution still needs a gate.
Connect the Planner to Tools and Checks
After generating, evaluating and pruning candidates, the agent sends the selected plan or next action through validation and approval. These gates prevent an unchecked branch from causing an actual change. The agent then observes the result, updates its state and replans if needed.
Keep read-only tools separate from tools that change systems. Immediately before a state-changing tool acts, an execution gate must check identity, scope, parameters, risk, approvals and limits in the execution environment.
High-impact actions should pause for explicit human approval. Record the selected action, policy decision, approver, tool result, timestamp and resulting state.
Compare observations with the expected outcome. Failed preconditions, changed permissions or unexpected results should trigger replanning. If a write times out, check whether it completed before retrying. An unknown result is neither success nor failure.
Compare ToT with Other Planning Patterns
The table below shows where ToT fits. The main difference is how much searching each pattern does before acting. These are typical behaviours, not fixed boundaries: cost depends on model calls, tool calls and evaluations.
| Pattern | Search behaviour | Tool use | Plan revision | Cost | Suitable tasks |
|---|---|---|---|---|---|
| Chain-of-Thought | Usually follows one sequential path | Optional | Usually continues forward | Usually low | Straightforward, well-defined problems |
| ReAct | Alternates reasoning, actions and observations | Central | Revises after observations | Variable | Interactive research and troubleshooting |
| Reflection | Critiques an existing attempt | Optional | Revises after evaluation | Variable | Improving an answer, plan or artefact |
| Tree-of-Thought | Searches, scores and prunes branches | Optional | Revises during search and after observations | Medium to high | Multi-step tasks with meaningful alternatives |
| Graph-based planning | Searches linked states or subplans | Optional | Merges paths and revisits states | Variable, often high | Shared subgoals, dependencies and cycles |
These patterns can work together. ReAct gathers observations, ToT searches candidate plans, and reflection critiques the selected plan. Graph-based planning is a broader family that includes tree search, directed acyclic graphs, state-transition graphs and workflow planners.
Backtracking in a plan does not undo an executed action. That requires a safe, tested compensating action in the connected tool and business workflow.
A task with one clear path and few meaningful alternatives calls for a simpler approach.
Build and Test a ToT Planner with Limits
Once you’ve defined the search pattern, set firm limits so you can test it. Start with one bounded workflow, fixed test data and clear acceptance criteria. Keep the planner, policy checks, executor and verifier separately testable.
Implement the Loop and Set Search Limits
For a hypothetical pilot, allow four successors per state, a beam width of three and a depth of five. Cap each attempt at 20 candidates, 12,000 total tokens, 12 tool calls, 45 seconds and £0.50. Rejected branches, retries and replanning all count towards the same budget.
The loop below shows the minimum control structure for a bounded prototype - not a production recipe.
state = initialise(request, authoritative_records, constraints)
if missing_or_conflicting_fields(state):
return CLARIFICATION_REQUIRED
frontier = [state]
plan = none
while frontier and budget.remaining():
current = pop_best(frontier)
candidates = generate_successors(current, maximum=4)
for candidate in candidates:
if not budget.remaining():
break
budget.count_candidate()
if schema_valid(candidate) and preconditions_hold(candidate):
successor = simulate_transition(current, candidate)
if deterministic_checks_pass(successor):
successor.score = score_with_fixed_rubric(successor)
frontier.add(successor)
frontier = deduplicate_and_prune(frontier, width=3, depth=5)
plan = independently_verify_complete_plan(frontier)
if plan:
break
if not plan:
return classify_stop(
BUDGET_EXHAUSTED,
CLARIFICATION_REQUIRED,
NO_VALID_SOLUTION,
ESCALATE_TO_OPERATOR
)
approval = authorise(plan, current_state_version)
if not approval.granted:
return ESCALATE_TO_OPERATOR
result = execute_approved_actions(plan, remaining_budget)
observation = independently_verify_result(result)
if observation.success:
return VERIFIED_SUCCESS
return replan(observation, remaining_budget)
Prevent Evaluation Errors and Unsafe Actions
More branches cannot fix a faulty evaluator. Check the starting state against authoritative records. Reject invented identifiers and invalid dependencies before scoring, then use fixed weights with labelled test cases. Validate candidate schemas, test good, bad and ambiguous cases, and deduplicate states before caching evaluations.
Keep state validation, branch scoring, approval and execution checks separately testable. Enforce permissions outside the model. Log structured records rather than private reasoning transcripts: request ID, initial state, candidate IDs, scores, selected branch, policy decisions, tool calls, approvals, observed results and final status.[6]
Compare Results with a Simpler Baseline
Test the planner against a single-path baseline using the same workload and limits. Keep the model, tools and context constant. Include successes, impossible requests, missing information, stale records, tool failures and adversarial instructions. Repeat trials to spot inconsistent scoring. Search is worth using only if the results justify its extra cost.
The table gives hypothetical acceptance targets. Calculate completion as independently verified successes divided by all attempted cases. Count correct refusals and clarification requests only when they match the labelled expected outcome.
| Metric | Baseline result | ToT result | Acceptance criterion |
|---|---|---|---|
| Verified completion rate | Not measured | Not measured | At least 95% of eligible tasks |
| Proposed invalid actions | Not measured | Not measured | No more than 2% of proposed actions |
| Executed invalid actions | Not measured | Not measured | 0 for production actions |
| Recovery rate | Not measured | Not measured | At least 80% of recoverable failures |
| Branches explored per task | Not measured | Not measured | No more than 20 |
| P95 latency | Not measured | Not measured | No more than 60 seconds |
| Tokens per task | Not measured | Not measured | Within the approved token budget |
| Tool calls per task | Not measured | Not measured | No more than 12 |
| Cost per verified task | Not measured | Not measured | No more than £0.50 |
Report zero denominators as “not applicable”, not 0%. When calculating cost per verified task, include failed attempts, retries, model calls, tools, infrastructure and review costs. Move from proposal-only runs to sandbox testing, then to human-approved production use.
Hokstad Consulting can help define the first workflow, governance and a modular architecture. This lets you test the planner, policy engine, tool adapters, approval service and verification layer separately. Performance figures must come from your own evaluation.
Conclusion: Use Search When Results Justify It
After generation, scoring and pruning, the rule is simple: use ToT only when search improves verified outcomes. Generate candidate steps, score them against the goal and constraints, and search only the strongest branches. Execute only authorised actions and audit the result. A high-scoring branch is still just a hypothesis.[4][3][8]
Start with one narrow, verifiable workflow in production. Use search only when conflicting evidence, failed checks or high-cost decisions justify it.[10]
Add more search only when that first workflow shows verified gains outweigh cost, latency and deployment risk. Otherwise, use a simpler planner.[9][7][5]
FAQs
How do I choose which planning steps to branch on?
Choose paths only when verified inputs, available tools and clear business goals support them. Check each path before execution: it must be authorised, needed and logically consistent, and stay within budget, deadline and safety limits.
Block execution if goals are unclear or authorisation is missing. Refer decisions with material financial or rights-related effects to a named owner. For complex workflows, map dependencies in structured, versioned plans.
How can I check plans without relying on model confidence?
Use a validation gate: all seven checks must pass before execution. Check that goals and completion criteria are clear, dependencies are accounted for, tools are accessible, tasks are in the right order, resource and cost limits are met, scheduling fits the allowed time windows, and approval rules are satisfied.
Judge plans using objective, verifiable evidence - such as successful system responses, business rules and predefined acceptance thresholds - not model confidence.
How do I keep plans valid when system state changes?
Treat validation as a continuous gate, not a one-off check [1]. If any prerequisite, tool access, dependency or security policy changes, pause execution immediately [1]. Log the change, revalidate the whole plan against the new conditions and get approval again before resuming [1]. Never let an agent carry on with outdated context or stale data: this leads to approval drift [1].