Message Persistence
To keep the threads of a self-hosted agent after a server restart, compile the graph with a database checkpointer, such as AsyncPostgresSaver or AsyncSqliteSaver. Set up the checkpointer in a FastAPI lifespan function, as follows. In this sample, workflow is your StateGraph builder.
from fastapi import FastAPI
from contextlib import asynccontextmanager
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
from copilotkit import LangGraphAGUIAgent
from ag_ui_langgraph import add_langgraph_fastapi_endpoint
@asynccontextmanager
async def lifespan(app: FastAPI):
async with AsyncPostgresSaver.from_conn_string(
"postgresql://postgres:postgres@127.0.0.1:5432/postgres"
) as checkpointer:
# NOTE: you need to call .setup() the first time you're using your checkpointer
await checkpointer.setup()
# Create an async graph
graph = workflow.compile(checkpointer=checkpointer)
# Serve the compiled graph, now that it exists
add_langgraph_fastapi_endpoint(
app=app,
agent=LangGraphAGUIAgent(
name="research_agent",
description="Research agent.",
graph=graph,
),
path="/agents/research_agent"
)
yield
app = FastAPI(lifespan=lifespan)
Restart the server and send a message on an existing thread. The agent answers with the earlier messages of that thread in its context.
To load earlier messages and agent state in the frontend, see Thread & History Lifecycle.
To learn more about persistence in LangGraph, check out the LangGraph documentation.
How is this guide?