Adding Conversation Memory to AI Assistants with LangGraph and PostgreSQL | AI Engineering Series #2

Welcome back to my AI Engineering Series! 🚀

In Part 1, we built an intelligent AI workflow using FastAPI, LangChain, LangGraph and Google Gemini. Our application could understand user intent and route requests to specialized AI assistants.

However, our assistant had one major limitation — it could not remember previous conversations.

In this article, we will extend the same application by introducing conversation memory, thread management, message trimming and persistent storage using PostgreSQL.

1. Understanding the Problem

Consider the following conversation:

User: My name is Jayakrishna.

AI: Nice to meet you, Jayakrishna!

User: What is my name?

AI: I don't know your name.

This happens because every API request is processed independently. The model receives only the current question without previous conversation history.

This is called a stateless AI application.

With conversation memory, the assistant can remember previous interactions and provide context-aware responses.

User: What is my name?

AI: Your name is Jayakrishna.

The model is not learning new information permanently. Our application stores previous messages and provides relevant conversation history to the model.

2. What Are We Building?

In this hands-on session, we will implement:

  • Conversation memory using LangGraph
  • Context-aware intent classification
  • Thread-based conversations
  • Message trimming
  • Conversation history API
  • Clear memory API
  • PostgreSQL integration
  • Persistent conversation memory
  • Database connection pooling

Our goal is to build an AI assistant that remembers conversations even after restarting the application.

3. Technology Stack

Technology Purpose
Python Backend development
FastAPI REST APIs
LangChain LLM integration
LangGraph Stateful AI workflows
Google Gemini Large language model
PostgreSQL Persistent memory storage
Psycopg Database connectivity
Pydantic API validation

We will continue using the existing project from Part 1.

4. Application Architecture

flowchart TD A[User Request] --> B[FastAPI] B --> C[LangGraph State] C --> D[Intent Classifier] D --> E[Coding Assistant] D --> F[Email Assistant] D --> G[General Assistant] E --> H[Google Gemini] F --> H G --> H H --> I[API Response] C <--> J[PostgreSQL Checkpointer]

How it works

  1. The user sends a question with a thread ID.
  2. FastAPI receives the request.
  3. LangGraph retrieves the previous conversation.
  4. The classifier identifies the user's intent.
  5. The appropriate AI node generates a response.
  6. LangGraph saves the updated conversation state.
  7. FastAPI returns the response.

5. Prepare the Existing Project

Open the project created in Part 1.

cd ai-smart-assistant 

Activate the virtual environment on Windows:

venv\Scripts\activate.bat 

Create a new Git branch:

git checkout -b feature/conversation-memory 

This allows us to develop new features without affecting the existing implementation on the main branch.

Verify the required packages:

pip show langgraph langgraph-checkpoint langchain-core 

6. Update the Application State

File: app/state.py

Action: Replace the existing code.

In Part 1, we used TypedDict to manage the current question, intent and answer.

Now we will use LangGraph's built-in MessagesState.

from langgraph.graph import MessagesState class AgentState(MessagesState): question: str intent: str answer: str 

MessagesState provides a built-in messages field that automatically merges new messages into the existing conversation history.

Important message types

Message Type Purpose
HumanMessage User input
AIMessage AI-generated response
SystemMessage Instructions provided to the model

This allows us to maintain structured conversation history without manually appending every message.

7. Make Intent Classification Context-Aware

File: app/nodes.py

Action: Update the imports and replace the existing classify_intent() function.

Consider the following conversation:

User: Explain Angular Signals.

AI: Angular Signals are reactive values.

User: Give me another example.

Without previous messages, the classifier may not understand what example the user is requesting.

We can solve this using MessagesPlaceholder.

from typing import Literal from pydantic import BaseModel from langchain_core.prompts import ( ChatPromptTemplate, MessagesPlaceholder ) from app.llm import llm from app.state import AgentState class IntentResult(BaseModel): intent: Literal["coding", "email", "general"] def classify_intent(state: AgentState): prompt = ChatPromptTemplate.from_messages([ ("system", """ Classify the latest user request using the conversation history. coding: Programming-related questions. email: Email writing requests. general: All other questions. Consider previous messages when the user asks a follow-up question. """), MessagesPlaceholder( variable_name="messages" ) ]) chain = prompt | llm.with_structured_output( IntentResult ) response = chain.invoke({ "messages": state["messages"] }) return { "intent": response.intent } 

MessagesPlaceholder inserts the conversation history into the prompt.

The classifier can now use previous messages to understand follow-up questions.

8. Generate Context-Aware Responses

File: app/nodes.py

Action: Update generate_answer() and the specialized assistant nodes.

Add the following imports:

from langchain_core.messages import ( SystemMessage, AIMessage ) 

Replace the existing response generation function:

def generate_answer( state: AgentState, instruction: str ): messages = [ SystemMessage(content=instruction), *state["messages"] ] response = llm.invoke(messages) return { "answer": response.text, "messages": [ AIMessage(content=response.text) ] } 

Update the specialized assistant nodes:

def coding_node(state: AgentState): return generate_answer( state, "You are a senior software engineer. " "Explain concepts with simple code examples. " "Use previous conversation context." ) def email_node(state: AgentState): return generate_answer( state, "You are a professional email writer. " "Generate a subject and concise email body. " "Use previous conversation context." ) def general_node(state: AgentState): return generate_answer( state, "You are a helpful AI assistant. " "Provide clear and accurate answers. " "Remember relevant conversation details." ) 

The model now receives previous conversation messages along with the latest question.

The generated AI response is also added to the conversation state.

9. Configure LangGraph In-Memory Checkpoints

File: app/graph.py

Action: Add a checkpointer and update graph compilation.

A checkpointer saves snapshots of the LangGraph state during workflow execution.

For our initial implementation, we will use InMemorySaver.

Add the import:

from langgraph.checkpoint.memory import InMemorySaver 

Replace the existing graph compilation:

memory = InMemorySaver() graph = workflow.compile( checkpointer=memory ) 

Keep the existing nodes, edges and conditional routing unchanged.

Our application can now save conversation state while the server is running.

However, this memory is stored in RAM and will be lost when the application restarts.

We will solve this using PostgreSQL later in this article.

10. Add Thread-Based Conversation Management

File: app/schemas.py

Action: Replace the existing request and response models.

A thread ID identifies a specific conversation.

For example:

Thread ID Conversation
user-101 Python programming
user-102 Email writing
user-103 Angular development

Each thread maintains its own conversation history.

from pydantic import BaseModel, Field class ChatRequest(BaseModel): question: str = Field( min_length=1, max_length=5000 ) thread_id: str = Field( min_length=1, max_length=100 ) class ChatResponse(BaseModel): thread_id: str question: str intent: str answer: str 

The client must now provide a thread ID along with every question.

Using the same thread ID allows the assistant to continue an existing conversation.

11. Update the FastAPI Chat Endpoint

File: app/main.py

Action: Replace the existing /chat endpoint.

Make sure the following imports are available:

import logging from fastapi import FastAPI, HTTPException from langchain_core.messages import HumanMessage from app.graph import graph from app.schemas import ChatRequest, ChatResponse logger = logging.getLogger(__name__) 

Update the chat endpoint:

@app.post("/chat", response_model=ChatResponse) def chat(request: ChatRequest): try: config = { "configurable": { "thread_id": request.thread_id } } result = graph.invoke( { "question": request.question, "messages": [ HumanMessage( content=request.question ) ] }, config=config ) return ChatResponse( thread_id=request.thread_id, question=request.question, intent=result["intent"], answer=result["answer"] ) except Exception: logger.exception("AI workflow failed") raise HTTPException( status_code=500, detail="AI workflow failed" ) 

The important change is the thread_id configuration.

LangGraph uses this identifier to retrieve the existing conversation state and merge the latest user message.

We do not need to send the entire conversation history from the client.

12. Test Conversation Memory

Start the application:

uvicorn app.main:app --reload 

Open Swagger UI:

http://127.0.0.1:8000/docs

Test 1 — Introduce yourself

Execute POST /chat:

{ "question": "My name is Jayakrishna and I am a software developer.", "thread_id": "user-101" } 

Test 2 — Ask a follow-up question

{ "question": "What is my name and profession?", "thread_id": "user-101" } 

Expected response:

Your name is Jayakrishna, and you are a software developer. 

Test 3 — Use a different thread

{ "question": "What is my name?", "thread_id": "user-102" } 

The assistant should not know the name provided in the previous conversation.

This confirms that different thread IDs maintain separate conversation states.

13. Implement Message Trimming

As conversations grow, sending every previous message to the model can increase token consumption, response time and API costs.

Message trimming helps us limit the conversation context sent to the model.

File: app/utils.py

Action: Create a new file.

from langchain_core.messages import trim_messages def get_recent_messages(messages): return trim_messages( messages, max_tokens=10, token_counter=len, strategy="last", start_on="human", include_system=False, allow_partial=False ) 

File: app/nodes.py

Action: Import the utility and update both AI functions.

Add the import:

from app.utils import get_recent_messages 

Inside classify_intent(), replace the chain invocation with:

response = chain.invoke({ "messages": get_recent_messages( state["messages"] ) }) 

Inside generate_answer(), replace the message preparation logic with:

recent_messages = get_recent_messages( state["messages"] ) messages = [ SystemMessage(content=instruction), *recent_messages ] 

Keep the remaining function logic unchanged.

Now the model receives a maximum of 10 recent conversation messages.

Since we use token_counter=len, we are counting messages rather than actual LLM tokens.

Older messages remain in storage. They are simply excluded from the current model request.

14. Create a Conversation History API

File: app/main.py

Action: Add a new GET endpoint below the existing chat endpoint.

We can retrieve the saved conversation using LangGraph's get_state() method.

@app.get("/history/{thread_id}") def get_history(thread_id: str): config = { "configurable": { "thread_id": thread_id } } state = graph.get_state(config) messages = state.values.get( "messages", [] ) history = [ { "role": message.type, "content": message.content } for message in messages ] return { "thread_id": thread_id, "total_messages": len(history), "history": history } 

Example API request:

GET /history/user-101 

Example response:

{ "thread_id": "user-101", "total_messages": 2, "history": [ { "role": "human", "content": "My name is Jayakrishna." }, { "role": "ai", "content": "Nice to meet you!" } ] } 

This endpoint will be useful when we build our React frontend in a future article.

15. Create a Clear Memory API

File: app/main.py

Action: Update the graph import and add a DELETE endpoint.

Update the import:

from app.graph import graph, memory 

Add the following endpoint:

@app.delete("/memory/{thread_id}") def clear_memory(thread_id: str): memory.delete_thread(thread_id) return { "thread_id": thread_id, "message": "Conversation memory cleared", "status": "success" } 

Example request:

DELETE /memory/user-101 

Expected response:

{ "thread_id": "user-101", "message": "Conversation memory cleared", "status": "success" } 

This removes the saved checkpoints associated with the selected conversation.

Other conversation threads remain unaffected.

16. Why Do We Need PostgreSQL?

Our application now supports conversation memory, but there is still one limitation.

When we restart FastAPI, all conversations stored using InMemorySaver are lost.

To solve this problem, we need persistent storage.

LangGraph provides a PostgreSQL checkpointer called PostgresSaver.

Feature InMemorySaver PostgresSaver
Storage RAM PostgreSQL
Survives server restart No Yes
Persistent memory No Yes
Thread management Yes Yes
Database required No Yes

I selected PostgreSQL because LangGraph provides direct integration with it.

We can also reuse PostgreSQL with the pgvector extension when we explore vector databases and semantic search in upcoming articles.

17. Install and Configure PostgreSQL

Install PostgreSQL on your local machine and open pgAdmin 4.

Create a new database:

CREATE DATABASE ai_smart_assistant; 

Database configuration:

Configuration Value
Host localhost
Port 5432
Database ai_smart_assistant
Username postgres

Install the required Python dependencies:

pip install langgraph-checkpoint-postgres "psycopg[binary,pool]" 

File: .env

Action: Add the PostgreSQL configuration.

DB_HOST=localhost DB_PORT=5432 DB_NAME=ai_smart_assistant DB_USER=postgres DB_PASSWORD=your_database_password 

Keep the existing Gemini API configuration unchanged.

Also update .env.example with placeholder database credentials.

Never commit your actual .env file, API keys or database passwords to GitHub.

18. Implement Database Connection Pooling

File: app/database.py

Action: Create a new file.

Connection pooling allows the application to reuse existing database connections instead of creating a new connection for every request.

import os from dotenv import load_dotenv from psycopg.conninfo import make_conninfo from psycopg.rows import dict_row from psycopg_pool import ConnectionPool load_dotenv() DB_URI = make_conninfo( host=os.getenv("DB_HOST", "localhost"), port=os.getenv("DB_PORT", "5432"), dbname=os.getenv("DB_NAME"), user=os.getenv("DB_USER"), password=os.getenv("DB_PASSWORD") ) pool = ConnectionPool( conninfo=DB_URI, min_size=1, max_size=10, open=False, kwargs={ "autocommit": True, "prepare_threshold": 0, "row_factory": dict_row } ) 

Configuration explained

Configuration Purpose
min_size Minimum database connections
max_size Maximum database connections
autocommit Automatically commits database operations
prepare_threshold Disables automatic prepared statements
row_factory Returns database rows as dictionaries
open=False Opens the pool during application startup

Test database connectivity:

python -c "from app.database import pool; pool.open(); pool.wait(); print('PostgreSQL connected successfully'); pool.close()" 

Expected output:

PostgreSQL connected successfully 

19. Integrate PostgreSQL with LangGraph

File: app/graph.py

Action: Replace InMemorySaver with PostgresSaver.

Remove the existing import:

from langgraph.checkpoint.memory import InMemorySaver 

Add the following imports:

from langgraph.checkpoint.postgres import PostgresSaver from app.database import pool 

Replace:

memory = InMemorySaver() 

With:

memory = PostgresSaver(pool) 

Keep the graph compilation:

graph = workflow.compile( checkpointer=memory ) 

No changes are required in our existing intent classifier, specialized nodes or conditional routing.

LangGraph will now use PostgreSQL to store conversation checkpoints.

20. Manage the FastAPI Application Lifecycle

File: app/main.py

Action: Add a lifespan handler and update the FastAPI configuration.

We need to open database connections when the application starts and close them when it shuts down.

Add the following imports:

from contextlib import asynccontextmanager from app.database import pool 

Make sure the graph import includes both:

from app.graph import graph, memory 

Add the lifespan function before the FastAPI application declaration:

@asynccontextmanager async def lifespan(app: FastAPI): try: pool.open() pool.wait() memory.setup() logger.info( "PostgreSQL memory initialized" ) yield finally: pool.close() 

Replace the existing FastAPI declaration:

app = FastAPI( title="AI Smart Assistant", description="Conversational AI with PostgreSQL Memory", version="2.1.0", lifespan=lifespan ) 

Update the home endpoint:

@app.get("/") def home(): return { "message": Source:https://dev.to/jayakrishna_chadalawada/adding-conversation-memory-to-ai-assistants-with-langgraph-and-postgresql-ai-engineering-series-2-5514

Related posts