Agent 2 – Chatbot with Persistent Memory (LangGraph + LangChain) A conversational AI agent that maintains full conversation history using structured message types (HumanMessage, AIMessage) and demonstrates how to persist memory beyond runtime using files or databases. This project is a foundational step toward stateful, memory-enabled AI agents.
🚀 Objectives
✅ Use different message types:
HumanMessage
AIMessage
✅ Maintain full conversation history
✅ Build the agent using LangGraph
✅ Use LLM via LangChain
ChatGoogleGenerativeAI (Gemini)
(Can be swapped with ChatOpenAI – GPT-4o)
✅ Create a memory mechanism for the agent
🧩 Tech Stack
Python
LangChain
LangGraph
Google Gemini Pro
dotenv
TypedDict for state management
📂 Project Structure ├── agent.py ├── .env ├── logging.txt ├── README.md
🔐 Environment Setup Create a .env file in the root directory: GEMINI_API_KEY=your_google_api_key_here
🧠 How Memory Works The agent stores conversation as: List[Union[HumanMessage, AIMessage]]
Each turn:
User input → HumanMessage
LLM response → AIMessage
Messages appended to state
Full history passed back to the model
This allows the agent to remember past context during the session.
⚙️ Core Agent Logic Agent State Definition class AgentState(TypedDict): messages: List[Union[HumanMessage, AIMessage]]
Processing Node (Memory Update) def process(state: AgentState) -> AgentState: response = llm.invoke(state["messages"]) state["messages"].append(AIMessage(content=response.content)) return state
This node:
Receives full conversation history
Generates a response
Appends it back to memory
LangGraph Flow START → process → END
💬 Running the Chatbot python agent.py
Example: Enter: Hi AI: Hello! How can I help you today? Enter: What did I just say? AI: You said "Hi".
Type exit to end the conversation.
📝 Conversation Logging At the end of the session, the full conversation is saved to: logging.txt
Format: You : ... AI : ...
❗ Current Limitation ❌ Memory gets wiped after program exits Because memory is stored in-memory (RAM), it resets when the script stops.
✅ Solutions for Persistent Memory To prevent memory loss, you can store conversation data in: 1️⃣ Text Files / Markdown Append messages after every turn Reload on startup 2️⃣ Database (SQL / NoSQL)
SQLite PostgreSQL MongoDB
3️⃣ Vector Database (Best for Long-Term Memory)
ChromaDB FAISS Pinecone Weaviate This allows: Semantic recall Long-term memory
RAG-based agents