Skip to main content
This guide demonstrates the basics of LangGraph’s Graph API. It walks through state, as well as composing common graph structures such as sequences, branches, and loops. It also covers LangGraph’s control features, including the Send API for map-reduce workflows and the Command API for combining state updates with “hops” across nodes.

Setup

Install langgraph:
pip install -U langgraph
Set up LangSmith for better debuggingSign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started in the docs.

Define and update state

Here we show how to define and update state in LangGraph. We will demonstrate:
  1. How to use state to define a graph’s schema
  2. How to use reducers to control how state updates are processed.

Define state

State in LangGraph can be a TypedDict, Pydantic model, or dataclass. Below we will use TypedDict. See this section for detail on using Pydantic. By default, graphs will have the same input and output schema, and the state determines that schema. See this section for how to define distinct input and output schemas. Let’s consider a simple example using messages. This represents a versatile formulation of state for many LLM applications. See our concepts page for more detail.
from langchain.messages import AnyMessage
from typing_extensions import TypedDict

class State(TypedDict):
    messages: list[AnyMessage]
    extra_field: int
This state tracks a list of message objects, as well as an extra integer field.

Update state

Let’s build an example graph with a single node. Our node is just a Python function that reads our graph’s state and makes updates to it. The first argument to this function will always be the state:
from langchain.messages import AIMessage

def node(state: State):
    messages = state["messages"]
    new_message = AIMessage("Hello!")
    return {"messages": messages + [new_message], "extra_field": 10}
This node simply appends a message to our message list, and populates an extra field.
Nodes should return updates to the state directly, instead of mutating the state.
Let’s next define a simple graph containing this node. We use StateGraph to define a graph that operates on this state. We then use add_node populate our graph.
from langgraph.graph import StateGraph

builder = StateGraph(State)
builder.add_node(node)
builder.set_entry_point("node")
graph = builder.compile()
LangGraph provides built-in utilities for visualizing your graph. Let’s inspect our graph. See this section for detail on visualization.
from IPython.display import Image, display

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