How to Intermediate · 4 min read

How to use state in LangGraph

Quick answer
In LangGraph, use the State object to store and manage persistent data across nodes, enabling context-aware workflows. You create a State instance and pass it to nodes or chains to read and update state during execution.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install langchain>=0.2.0

Setup

Install langchain and set your OpenAI API key in the environment variables.

  • Run pip install langchain openai
  • Set environment variable OPENAI_API_KEY with your API key
bash
pip install langchain openai

Step by step

This example demonstrates creating a State object in LangGraph, updating it in a node, and accessing it later to maintain context across calls.

python
from langchain.graphs import LangGraph, State
from langchain.schema import BaseNode
from langchain_openai import ChatOpenAI
import os

# Initialize the OpenAI client
llm = ChatOpenAI(model_name="gpt-4o", temperature=0, openai_api_key=os.environ["OPENAI_API_KEY"])

# Define a simple node that updates state
class UpdateStateNode(BaseNode):
    def __init__(self, key: str, value: str):
        super().__init__()
        self.key = key
        self.value = value

    def invoke(self, state: State):
        # Update the state with a key-value pair
        state[self.key] = self.value
        return f"State updated: {self.key} = {self.value}"

# Define a node that reads from state
class ReadStateNode(BaseNode):
    def __init__(self, key: str):
        super().__init__()
        self.key = key

    def invoke(self, state: State):
        # Read the value from state
        return f"Value for {self.key}: {state.get(self.key, 'Not found')}"

# Create LangGraph and State
graph = LangGraph()
state = State()

# Add nodes
update_node = UpdateStateNode("user_name", "Alice")
read_node = ReadStateNode("user_name")

# Add nodes to graph
graph.add_node(update_node)
graph.add_node(read_node)

# Run update node
print(update_node.invoke(state))  # Output: State updated: user_name = Alice

# Run read node
print(read_node.invoke(state))    # Output: Value for user_name: Alice
output
State updated: user_name = Alice
Value for user_name: Alice

Common variations

You can use State with asynchronous nodes by making invoke async and passing state. Also, integrate State with LangChain chains or agents to maintain conversation context or intermediate results. Different models like gpt-4o or claude-3-5-sonnet-20241022 can be used interchangeably.

python
import asyncio

class AsyncUpdateStateNode(BaseNode):
    def __init__(self, key: str, value: str):
        super().__init__()
        self.key = key
        self.value = value

    async def invoke(self, state: State):
        # Simulate async update
        await asyncio.sleep(0.1)
        state[self.key] = self.value
        return f"Async state updated: {self.key} = {self.value}"

async def main():
    state = State()
    node = AsyncUpdateStateNode("session_id", "xyz123")
    result = await node.invoke(state)
    print(result)
    print(f"Stored session_id: {state.get('session_id')}")

asyncio.run(main())
output
Async state updated: session_id = xyz123
Stored session_id: xyz123

Troubleshooting

  • If state updates do not persist, ensure you are passing the same State instance across nodes.
  • If you get KeyError when reading state, use state.get(key, default) to avoid exceptions.
  • For async nodes, confirm your environment supports async execution and you await invoke properly.

Key Takeaways

  • Use the State object in LangGraph to persist data across nodes and calls.
  • Pass the same State instance to nodes to maintain context and update values.
  • Async nodes can also read and write state by making invoke async and awaiting it.
  • Always handle missing keys gracefully with state.get(key, default).
  • Integrate State with LangChain chains or agents for complex workflows.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗