This walkthrough follows the actual code structure, so you can map each ToT concept to concrete functions.
node examples/12_tree-of-thought/tree-of-thought.jsAt the top of the file:
HYPOTHESIS_TYPESdefines the four competing branches.BEHAVIOR_INPUTis the case description.hypothesisSchema,scoreSchema,rankingSchema,analysisSchemadefine the JSON contracts for each phase.promptJson(schema, userText)is the shared utility that:- resets chat history,
- enforces schema grammar,
- parses/repairs JSON.
This keeps each phase function focused on logic, not parser boilerplate.
developHypothesis(behavior, hypothesisType) does one thing:
- prompts the model to reason through exactly one lens,
- returns a structured object:
nameargumentsignalscounter_evidence
In runTreeOfThoughtMotivationAnalysis(), this runs in a loop over HYPOTHESIS_TYPES, creating four competing branches.
scoreHypothesis(behavior, hypothesis) returns:
score(raw numeric score from formula),details(explanatory_power,plausibility,falsifiability),blindSpot,reasoning.
rerankHypotheses(behavior, scoredHypotheses) forces a strict ranking with no ties and then maps ranks to calibrated scores:
- rank1 ->
8.8 - rank2 ->
8.1 - rank3 ->
7.4 - rank4 ->
6.7
This is why the console shows:
- captured raw evaluations
- then calibrated scores used for pruning
So learners see what the system actually uses for branch selection.
pruneHypotheses(scoredHypotheses):
- sorts descending by score,
- keeps the winner,
- returns
discardedbranches.
This is the structural heart of ToT in this example: one winner continues, alternatives are dropped.
createConclusion(behavior, winner) builds the final analysis using only:
- winner name
- winner argument
- winner signals
Discarded branches do not feed into the final answer.
That intentional limitation is shown in the console block: WHAT TOT LOST IN THIS RUN.
This function is the end-to-end controller:
- branch (collect hypotheses)
- score (raw + calibrated)
- prune (winner + discarded)
- conclude (winner only)
- print output + call visualization helper
Visualization is intentionally delegated to:
writeToTMotivationVisualization(...)
so the example file stays focused on ToT control flow.
Read functions in this sequence:
promptJsondevelopHypothesisscoreHypothesisrerankHypothesespruneHypothesescreateConclusionrunTreeOfThoughtMotivationAnalysis
That order mirrors the runtime flow and makes the file much easier to understand.