LangGraph 1 cheatsheet
LangGraph 1: Building graphs
9 common LangGraph 1 tasks.
Define the state
Describe the data that flows through the graph. add_messages appends new messages instead of replacing the list.
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list, add_messages]
Use the built-in messages state
Use MessagesState when you only need a list of messages.
from langgraph.graph import MessagesState, StateGraph
builder = StateGraph(MessagesState)
Add a node
A node is a function that takes the state and returns the parts of it to update.
def chatbot(state: State):
return {"messages": [model.invoke(state["messages"])]}
builder.add_node("chatbot", chatbot)
Connect nodes
Edges decide which node runs next. START and END mark the entry and exit.
from langgraph.graph import START, END
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
Branch with a conditional edge
Pick the next node with a function that returns the name of a node or END.
def route(state: State):
return "tools" if state["messages"][-1].tool_calls else END
builder.add_conditional_edges("chatbot", route)
Run tools with the prebuilt node
ToolNode runs the tool calls in the last message, and tools_condition routes to it or to the end.
from langgraph.prebuilt import ToolNode, tools_condition
builder.add_node("tools", ToolNode(tools))
builder.add_conditional_edges("chatbot", tools_condition)
builder.add_edge("tools", "chatbot")
Update state and route in one step
Return a Command from a node to change the state and choose the next node together.
from langgraph.types import Command
def review(state: State) -> Command:
return Command(update={"approved": True}, goto="publish")
Fan out to parallel workers
Return Send objects from a conditional edge to run one node per item, for example map-reduce.
from langgraph.types import Send
def fan_out(state):
return [Send("worker", {"item": item}) for item in state["items"]]
builder.add_conditional_edges(START, fan_out, ["worker"])