Serving a Graph
FastAPI.
A graph becomes useful when apps can reach it. FastAPI turns it into a web API in a few lines. The client sends a thread ID with each message, so conversations continue.

- Apps need to reach it
- FastAPI
- Thread ID per conversation
A chat endpoint
The endpoint receives a thread ID and a message. It invokes our chat graph, with a checkpointer, on that thread, and returns the reply. The test client calls it twice on the same thread. Run it. The second reply remembers the first message, because the thread carried the conversation.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from chat_memory import graph
app = FastAPI()
class Message(BaseModel):
thread_id: str
text: str
@app.post("/chat")
def chat(m: Message):
out = graph.invoke({"messages": [{"role": "user", "content": m.text}]},
{"configurable": {"thread_id": m.thread_id}})
return {"reply": out["messages"][-1].text.strip()}
client = TestClient(app)
for text in ["Hi, I'm Ana. One sentence please.", "What's my name? One word."]:
print(client.post("/chat", json={"thread_id": "ana-1", "text": text}).json()){'reply': "Hi Ana, it's wonderful to meet you, and I hope you're having a fantastic
day!"}
{'reply': 'Ana.'}Also uses chat_memory.py
from langchain.chat_models import init_chat_model
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import MessagesState, StateGraph, START
model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
def chat(s: MessagesState):
return {"messages": [model.invoke(s["messages"])]}
b = StateGraph(MessagesState); b.add_node(chat); b.add_edge(START, "chat")
graph = b.compile(checkpointer=InMemorySaver())Serving tips
Never let clients choose someone else's thread, so tie thread IDs to the logged in user. Use async endpoints and a invoke for many users. Stream updates or tokens for a better experience. And use a database checkpointer.
| key | value |
|---|---|
| Thread IDs | tied to the user |
| Async | ainvoke |
| Stream | progress, tokens |
| Persist | database saver |
Summary
FastAPI serves a graph as a web API, with a thread ID per conversation. Next, the options for deploying graphs.
Key takeaways- POST /chat
- thread_id from the client
- Checkpointer keeps history