LangGraph Tutorial (Python): persisting agent state for beginners

By Cyprian AaronsUpdated 2026-04-22
langgraphpersisting-agent-state-for-beginnerspython

This tutorial shows you how to persist LangGraph agent state in Python using a real checkpointer, so your agent can resume conversations after each run. You need this when you want memory across requests, support multi-turn workflows, or recover state after a process restart.

What You'll Need

  • Python 3.10+
  • langgraph
  • langchain-openai
  • An OpenAI API key set as OPENAI_API_KEY
  • A terminal and a virtual environment
  • Basic familiarity with LangGraph nodes, edges, and StateGraph

Step-by-Step

  1. Install the packages and set your API key.
    We’ll use a simple chat agent backed by OpenAI and persist its state with SQLite, which is enough for local development and beginner-friendly testing.
pip install langgraph langchain-openai
export OPENAI_API_KEY="your-api-key-here"
  1. Define the graph state and the model node.
    The key idea is that the graph state includes the conversation messages, and the node appends a new assistant response on each turn.
from typing import Annotated
from typing_extensions import TypedDict

from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages

llm = ChatOpenAI(model="gpt-4o-mini")

class State(TypedDict):
    messages: Annotated[list, add_messages]

def chatbot(state: State):
    response = llm.invoke(state["messages"])
    return {"messages": [response]}
  1. Add a persistent checkpointer.
    This is what stores state between runs. We’ll use SQLite so the same thread can be resumed later by passing the same thread_id.
from langgraph.checkpoint.sqlite import SqliteSaver

builder = StateGraph(State)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)

checkpointer = SqliteSaver.from_conn_string("checkpoints.sqlite")
graph = builder.compile(checkpointer=checkpointer)
  1. Run the graph with a thread ID.
    The thread_id is the handle LangGraph uses to load and save state for one conversation. If you reuse it, the graph continues from where it left off.
config = {"configurable": {"thread_id": "user-123"}}

result1 = graph.invoke(
    {"messages": [("user", "My name is Amina")]},
    config=config,
)

print(result1["messages"][-1].content)
  1. Invoke it again with the same thread ID to prove persistence.
    On the second call, LangGraph restores prior state from SQLite before running the next step, so the model can see earlier messages without you manually passing them in.
result2 = graph.invoke(
    {"messages": [("user", "What is my name?")]},
    config=config,
)

for msg in result2["messages"]:
    print(f"{msg.type}: {msg.content}")
  1. Inspect saved state directly when debugging.
    This is useful when you need to confirm what LangGraph stored after each turn or troubleshoot why an agent resumed with unexpected context.
snapshot = graph.get_state(config)
print(snapshot.values["messages"][-2].content)
print(snapshot.values["messages"][-1].content)

Testing It

Run the script once and send a first message like “My name is Amina.” Then run it again with the same thread_id and ask “What is my name?” If persistence is working, the assistant should answer correctly using the stored conversation history.

You should also see a checkpoints.sqlite file appear in your project directory. That file contains the saved graph state for your thread, so deleting it resets memory.

If you want to verify multiple conversations, change thread_id to something else like "user-456". Each thread will keep its own independent history.

Next Steps

  • Add structured state fields beyond messages, such as user profile data or tool results.
  • Swap SQLite for Postgres when you need shared persistence across multiple app instances.
  • Learn how to use LangGraph interrupts and human-in-the-loop flows on top of persisted state.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides