How to beginner · 3 min read

How to compile a LangGraph graph

Quick answer
To compile a LangGraph graph, define your nodes as Python functions, add them to a StateGraph instance, set the entry point, and then call graph.compile() to create an executable app. The compiled app can be invoked with initial state data to run the graph logic.

PREREQUISITES

  • Python 3.8+
  • pip install langgraph
  • Basic Python knowledge

Setup

Install the langgraph package via pip and import the necessary classes. Ensure you have Python 3.8 or newer.

bash
pip install langgraph
output
Collecting langgraph
  Downloading langgraph-0.1.0-py3-none-any.whl (10 kB)
Installing collected packages: langgraph
Successfully installed langgraph-0.1.0

Step by step

Define a typed state dictionary, create node functions that accept and return state, add nodes to a StateGraph, set the entry point, compile the graph, and invoke it with initial state.

python
from langgraph.graph import StateGraph, END
from typing import TypedDict

class State(TypedDict):
    messages: list[str]

def my_node(state: State) -> State:
    return {"messages": state["messages"] + ["response from my_node"]}

graph = StateGraph(State)
graph.add_node("my_node", my_node)
graph.set_entry_point("my_node")
graph.add_edge("my_node", END)

app = graph.compile()

result = app.invoke({"messages": ["Hello"]})
print(result)
output
{'messages': ['Hello', 'response from my_node']}

Common variations

You can define multiple nodes and edges for complex workflows, use async functions for nodes, or persist state between invocations with a checkpointer. The invoke method runs the compiled graph synchronously.

python
import asyncio

async def async_node(state: State) -> State:
    await asyncio.sleep(0.1)
    return {"messages": state["messages"] + ["async response"]}

# Add async node example

graph.add_node("async_node", async_node)
graph.add_edge("my_node", "async_node")
graph.add_edge("async_node", END)

app = graph.compile()

# To invoke async graph:
async def main():
    result = await app.invoke({"messages": ["Start"]})
    print(result)

asyncio.run(main())
output
{'messages': ['Start', 'response from my_node', 'async response']}

Troubleshooting

  • If you see TypeError, verify your node functions accept and return the correct State type.
  • If invoke hangs, check if you need to use await for async nodes.
  • Ensure you set an entry point with set_entry_point() before compiling.

Key Takeaways

  • Use StateGraph to add nodes and define edges before compiling.
  • Call graph.compile() to get an executable app for invocation.
  • Invoke the compiled app with initial state to run the graph logic.
  • Async nodes require await when invoking the graph.
  • Always set an entry point node before compiling the graph.
Verified 2026-04
Verify ↗