Objectives
- Understand state persistence and message accumulation.
- Build a looping dialogue agent that appends interactions.
- Maintain contextual conversation state.
Agent II: Memory Agent
Goal
Build a stateful chatbot that remembers conversation history and appends responses back to the message list.Sample Input
Sequential inputs:{"messages": [HumanMessage(content="Hi, my name is Satish.")]}{"messages": [HumanMessage(content="What is my name?")]}(including history)
Sample Output
"Hello Satish! Nice to meet you.""Your name is Satish."
Plan
- Define the
AgentStateschema containingmessages(a list of messages, using both HumanMessage and AIMessage). - Create the
processnode function that invokes the LLM with the full message history and appends the result tomessages. - Build the graph, compile it, and invoke it sequentially to see it remember previous details.
Code Implementation
1. Define the State Schema
We define a schemaAgentState with a list of messages:
2. Define the Node Function
The node function invokes the model with the entire message history and appends the model’s response back into the state:3. Build and Compile the Graph
4. Invoke the Agent
We invoke the compiled agent sequentially:Exercise: Math Tutor Memory Agent 🧮
Goal
Build a Math Tutor chatbot that remembers the user’s name and guides them through math questions, keeping conversation context.Sample Input
Sequential inputs:"Hi, I am Rahul. I need help with arithmetic.""What is my name and what subject did I ask for help with?"
Sample Output
"Hello Rahul! I'd be happy to help you with arithmetic. What is your first question?""Your name is Rahul, and you asked for help with arithmetic."
Plan
- Create a
TypedDictfor the list of conversation messages. - Write
tutor_nodethat binds a math system message instruction, runs the LLM on the chat list, and appends the response. - Register the tutor node, set entry/finish points, compile the graph.
- Test with sequential questions to confirm memory retention.
Solution
Solution
Practice & Exercises
To reinforce what you’ve learned in this section, practice with the interactive notebook:Practice & Exercises
Practice building stateful chatbots, accumulating messages, and persisting conversation history.💻 VS Code | 🚀 Colab | 📥 Download