You can visualize any arbitrary Graph, including StateGraph. Let's have some fun by drawing fractals :).
importrandomfromtypingimportAnnotated,Literalfromtyping_extensionsimportTypedDictfromlanggraph.graphimportStateGraph,START,ENDfromlanggraph.graph.messageimportadd_messagesclassState(TypedDict):messages:Annotated[list,add_messages]classMyNode:def__init__(self,name:str):self.name=namedef__call__(self,state:State):return{"messages":[("assistant",f"Called node {self.name}")]}defroute(state)->Literal["entry_node","__end__"]:iflen(state["messages"])>10:return"__end__"return"entry_node"defadd_fractal_nodes(builder,current_node,level,max_level):iflevel>max_level:return# Number of nodes to create at this levelnum_nodes=random.randint(1,3)# Adjust randomness as neededforiinrange(num_nodes):nm=["A","B","C"][i]node_name=f"node_{current_node}_{nm}"builder.add_node(node_name,MyNode(node_name))builder.add_edge(current_node,node_name)# Recursively add more nodesr=random.random()ifr>0.2andlevel+1<max_level:add_fractal_nodes(builder,node_name,level+1,max_level)elifr>0.05:builder.add_conditional_edges(node_name,route,node_name)else:# Endbuilder.add_edge(node_name,"__end__")defbuild_fractal_graph(max_level:int):builder=StateGraph(State)entry_point="entry_node"builder.add_node(entry_point,MyNode(entry_point))builder.add_edge(START,entry_point)add_fractal_nodes(builder,entry_point,1,max_level)# Optional: set a finish point if requiredbuilder.add_edge(entry_point,END)# or any specific nodereturnbuilder.compile()app=build_fractal_graph(3)
importnest_asyncionest_asyncio.apply()# Required for Jupyter Notebook to run async functionsdisplay(Image(app.get_graph().draw_mermaid_png(curve_style=CurveStyle.LINEAR,node_colors=NodeStyles(first="#ffdfba",last="#baffc9",default="#fad7de"),wrap_label_n_words=9,output_file_path=None,draw_method=MermaidDrawMethod.PYPPETEER,background_color="white",padding=10,)))
try:display(Image(app.get_graph().draw_png()))exceptImportError:print("You likely need to install dependencies for pygraphviz, see more here https://github.com/pygraphviz/pygraphviz/blob/main/INSTALL.txt")