Building a Simple Chatbot - Part 3: Adding Context
Our chatbot can respond to messages, but it doesn't remember anything. Let's add conversation context.
The Problem
In [Part 1](/blog/building-simple-chatbot-no-ai-part-1) we built the UI. In [Part 2](/blog/building-simple-chatbot-no-ai-part-2) we added response matching. But conversations like this happen:
User: What's your name?
Bot: I'm ChatBot!
User: Nice to meet you
Bot: I'm not sure I understand...
The bot doesn't remember it just introduced itself.
Adding Memory
Conversation State
const conversation = {
messages: [],
context: {
askedName: false,
userName: null,
topic: null
}
};
Updating Context
function updateContext(userInput, botResponse) {
const input = userInput.toLowerCase();
// Track if we've exchanged names
if (input.includes('your name')) {
conversation.context.askedName = true;
}
// Remember user's name if they introduce themselves
const nameMatch = input.match(/my name is (\w+)/i);
if (nameMatch) {
conversation.context.userName = nameMatch[1];
}
// Track current topic
if (input.includes('weather')) conversation.context.topic = 'weather';
if (input.includes('help')) conversation.context.topic = 'help';
}
Context-Aware Responses
function findResponse(userInput) {
const input = userInput.toLowerCase();
const { context } = conversation;
// Use context to improve responses
if (context.userName && input.includes('hello')) {
return `Hi again, ${context.userName}!`;
}
// Follow-up on previous topic
if (context.topic === 'weather' && input.includes('tomorrow')) {
return "I can't actually predict weather, but I hope it's nice!";
}
// ... rest of pattern matching
}
Conversation Flow
For more complex flows, use a state machine:
const flows = {
greeting: {
entry: (ctx) => "Hi! What's your name?",
next: 'waiting_name'
},
waiting_name: {
match: /my name is (\w+)/i,
action: (ctx, match) => {
ctx.userName = match[1];
return `Nice to meet you, ${match[1]}! How can I help?`;
},
next: 'ready'
},
ready: {
// Normal conversation
}
};
let currentState = 'greeting';
Persistence
For longer memory, save to localStorage:
function saveConversation() {
localStorage.setItem('chatbot_context',
JSON.stringify(conversation.context));
}
function loadConversation() {
const saved = localStorage.getItem('chatbot_context');
if (saved) {
conversation.context = JSON.parse(saved);
}
}
Now returning users get a personalized greeting!
What We've Built
Over this series, we've created:
- ✅ Chat UI with message bubbles
- ✅ Pattern matching responses
- ✅ Randomized replies
- ✅ Conversation context
- ✅ State persistence
All without any AI! The full code is at github.com/adhddev/simple-chatbot.
Where would you take this next?