Visualizing graphs with Mermaid

Topic 4 of 4 in Introduction to LangGraph26 min readBeginnerFree course

Overview

In the previous lesson, Your first graph, you built a working LangGraph application by defining state, registering nodes, connecting edges, compiling the graph, and invoking it with an input.

Although reading the Python implementation is manageable for a small sequential workflow, real agentic applications can contain dozens of nodes, conditional decisions, repeated processing steps, tool calls, and nested workflows.

Understanding these relationships from source code alone becomes increasingly difficult.

Graph visualization solves this problem by converting your workflow’s structure into a visual representation. Instead of mentally following every add_edge() statement, you can inspect a diagram showing how execution may move through the application.

LangGraph provides built-in visualization capabilities through Mermaid, a text-based diagramming language that converts textual definitions into graphical diagrams.

Visualization helps engineers answer questions such as:

  • Where does execution begin?
  • Which node executes next?
  • Are processing steps connected in the intended order?
  • Which alternative execution paths exist?
  • Does the graph contain a cycle?
  • Can the workflow reach its intended termination point?
  • Are there unexpected connections between nodes?

These questions become particularly important when developing AI agents, where execution paths may depend on model responses, tool results, or changing state.

Three levels of visualization

LangGraph supports different ways of inspecting a workflow.

Visualization method What it provides Best use case
Mermaid source Textual graph definition Documentation and version control
PNG image Rendered static diagram Visual inspection and presentations
LangSmith Studio Interactive graph and execution inspection Development and debugging
Programmatic inspection Structured node and edge information Automated architecture tests

Mermaid text and PNG images describe the graph’s structure. Studio additionally helps you investigate what happens when the graph actually executes.

Throughout this lesson, we will use deterministic Python functions instead of language models. This keeps the examples focused on graph visualization without introducing API costs, credentials, or unpredictable model responses.

Use Python 3.11 or newer and install the required packages in your course environment.

Terminal
python -m pip install "langgraph>=1,<2" "langchain-core>=1,<2" typing-extensions

Note: The APIs in this lesson follow the current LangGraph 1.x and LangChain Core 1.x references. The examples have been checked against the official API documentation but have not been executed in the author’s environment.

Mermaid text

What is Mermaid?

Mermaid is a declarative diagramming language. You describe the elements of a diagram and their relationships using text, and a compatible renderer determines how to display them.

This approach is similar to writing HTML instead of manually drawing a web page.

A Mermaid flowchart generally contains:

  • A diagram direction, such as top-to-bottom or left-to-right.
  • Node identifiers representing individual steps.
  • Labels describing those steps.
  • Directed edges connecting nodes.
  • Optional labels explaining conditional transitions.

The following diagram represents a simple order-processing workflow.

Mermaid text diagram: START to Validate Order; Validate Order to Calculate Total; Calculate Total to Prepare Confirmation; Prepare Confirmation to END.

Here, execution begins at START, moves through three processing nodes, and terminates at END.

Mermaid automatically calculates the positions of nodes and arrows. You do not need to specify coordinates or manually arrange graphical elements.

More importantly, LangGraph can generate Mermaid definitions directly from your compiled workflow. This avoids maintaining a separate diagram by hand whenever the application changes.

Understanding the visualization pipeline

The visualization process involves three distinct objects or representations:

  1. A StateGraph builder containing your workflow definition.
  2. A compiled graph containing the executable workflow.
  3. A drawable graph containing a representation of nodes and edges.

Calling compile() produces the executable graph.

Calling get_graph() on that compiled graph produces a drawable representation using LangChain Core’s graph utilities.

Calling draw_mermaid() on the drawable representation generates Mermaid source as a Python string.

These operations are separate from execution. Generating a diagram does not call your processing nodes, make model requests, or perform the business operations implemented inside those nodes.

Example 1: Visualizing a sequential graph

Create a file named order_graph.py. This example builds an order-processing workflow and exports its architecture as Mermaid text.

Python
from pathlib import Path
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class OrderState(TypedDict):
    quantity: int
    unit_price: int
    total: int
    confirmation: str

def validate_order(state: OrderState):
    if state["quantity"] <= 0:
        raise ValueError("Quantity must be positive")

    if state["unit_price"] < 0:
        raise ValueError("Price cannot be negative")

    return {}

def calculate_total(state: OrderState):
    return {
        "total": state["quantity"] * state["unit_price"]
    }

def prepare_confirmation(state: OrderState):
    return {
        "confirmation": f"Order total: ${state['total']}"
    }

builder = StateGraph(OrderState)

builder.add_node("validate_order", validate_order)
builder.add_node("calculate_total", calculate_total)
builder.add_node("prepare_confirmation", prepare_confirmation)

builder.add_edge(START, "validate_order")
builder.add_edge("validate_order", "calculate_total")
builder.add_edge("calculate_total", "prepare_confirmation")
builder.add_edge("prepare_confirmation", END)

graph = builder.compile()

if __name__ == "__main__":
    drawable = graph.get_graph()
    mermaid_source = drawable.draw_mermaid()

    print(mermaid_source)

    Path("order_graph.mmd").write_text(
        mermaid_source,
        encoding="utf-8",
    )

    result = graph.invoke({
        "quantity": 3,
        "unit_price": 250,
        "total": 0,
        "confirmation": "",
    })

    print(result)

Run the program:

Terminal
python order_graph.py

The terminal displays generated Mermaid source followed by the final state.

The Mermaid source may contain configuration information, node declarations, edge definitions, and automatically generated styling.

The final state should be:

Text
{
    'quantity': 3,
    'unit_price': 250,
    'total': 750,
    'confirmation': 'Order total: $750'
}

The program also creates an order_graph.mmd file in the current working directory.

Rendering the generated Mermaid source

You can render this file using several Mermaid-compatible environments:

  • The Mermaid Live Editor.
  • GitHub Markdown documentation.
  • Visual Studio Code with a Mermaid-compatible extension.
  • Documentation platforms that support Mermaid.

For example, open the generated .mmd file, copy its contents, and paste them into the Mermaid Live Editor. The corresponding diagram will appear automatically.

To embed the source in supported Markdown documentation, place it inside a fenced code block identified as mermaid.

The exact generated syntax can change between LangChain Core releases. It may use different node shapes, styling declarations, or formatting while preserving the same underlying topology.

For source with less generated styling, use:

Python
from order_graph import graph

print(
    graph.get_graph().draw_mermaid(with_styles=False)
)

This produces Mermaid text with generated styling disabled, making it easier to focus on the workflow structure.

The available rendering options are documented in the official draw_mermaid API reference.

Why store Mermaid source in version control?

Mermaid files are ordinary text files. Git can compare their contents and show how a workflow’s architecture changes between commits.

Suppose a developer introduces a new fraud-detection node between validation and order confirmation. Reviewing the regenerated Mermaid file can reveal whether the new node was connected correctly.

This makes graph visualization useful not only for learning but also for architectural reviews, pull requests, technical documentation, and team collaboration.

As an image

Mermaid source is useful for documentation, but sometimes you need a ready-to-view image.

LangGraph’s drawable graph provides the draw_mermaid_png() method, which renders the graph into PNG format.

Unlike draw_mermaid(), which returns a string, draw_mermaid_png() returns binary image data as Python bytes.

Example 2: Exporting the graph as a PNG

Save the following program as render_order.py in the same directory as order_graph.py.

It imports the compiled workflow and generates a PNG image.

Python
from pathlib import Path
from order_graph import graph

drawable = graph.get_graph()

png_data = drawable.draw_mermaid_png()

output_path = Path("order_graph.png")
output_path.write_bytes(png_data)

print(f"Diagram saved to: {output_path.resolve()}")
print(f"Image size: {len(png_data)} bytes")

Run:

Terminal
python render_order.py

When rendering succeeds, the program creates order_graph.png.

Open this file using your operating system’s image viewer. You should see the same workflow structure represented by the Mermaid source.

The method also supports saving directly to a file, eliminating the need to call Path.write_bytes() yourself.

Python
from order_graph import graph

graph.get_graph().draw_mermaid_png(
    output_file_path="order_graph.png"
)

Both approaches produce a PNG file. Use the bytes-based approach when the image must be uploaded to object storage, returned through an API, or processed by another application.

Displaying a graph in Jupyter Notebook

When developing LangGraph applications in Jupyter Notebook, displaying diagrams directly inside the notebook is especially convenient.

Install IPython if it is not already available:

Terminal
python -m pip install ipython

Run the following code in a notebook cell:

Python
from IPython.display import Image, display
from order_graph import graph

display(
    Image(graph.get_graph().draw_mermaid_png())
)

The rendered graph appears beneath the cell.

This allows you to inspect the graph immediately after compiling it, without switching to a separate application.

A notebook is particularly useful when experimenting with different architectures. You can modify connections, recompile the workflow, and regenerate the visualization.

Understanding rendering methods

By default, draw_mermaid_png() uses an external Mermaid rendering API, normally Mermaid.ink.

The graph definition is sent to the rendering service, which produces the PNG image and returns it to your Python application.

This introduces a network dependency that does not exist when generating Mermaid text.

Rendering method Network requirements Additional setup
draw_mermaid() None No additional renderer
Mermaid API Access to rendering server None by default
Pyppeteer Initial setup and potentially external assets Chromium and Pyppeteer
Graphviz Can render entirely locally after installation Graphviz and PyGraphviz

Example 3: Browser-based rendering with Pyppeteer

Pyppeteer controls a Chromium browser that can render Mermaid diagrams.

Install the package:

Terminal
python -m pip install pyppeteer

Save the following program as render_browser.py.

Python
from langchain_core.runnables.graph import MermaidDrawMethod
from order_graph import graph

graph.get_graph().draw_mermaid_png(
    draw_method=MermaidDrawMethod.PYPPETEER,
    output_file_path="order_browser.png",
    background_color="white",
    padding=20,
)

print("Browser-rendered diagram saved.")

Run:

Terminal
python render_browser.py

The first execution may require downloading Chromium. Depending on the environment and renderer implementation, additional browser dependencies or access to Mermaid’s JavaScript assets may be necessary.

In Jupyter environments, an existing asynchronous event loop may also require an event-loop compatibility solution such as nest_asyncio.

Do not assume that browser-based rendering is automatically suitable for a fully disconnected environment.

For strictly local rendering, Graphviz is another option. After installing the system Graphviz software and the pygraphviz Python package, you can call:

Python
from order_graph import graph

graph.get_graph().draw_png(
    output_file_path="order_graphviz.png"
)

This renders the graph through Graphviz rather than Mermaid.

Tip: Avoid sending confidential workflow definitions to public rendering services. Even without state values or prompts, node names and graph relationships can reveal internal business processes. Use an approved renderer or local rendering environment for sensitive applications.

Handling rendering failures

PNG generation can fail because of restricted internet access, DNS errors, rendering-service outages, missing browser dependencies, or unsupported operating-system configurations.

A rendering failure does not necessarily indicate a problem with your LangGraph application.

Generate and save Mermaid source first. Treat PNG rendering as an optional second operation.

The draw_mermaid_png API reference documents additional options, including rendering configuration, output paths, and network retry settings.

Reading the diagram

Generating a diagram is only the first step. An engineer must also understand what the diagram represents and identify potential architecture problems.

Understanding nodes and edges

In a generated LangGraph diagram, the following elements have specific meanings.

Diagram element Meaning
__start__ Virtual workflow entry point
__end__ Virtual workflow termination point
Processing node Registered function or runnable
Solid arrow Typically a normal directed edge
Dashed arrow Typically a conditional or dynamically declared transition
Edge label Name of a routing outcome
Backward connection A possible repeated execution path
Multiple outgoing edges Alternative routes or parallel scheduling, depending on the edge configuration

START and END are special graph markers rather than ordinary business-processing functions.

An arrow describes a control-flow relationship. It does not necessarily mean that the complete return value of one function is passed directly as the next function’s argument.

LangGraph nodes communicate through shared state. A node returns state updates, which the runtime applies before subsequent execution steps.

This distinction becomes increasingly important when workflows contain multiple state fields and concurrent branches.

Example 4: Visualizing conditional routing and cycles

Consider an automated document-review system.

The system checks whether a document is approved. If approval has not been achieved, it performs another revision and checks the document again.

The following conceptual diagram illustrates the possible execution paths.

Reading the diagram diagram: START to Review Document; Review Document to Revise Document (revise); Revise Document to Review Document; Review Document to END (finish).

Unlike the sequential order-processing workflow, this graph contains a cycle.

The review node can conditionally schedule the revision node or terminate the workflow. The revision node always returns execution to the review node.

Create review_graph.py to implement this behavior.

Python
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class ReviewState(TypedDict):
    revision_count: int
    approved: bool

def review_document(state: ReviewState):
    return {
        "approved": state["revision_count"] >= 2
    }

def revise_document(state: ReviewState):
    return {
        "revision_count": state["revision_count"] + 1
    }

def choose_next_step(
    state: ReviewState,
) -> Literal["revise", "finish"]:
    if state["approved"]:
        return "finish"

    return "revise"

builder = StateGraph(ReviewState)

builder.add_node("review_document", review_document)
builder.add_node("revise_document", revise_document)

builder.add_edge(START, "review_document")

builder.add_conditional_edges(
    "review_document",
    choose_next_step,
    {
        "revise": "revise_document",
        "finish": END,
    },
)

builder.add_edge("revise_document", "review_document")

graph = builder.compile()

if __name__ == "__main__":
    print(graph.get_graph().draw_mermaid())

    initial_state = {
        "revision_count": 0,
        "approved": False,
    }

    for chunk in graph.stream(
        initial_state,
        config={"recursion_limit": 20},
        stream_mode="updates",
        version="v2",
    ):
        print(chunk["data"])

    print(
        graph.invoke(
            initial_state,
            config={"recursion_limit": 20},
        )
    )

Expected state updates:

Text
{'review_document': {'approved': False}}
{'revise_document': {'revision_count': 1}}
{'review_document': {'approved': False}}
{'revise_document': {'revision_count': 2}}
{'review_document': {'approved': True}}
{'revision_count': 2, 'approved': True}

The stream reveals that the same node can execute multiple times during one invocation.

The generated Mermaid diagram shows the cycle only once because it represents the possible structural connections, not an expanded timeline of every execution.

This is a fundamental characteristic of agentic workflows. An AI agent may repeatedly evaluate progress, call tools, and reconsider its next action before reaching a termination condition.

The explicit recursion limit provides a safety boundary. It limits graph execution steps rather than directly counting document revisions. A well-designed stopping condition remains necessary.

Why explicit routing destinations matter

Python routing functions can contain arbitrary logic. LangGraph cannot reliably determine every possible destination by inspecting unrestricted Python code.

When defining conditional edges, provide an explicit path mapping or a suitable Literal return annotation identifying destination node names.

Without this information, visualization may conservatively display connections to nodes that the routing function would never select.

Our review example uses an explicit mapping between routing outcomes and destination nodes.

For workflows that later use Command for dynamic routing, destination type annotations or the destinations argument of add_node() can improve visualization.

The destinations argument is descriptive metadata for rendering; it does not create executable routing behavior.

See the conditional edge reference for details.

Inspecting the graph programmatically

You do not always need to render an image to verify graph structure.

The drawable graph exposes its nodes and edges as Python objects.

The following example checks whether the order-processing workflow has the expected topology.

Python
from langgraph.graph import START, END
from order_graph import graph

drawable = graph.get_graph()

print("Nodes:")

for node_id in drawable.nodes:
    print(node_id)

print("\nEdges:")

actual_edges = set()

for edge in drawable.edges:
    print(f"{edge.source} -> {edge.target}")
    actual_edges.add((edge.source, edge.target))

expected_edges = {
    (START, "validate_order"),
    ("validate_order", "calculate_total"),
    ("calculate_total", "prepare_confirmation"),
    ("prepare_confirmation", END),
}

assert actual_edges == expected_edges

print("Graph structure is correct.")

The assertion passes when all expected connections exist and no unexpected connections are present.

This technique can be incorporated into automated tests and continuous integration pipelines.

For nested workflows, LangGraph also supports expanded structural inspection through get_graph(xray=True), which exposes discoverable subgraphs rather than displaying only their outer representation.

Common mistakes when interpreting diagrams

Mistake Correct interpretation
Assuming every displayed node executes Conditional routes may skip nodes
Assuming all outgoing arrows are alternatives Normal outgoing edges may schedule multiple nodes
Assuming a cycle is automatically invalid Cycles are supported but require safe termination
Assuming a diagram proves correctness Node logic and state transitions still require testing
Editing Mermaid to change execution Change the Python graph and regenerate the diagram
Assuming diagram position determines order Directed edges and runtime scheduling determine execution

A static diagram cannot reveal whether a database request failed, a model returned an incorrect response, or a state update contained unexpected data.

For these investigations, you need execution-level observability.

Studio: the interactive view

What is LangSmith Studio?

LangSmith Studio is an interactive development interface for inspecting, executing, and debugging LangGraph applications.

Unlike Mermaid, which produces a static representation, Studio connects to a running Agent Server and lets you interact with the workflow.

You can submit inputs, observe executed nodes, inspect state changes, investigate errors, and experiment with different execution paths.

Studio is particularly valuable when developing workflows whose behavior depends on runtime decisions.

Setting up Studio locally

Reuse the sequential order_graph.py application created earlier.

Install the LangGraph CLI with its local development-server dependencies.

Terminal
python -m pip install -U "langgraph-cli[inmem]"

Your project directory should contain the following files:

Text
order_project/
    order_graph.py
    langgraph.json
    requirements.txt
    .env

Create requirements.txt:

Text
langgraph>=1,<2
langchain-core>=1,<2
typing-extensions

Create langgraph.json:

JSON
{
  "dependencies": ["."],
  "graphs": {
    "order_processing": "./order_graph.py:graph"
  },
  "env": ".env"
}

The graphs configuration associates the public graph identifier order_processing with the compiled Python object named graph inside order_graph.py.

The dependency entry points to the current project directory, where the requirements file is located.

Create a LangSmith account and API key through LangSmith.

Create the .env file:

DOTENV
LANGSMITH_API_KEY=your_langsmith_api_key
LANGSMITH_TRACING=false

Replace the placeholder with your actual key. Keep .env outside version control.

Tracing is disabled here because this example focuses on local workflow inspection. Remote tracing configuration will be covered later in the course.

From your project directory, start the local development server.

Terminal
langgraph dev

This launches an in-memory Agent Server suitable for development and testing without requiring Docker.

The terminal normally provides addresses for:

  • The local API server at http://127.0.0.1:2024.
  • Interactive API documentation at http://127.0.0.1:2024/docs.
  • The LangSmith Studio web interface.

Open the Studio URL printed by the CLI. The usual address is:

Text
https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024

If browser restrictions prevent a connection to the local server, consult the Studio setup guide for supported connection options, including secure tunneling.

Executing the graph in Studio

Select the order_processing graph and use Graph mode to inspect its structure.

Provide the following input:

JSON
{
  "quantity": 4,
  "unit_price": 150,
  "total": 0,
  "confirmation": ""
}

Submit the input and inspect the run.

You should observe the validation node, total-calculation node, and confirmation node executing sequentially.

The expected final state is:

JSON
{
  "quantity": 4,
  "unit_price": 150,
  "total": 600,
  "confirmation": "Order total: $600"
}

Inspect the intermediate state after the total-calculation node. The total should already be 600, while the confirmation should not yet contain its final value.

Next, test an invalid input by setting quantity to 0.

The validation node should raise an exception, and the normal downstream processing should not complete. Studio allows you to investigate the failure in its execution context.

Studio’s development server also supports code reloading, allowing you to change your Python implementation and test the updated application.

Graph mode versus Chat mode

Studio provides interfaces for different application types.

Graph mode is appropriate for general state-based workflows because it exposes execution structure and intermediate data.

Chat mode is designed for conversational applications whose state contains or extends MessagesState. It becomes more useful when developing tool-calling assistants and conversational agents.

Our order-processing application uses ordinary structured state rather than conversation messages, so Graph mode is the appropriate choice.

Engineering practices for graph visualization

Generate a fresh diagram whenever you introduce a new node, conditional branch, or cycle. Use descriptive node names that communicate responsibilities rather than generic identifiers such as step1 and step2.

Keep graph construction separate from invocation so that visualization and Studio can import your compiled workflow without accidentally executing business operations.

For larger systems, combine static diagrams with structural assertions and representative runtime tests. During code review, inspect both the intended topology and the behavior observed during execution.

Treat Mermaid files as generated architectural artifacts rather than the source of truth. Your Python graph definition remains responsible for executable control flow.

The chapter’s hands-on project, building a basic sequential graph, is now easier to validate because you can inspect its architecture independently of its final output.

In the next lesson, Understanding graph state, we will investigate the data that moves through these visualized workflows. You will learn how nodes read shared state, return partial updates, and communicate through state fields rather than directly calling one another. This knowledge will explain not only where execution travels, but also how information evolves along each execution path.

Exercise

Visualize a Sequential Text Processing Graph

Build a sequential LangGraph workflow that cleans input text, converts it to uppercase, and counts its words. Generate and save the graph as Mermaid source and, when rendering is available, as a PNG image. Verify that the diagram contains the expected three processing nodes in the correct order, and execute the graph to confirm its behavior.

Python
from pathlib import Path
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class TextState(TypedDict):
    text: str
    word_count: int

def clean_text(state: TextState):
    return {"text": " ".join(state["text"].split())}

def uppercase_text(state: TextState):
    return {"text": state["text"].upper()}

def count_words(state: TextState):
    return {"word_count": len(state["text"].split())}

builder = StateGraph(TextState)

# TODO: Register all three nodes.

# TODO: Connect START, the three nodes, and END.

# TODO: Compile the graph.

# TODO: Generate and print the Mermaid source.

# TODO: Save the Mermaid source to text_workflow.mmd.

# TODO: Save a PNG image to text_workflow.png.

# TODO: Invoke the graph and verify the final state.

Summary

  • A compiled LangGraph workflow exposes its drawable structure through the get_graph() method.
  • Mermaid represents nodes and directed edges using a readable text-based diagram language.
  • The draw_mermaid() method generates Mermaid source without executing the workflow or requiring a rendering service.
  • The draw_mermaid_png() method produces PNG image bytes and supports saving diagrams directly to files.
  • Explicit conditional routing destinations improve the accuracy and readability of generated diagrams.
  • Static graph diagrams describe possible execution paths rather than the actual history of a particular run.
  • LangSmith Studio provides interactive graph visualization, execution testing, and intermediate state inspection.