Memory Management
Introduction
The CMND React SDK provides memory management capabilities that allow you to store and manage conversation context through the initialMemory prop and memory management functions.
This guide contains information on how to initialize memory values, update conversation memory during runtime, and remove specific memory keys from active conversations.
Memory Features
- Initial Memory Setup
- Set Memory
- Delete Memory
Initializing Memory
You can initialize the chat with predefined memory values using the initialMemory prop when setting up the ChatProvider:
<ChatProvider
baseUrl="<your-cmnd-api-base-url>"
chatbotId={"<your-chatbot-id>"}
organizationId={"<your-organization-id>"}
initialMemory={{
accessToken: "your-access-token",
date: "2022-01-01",
// Add any other initial memory key-value pairs
}}
/>
Setting Memory Values
The setCurrentConversationMemory function allows you to set or update memory values during an active conversation:
import { setCurrentConversationMemory } from "@cmnd-ai/chatbot-react";
// Set single or multiple memory values
await setCurrentConversationMemory({
name: "John Doe",
email: "jon@doe.com",
phone: "1234567890",
});
setCurrentConversationMemory is only available during an active chat thread.
Deleting Memory Values
The deleteCurrentConversationMemory function enables you to remove specific memory keys from the current conversation:
import { deleteCurrentConversationMemory } from "@cmnd-ai/chatbot-react";
// Delete a specific memory key
await deleteCurrentConversationMemory("name");
deleteCurrentConversationMemory is only available during an active chat thread.
Usage Example
Complete Implementation Example
Here's a complete example showing how to implement memory management in your chat application:
import { ChatProvider } from "@cmnd-ai/chatbot-react";
import {
setCurrentConversationMemory,
deleteCurrentConversationMemory,
} from "@cmnd-ai/chatbot-react";
function ChatApp() {
const handleSetMemory = async () => {
try {
const response = await setCurrentConversationMemory({
name: "John Doe",
email: "jon@doe.com",
phone: "1234567890",
});
console.log("Memory Set:", response);
} catch (error) {
console.error("Error setting memory:", error);
}
};
const handleDeleteMemory = async () => {
try {
const response = await deleteCurrentConversationMemory("name");
console.log("Memory Deleted:", response);
} catch (error) {
console.error("Error deleting memory:", error);
}
};
return (
<>
<ChatProvider
baseUrl="<your-cmnd-api-base-url>"
chatbotId={"<your-chatbot-id>"}
organizationId={"<your-organization-id>"}
initialMemory={{
accessToken: "your-access-token",
date: "2022-01-01",
}}
/>
<Button onClick={handleSetMemory}>Set Memory</Button>
<Button onClick={handleDeleteMemory}>Delete Memory</Button>
</>
);
}
Best Practices
- Security Considerations
- Performance Optimization
- Error Handling
- Don't store anything sensitive in memory, as it's not meant for secure storage.
- Regularly clean up unnecessary memory entries.
- Only store essential information in memory.
- Clear outdated memory values when no longer needed.
- Avoid storing large data structures in memory.
- Implement proper error handling for memory operations.
- Validate memory values before storage.
- Provide feedback for failed memory operations.
- Memory values persist only for the current conversation session.
- Memory operations are asynchronous and return Promises.
- Ensure proper error handling for memory management functions.
- Memory keys should be strings and values should be serializable.
Advanced Usage
Memory Persistence Strategies
When building applications that require memory persistence across sessions, consider implementing a custom storage solution:
import { useEffect } from "react";
import {
ChatProvider,
setCurrentConversationMemory,
} from "@cmnd-ai/chatbot-react";
function PersistentChatApp() {
// Load saved memory from localStorage when component mounts
useEffect(() => {
const loadSavedMemory = async () => {
try {
const savedMemory = localStorage.getItem("chatMemory");
if (savedMemory) {
const parsedMemory = JSON.parse(savedMemory);
await setCurrentConversationMemory(parsedMemory);
console.log("Restored memory from local storage");
}
} catch (error) {
console.error("Error restoring memory:", error);
}
};
// Small delay to ensure chat thread is established
const timer = setTimeout(loadSavedMemory, 1000);
return () => clearTimeout(timer);
}, []);
// Save memory handler example
const saveMemoryToStorage = async (memoryObject) => {
try {
// First update the conversation memory
await setCurrentConversationMemory(memoryObject);
// Then save to localStorage
localStorage.setItem("chatMemory", JSON.stringify(memoryObject));
console.log("Memory saved to local storage");
} catch (error) {
console.error("Error saving memory:", error);
}
};
return (
<>
<ChatProvider
baseUrl="<your-cmnd-api-base-url>"
chatbotId={"<your-chatbot-id>"}
organizationId={"<your-organization-id>"}
initialMemory={{
// Initial values that will be overridden by localStorage if available
lastVisit: new Date().toISOString(),
}}
/>
{/* Application UI */}
</>
);
}
This approach allows you to maintain conversation context across browser sessions or page refreshes.