Generative AIby Dhruv Narang

1. Architectural Purpose & Mental Model

In standard LLM chains, state is transient: as soon as the script finishes running, the conversation history vanishes from RAM. For real-world chatbots, customer service copilots, and multi-turn assistants, systems require State Persistence:

  1. The conversation history must automatically accumulate without manual array appending in application code.
  2. The graph state must be saved to a persistent store (RAM, SQLite, PostgreSQL) after every execution turn.
  3. Multi-user conversations must be isolated cleanly using session identifiers (thread_id).

2. Architecture Diagram

flowchart LR
  START(["START"]) --> C["Chatbot node"] --> END(["END"])
  C -.-> M[("MemorySaver checkpointer<br/><small>saves state after every turn<br/>indexed by thread_id</small>")]
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef gate fill:#fdf1ec,stroke:#c9583a,color:#7a2e1a
classDef store fill:#f5f5f4,stroke:#57534e,color:#292524
classDef c0 fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef c1 fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef c2 fill:#e3f5ee,stroke:#4aa58a,color:#14463a
classDef c3 fill:#f6f4f0,stroke:#a7a29a,color:#3f3b35
classDef c4 fill:#eef7f7,stroke:#1a5c5b,color:#0e3b3a
class START term
class C c0
class END term
class M store

3. The Two Core Mechanics

A. The add_messages Reducer

Instead of overwriting the messages key, the add_messages reducer automatically:

  • Appends new incoming HumanMessage and AIMessage objects to the list.
  • Replaces messages if an update contains an identical message id (enabling message editing).

B. The Checkpointer & thread_id

When compiling a graph with compile(checkpointer=MemorySaver()), every invocation requires a configuration dictionary:

config = {"configurable": {"thread_id": "user_dhruv_session"}}
  • Invocations sharing the same thread_id automatically retrieve the latest state snapshot from that thread.
  • Different thread_id values run in 100% complete isolation, preventing cross-user data leakage.

4. Production Python Implementation (Chatbot_history.py)

Code · 50 lines01_chatbot_memory.pyShow here
import os
from dotenv import load_dotenv
load_dotenv()

from typing import TypedDict, Annotated
from langchain.chat_models import init_chat_model
from langgraph.graph import START, END, StateGraph
from langgraph.graph.message import add_messages
from langgraph.checkpoint.memory import MemorySaver

# 1. Initialize Model
model = init_chat_model("mistralai:mistral-small-2603")

# 2. State with add_messages Reducer
class ChatState(TypedDict):
    messages: Annotated[list, add_messages]

# 3. Worker Node
def chatbot_node(state: ChatState) -> dict:
    """Invokes LLM with current historical messages and returns new AI reply."""
    response = model.invoke(state["messages"])
    # Returning a list of messages triggers the add_messages reducer
    return {"messages": [response]}

# 4. Construct Graph
builder = StateGraph(ChatState)
builder.add_node("bot", chatbot_node)
builder.add_edge(START, "bot")
builder.add_edge("bot", END)

# 5. Compile with In-Memory Checkpointer
memory = MemorySaver()
app = builder.compile(checkpointer=memory)

# 6. Multi-Turn Session Simulation (Thread Isolation)
config_user_a = {"configurable": {"thread_id": "user_dhruv_01"}}
config_user_b = {"configurable": {"thread_id": "user_sarah_02"}}

print("=== USER A (DHRUV) TURN 1 ===")
res1 = app.invoke({"messages": [("human", "My name is Dhruv and I am building an AI agent.")]}, config=config_user_a)
print("AI:", res1["messages"][-1].content)

print("\n=== USER B (SARAH) TURN 1 ===")
res_b = app.invoke({"messages": [("human", "My name is Sarah and I love robotics.")]}, config=config_user_b)
print("AI:", res_b["messages"][-1].content)

print("\n=== USER A (DHRUV) TURN 2 (Memory Recall) ===")
# Note: We do NOT pass the name again. The model recalls it from thread state!
res2 = app.invoke({"messages": [("human", "What is my name and what am I building?")]}, config=config_user_a)
print("AI:", res2["messages"][-1].content)

5. Inspecting State & Time Travel

LangGraph allows programmatic inspection of any thread's historical snapshots:

# Get current snapshot of thread
current_state = app.get_state(config_user_a)
print("Current Message Count:", len(current_state.values["messages"]))

# Inspect full historical timeline
for snapshot in app.get_state_history(config_user_a):
    print(f"Checkpoint ID: {snapshot.config['configurable']['checkpoint_id']} | Next Node: {snapshot.next}")

6. Key Takeaways

  • No Manual History Lists: Application code no longer needs to manually maintain chat_history = []; the checkpointer and reducer manage it automatically.
  • Multi-Tenancy: A single compiled graph instance safely serves thousands of concurrent users simply by switching thread_id.
  • Production Storage: For server restarts, swap MemorySaver() with SqliteSaver.from_conn_string("state.db") or PostgresSaver.
Code
01_chatbot_memory.py01_chatbot_memory.py · 48 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import os 
from dotenv import load_dotenv

load_dotenv()


from langchain.chat_models import init_chat_model
from typing import TypedDict , Annotated
from langgraph.graph import START , END , StateGraph
from langgraph.graph.message import add_messages

from langgraph.checkpoint.memory import MemorySaver

model = init_chat_model("mistralai:open-mistral-nemo")


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


def chatbot_node(state:ChatState):
    response = model.invoke(state["messages"])
    return {"messages":[response]}

builder = StateGraph(ChatState)

builder.add_node("bot",chatbot_node)
builder.add_edge(START ,"bot")
builder.add_edge("bot",END)

"""Checkpointer: saves the state after every run, so the next run continues from it"""
memory = MemorySaver()

app = builder.compile(checkpointer=memory)

"""thread_id = one conversation. A new thread_id = a fresh chat with no memory"""
config = {"configurable": {"thread_id": "dhruv_chat_1"}}


res1 = app.invoke({"messages": [("human", "My name is Dhruv")]}, config=config)
print("AI:", res1["messages"][-1].content)

res2 = app.invoke({"messages": [("human", "What is my name?")]}, config=config)
print("AI:", res2["messages"][-1].content)