Visualizing LangGraph Structure With One Line of Code

  • β€’ Hello everyone, I am Student Zhang, sharing AI knowledge and practical cases daily.

  • β€’ Please like and follow πŸ‘ for continuous learning and consistent valuable output.

  • β€’ +v: jasper_8017 let’s communicate πŸ’¬ and improve together πŸ’ͺ.

Overview of Articles on Official Account

Visualizing LangGraph Structure With One Line of Code

Visualization is a very, very, very useful and friendly tool. In this article, we will realize the visualization of the LangGraph structure. When the LangGraph structure you create becomes more complex, you can use it to conveniently investigate and optimize logic.

It can be done with just one line of code, very simple.

0. Example Demo

0.1 Complete Code

First, here is the complete code, run it successfully before we continue.

from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.prebuilt import chat_agent_executor
from langchain_core.messages import HumanMessage

tools = [TavilySearchResults(max_results=1)]
model = ChatOpenAI()

app = chat_agent_executor.create_function_calling_executor(model, tools)

app.get_graph().print_ascii()

0.2 Pitfall: No module named ‘grandalf’

Encountered an issue during runtime:

Visualizing LangGraph Structure With One Line of Code

Simply install grandalf:

pip install -U grandalf -i https://pypi.tuna.tsinghua.edu.cn/simple

0.3 Running Result

Visualizing LangGraph Structure With One Line of Code

You can see that the visualized graph is the same as the graph I drew in the last article:

Visualizing LangGraph Structure With One Line of Code

1. Code Explanation

The code is simple, with just two lines of effective code:

(1) app = chat_agent_executor.create_function_calling_executor(model, tools), creates a Graph.

(2) app.get_graph().print_ascii(), prints the graph in ASCII format.

1.1 create_function_calling_executor

This is actually just a wrapper for the LangGraph creation process we implemented in the last article, the source code is as follows:

Visualizing LangGraph Structure With One Line of Code

1.2 print_ascii

From the running results, the final effect is to print out the nodes and edges, with some extra spaces and asterisks. The implementation principle is not difficult, but organizing the display effect (such as the number of spaces and asterisks) seems to be quite challenging. Here is some of the source code, just for reference:

def draw_ascii(self) -> str:
    return draw_ascii(
        {node.id: node_data_str(node) for node in self.nodes.values()},
        [(edge.source, edge.target) for edge in self.edges],
    )

def print_ascii(self) -> None:
    print(self.draw_ascii())  # noqa: T201

def draw_ascii(vertices: Mapping[str, str], edges: Sequence[Tuple[str, str]]) -> str:
    """Build a DAG and draw it in ASCII.

    Args:
        vertices (list): list of graph vertices.
        edges (list): list of graph edges.

    Returns:
        str: ASCII representation

    Example:
        >>> from dvc.dagascii import draw
        >>> vertices = [1, 2, 3, 4]
        >>> edges = [(1, 2), (2, 3), (2, 4), (1, 4)]
        >>> print(draw(vertices, edges))
        +---+     +---+
        | 3 |     | 4 |
        +---+    *+---+
          *    **   *
          *  **     *
          * *       *
        +---+       *
        | 2 |      *
        +---+     *
             *    *
              *  *
               **
             +---+
             | 1 |
             +---+
    """

2. A More Aesthetic Visualization

The tutorial also describes another way of visualization, with the result as follows:

Visualizing LangGraph Structure With One Line of Code

The code is as follows:

# Replace this line: app.get_graph().print_ascii()
from IPython.display import Image
Image(app.get_graph().draw_png())

Before running, you need to install the following dependencies:

pip install -U prompt_toolkit  -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -U grandalf -i https://pypi.tuna.tsinghua.edu.cn/simple

During installation, you might encounter the following issue: ERROR: Could not build wheels for pygraphviz, which is required to install pyproject.toml-based projects.

Visualizing LangGraph Structure With One Line of Code
For solutions on Windows platform, you can refer to this article:
https://savleen307.medium.com/pygraphviz-installation-in-windows-f45cc6fed981

3. Conclusion

This article introduces two methods for visualizing LangGraph, which can be accomplished with just one line of code:

app.get_graph().print_ascii()

or

Image(app.get_graph().draw_png())

where app is the LangGraph you constructed:

workflow = StateGraph(AgentState)
......
app = workflow.compile()

4. References

  • β€’ https://github.com/langchain-ai/langgraph/blob/main/examples/visualization.ipynb

If you find this article helpful, please give it a like and follow ~~~

  • β€’ Hello everyone, I am Student Zhang, sharing AI knowledge and practical cases daily.

  • β€’ Please like and follow πŸ‘ for continuous learning and consistent valuable output.

  • β€’ +v: jasper_8017 let’s communicate πŸ’¬ and improve together πŸ’ͺ.

Overview of Articles on Official Account

Visualizing LangGraph Structure With One Line of Code

Leave a Comment