A node in a tree structure representing a step in the reasoning process.
This class implements a tree node that stores content (text describing a reasoning step), maintains parent-child relationships, tracks node statistics, and provides utilities for traversing/visualizing the reasoning path.
PARAMETER | DESCRIPTION |
content | The text content/description for this reasoning step. TYPE: str |
parent | The parent node in the tree, if any. TYPE: Optional[ThinkNode] DEFAULT: None |
ATTRIBUTE | DESCRIPTION |
content | The text content/description for this reasoning step. TYPE: str |
value | A numeric score/value assigned to this node. TYPE: float |
parent | Reference to the parent node. TYPE: Optional[ThinkNode] |
reflection | A string containing reflections on the reasoning process. TYPE: str |
rating_details | A string providing details about the rating of this node. TYPE: str |
depth | The depth of this node in the tree (root = 0). TYPE: int |
children | TYPE: list[ThinkNode] |
visits | Number of times this node has been visited during search. TYPE: int |
The node automatically maintains the tree structure by: - Setting its depth based on the parent's depth + 1. - Adding itself to the parent's children list if the parent exists. - Providing trajectory utilities to get the full path from root to this node.
Source code in autogen/agents/experimental/reasoning/reasoning_agent.py
| def __init__(self, content: str, parent: Optional["ThinkNode"] = None) -> None:
"""A node in a tree structure representing a step in the reasoning process.
This class implements a tree node that stores content (text describing a reasoning step),
maintains parent-child relationships, tracks node statistics, and provides utilities
for traversing/visualizing the reasoning path.
Args:
content (str): The text content/description for this reasoning step.
parent (Optional[ThinkNode]): The parent node in the tree, if any.
Attributes:
content (str): The text content/description for this reasoning step.
value (float): A numeric score/value assigned to this node.
parent (Optional[ThinkNode]): Reference to the parent node.
reflection (str): A string containing reflections on the reasoning process.
rating_details (str): A string providing details about the rating of this node.
depth (int): The depth of this node in the tree (root = 0).
children (list[ThinkNode]): list of child nodes.
visits (int): Number of times this node has been visited during search.
The node automatically maintains the tree structure by:
- Setting its depth based on the parent's depth + 1.
- Adding itself to the parent's children list if the parent exists.
- Providing trajectory utilities to get the full path from root to this node.
"""
self.content: str = content
self.value: float = 0.0
self.parent: Optional[ThinkNode] = parent
self.reflection: str = ""
self.rating_details: str = ""
self.depth: int = parent.depth + 1 if parent is not None else 0
self.children: list[ThinkNode] = []
self.visits: int = 0
if self.parent:
self.parent.children.append(self)
|
content instance-attribute
parent instance-attribute
reflection instance-attribute
rating_details instance-attribute
depth instance-attribute
depth = depth + 1 if parent is not None else 0
children instance-attribute
visits instance-attribute
trajectory property
Get a formatted string representation of the path from root to this node.
RETURNS | DESCRIPTION |
str | A formatted string showing the question and each step in the reasoning process TYPE: str |
backpropagate
Update the score of this node and its parents using moving average.
PARAMETER | DESCRIPTION |
reward | The reward to backpropagate up the tree. TYPE: float |
Source code in autogen/agents/experimental/reasoning/reasoning_agent.py
| def backpropagate(self, reward: float) -> None:
"""Update the score of this node and its parents using moving average.
Args:
reward (float): The reward to backpropagate up the tree.
"""
node: Optional[ThinkNode] = self
while node is not None:
node.visits += 1
node.value = (node.value * (node.visits - 1) + reward) / node.visits
node = node.parent
|
to_dict
Convert ThinkNode to dictionary representation.
RETURNS | DESCRIPTION |
dict[str, Any] | dict[str, Any]: dictionary containing all node attributes and recursive children |
Source code in autogen/agents/experimental/reasoning/reasoning_agent.py
| def to_dict(self) -> dict[str, Any]:
"""Convert ThinkNode to dictionary representation.
Returns:
dict[str, Any]: dictionary containing all node attributes and recursive children
"""
return {
"content": self.content,
"value": self.value,
"depth": self.depth,
"reflection": self.reflection,
"rating_details": self.rating_details,
"visits": self.visits,
"children": [child.to_dict() for child in self.children],
}
|
from_dict classmethod
from_dict(data, parent=None)
Create ThinkNode from dictionary representation.
RETURNS | DESCRIPTION |
ThinkNode | Reconstructed node with all children TYPE: ThinkNode |
Source code in autogen/agents/experimental/reasoning/reasoning_agent.py
| @classmethod
def from_dict(cls, data: dict[str, Any], parent: Optional["ThinkNode"] = None) -> "ThinkNode":
"""Create ThinkNode from dictionary representation.
Args:
data (dict[str, Any]): dictionary containing node data
parent (Optional[ThinkNode]): Parent node to attach to
Returns:
ThinkNode: Reconstructed node with all children
"""
node = cls(content=data["content"], parent=parent)
node.value = data["value"]
node.depth = data["depth"]
node.visits = data["visits"]
node.reflection = data.get("reflection", "")
node.rating_details = data.get("rating_details", "")
# Recursively create children
for child_data in data["children"]:
cls.from_dict(child_data, parent=node)
return node
|
visualize_tree
Visualize the tree of thoughts using graphviz.
Source code in autogen/agents/experimental/reasoning/reasoning_agent.py
| def visualize_tree(self) -> None:
"""Visualize the tree of thoughts using graphviz."""
with optional_import_block() as result:
from graphviz import Digraph
if not result.is_successful:
print("Please install graphviz: pip install graphviz")
return
dot = Digraph(comment="Tree of Thoughts")
dot.attr(rankdir="TB") # Top to Bottom direction
def add_nodes(node: ThinkNode, node_id: str = "0") -> None:
# Truncate long content for better visualization
display_content = (node.content[:50] + "...") if len(node.content) > 50 else node.content
# Add node with stats
label = f"{display_content}\n visits: {node.visits}\n value: {node.value}"
dot.node(node_id, label)
# Recursively add children
for i, child in enumerate(node.children):
child_id = f"{node_id}_{i}"
add_nodes(child, child_id)
dot.edge(node_id, child_id)
add_nodes(self)
# Render the graph
try:
dot.render("tree_of_thoughts", view=False, format="png", cleanup=True)
except Exception as e:
print(f"Error rendering graph: {e}")
print("Make sure graphviz is installed on your system: https://graphviz.org/download/")
|