Compiling and running a graph

LangGraph · Essentials · 9 min

Every graph must be compiled before it runs, and invoke is the simplest way to run it.

A builder is only a description. Call graph = builder.compile() to turn it into a compiled graph you can run. Compiling checks the structure (for example, that edges point to nodes that exist) and is where you later attach extras such as a checkpointer for saving state.

Run it with invoke, passing the starting state:

result = graph.invoke({"text": "hello graph world"})

invoke runs node after node until it reaches END, then returns the final state as a dict. You only need to provide the keys your first nodes read; the rest are filled as nodes run.

Other ways to run the same graph:

  • graph.stream(...) yields results step by step (covered later),
  • await graph.ainvoke(...) and graph.astream(...) are the async versions, for programs written with Python's async/await style, such as most modern web servers,
  • invoke(..., version="v2") (LangGraph 1.1+) returns a GraphOutput object with .value and .interrupts, which is easier to type-check.

See what you built: graph.get_graph().draw_mermaid() returns a diagram description you can paste into any Mermaid viewer (Mermaid is a text format for drawing diagrams), and in a notebook draw_mermaid_png() renders an image.

A compiled graph is reusable and safe to call many times; build it once at startup, not per request.

Example

# continues the previous lesson's builder
graph = builder.compile()

result = graph.invoke({"text": "hello graph world"})
print(result)
# {'text': 'hello graph world', 'words': 3, 'shout': 'HELLO GRAPH WORLD'}

out = graph.invoke({"text": "hi"}, version="v2")
print(out.value["words"], out.interrupts)   # 1 ()

print(graph.get_graph().draw_mermaid())      # diagram source

Remember

  • builder.compile() validates and returns a runnable graph
  • invoke(input) runs to END and returns the final state
  • ainvoke/astream are the async versions
  • get_graph().draw_mermaid() visualizes the graph

Watch out for

  • Rebuilding and compiling the graph on every request instead of once at startup.

Check yourself

  1. What does graph.invoke(...) return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.langchain.com/oss/python/langgraph/use-graph-api