Managing Agent Memory and Sessions
1. Understanding Short-Term vs Long-Term Memory
| Memory Type | Description | Characteristics | Use Case |
|---|---|---|---|
| Short-Term Memory | Temporary storage for active context and recent interactions |
|
Active conversation flow, immediate task execution |
| Long-Term Memory | Persistent storage for learned patterns, user preferences, and historical data |
|
User preference persistence, knowledge base retrieval, task history |
Example: Memory Management in AI Agents
const agent = new AIAssistant({
shortTermMemory: {
maxSize: 500,
ttl: 300000 // 5 minutes
},
longTermMemory: {
storageType: 'vectorDB',
retentionPolicy: 'userPreferences'
}
});
Key Differences Summary
- Short-Term: Focused on current context and recent exchanges
- Long-Term: Stores learned behaviors, user-specific data, and persistent knowledge
- Interaction: Short-term is managed automatically; long-term requires explicit configuration
2. Persisting Session State
| Storage Method | Description | Use Case | Notes |
|---|---|---|---|
| Local Storage | Browser-based key-value storage with 5MB limit | Small session data, user preferences | Not suitable for large or sensitive data |
| IndexedDB | Client-side NoSQL database with larger capacity | Complex session state, logs, cached data | More complex API; requires structured cloning |
| Server-Side DB | Backend storage (e.g., PostgreSQL, MongoDB) | Multi-session tracking, shared context | Requires backend integration and sync logic |
| Memory Cache | In-memory storage (e.g., Redis, Memcached) | High-performance session caching | Session data lost on server restart |
Example: Saving Session to LocalStorage
const sessionState = {
userId: 'user123',
messages: [
{ role: 'user', content: 'Hello AI' },
{ role: 'assistant', content: 'Hi there!' }
],
timestamp: Date.now()
};
localStorage.setItem('aiSession', JSON.stringify(sessionState));
Example: Loading Session from LocalStorage
const savedSession = localStorage.getItem('aiSession');
if (savedSession) {
const sessionState = JSON.parse(savedSession);
console.log('Restored session:', sessionState.messages);
} else {
console.log('No previous session found');
}
Note: LocalStorage is synchronous and can block the UI. For large sessions, consider using IndexedDB or async storage solutions.
Warning: Never store sensitive session data (e.g., tokens, passwords) in client-side storage without encryption.
3. Resuming Previous Sessions
| Session ID | Description | Usage |
|---|---|---|
| session.id | Unique identifier for the session | "sess_abc123" |
| session.timestamp | Start time of the session | "2026-01-15T10:00:00Z" |
| session.context | Stored context from previous interactions | { messages: [...], memory: [...] } |
Example: Resuming Session
const session = await agent.resumeSession("sess_abc123");
console.log(session.context.messages); // Loaded messages
Note: Sessions are typically stored in-memory or persisted to a database for long-term access.
Session Resumption Process
- Load session by ID from storage
- Rehydrate context and memory state
- Resume interaction with previous state
4. Storing User Preferences in Memory
| Preference | Storage Method | Description | Notes |
|---|---|---|---|
| user.language | localStorage |
User's preferred programming language | Used for code suggestions and formatting |
| user.theme | sessionStorage |
UI theme preference (dark/light) | Reset on session end |
| user.editor | localStorage |
Preferred code editor (VSCode, IntelliJ) | Used for context-aware suggestions |
| user.shortcuts | localStorage |
Custom keyboard shortcuts | Synced across sessions |
Example: Saving User Preferences
const userPreferences = {
language: 'JavaScript',
theme: 'dark',
editor: 'VSCode',
shortcuts: {
save: 'Ctrl+S',
run: 'F5'
}
};
localStorage.setItem('userPreferences', JSON.stringify(userPreferences));
Example: Loading User Preferences
const savedPrefs = localStorage.getItem('userPreferences');
if (savedPrefs) {
const prefs = JSON.parse(savedPrefs);
// Apply preferences to agent
applyPreferences(prefs);
}
Note: Preferences are stored in the browser's local storage to persist across sessions.
5. Scoping Memory to Project vs User
| Scope Type | Description | Use Case | Memory Persistence |
|---|---|---|---|
| Project-Level Memory | Shared across all users within a project or workspace | Team collaboration, shared configuration, project-specific context | NEW Persistent across sessions |
| User-Level Memory | Unique to each individual user, isolated from others | Personal preferences, user-specific settings, individual context | Session-based, cleared on logout or session timeout |
Example: Memory Scoping Configuration
const config = {
projectMemory: {
enabled: true,
scope: "shared",
persistence: "persistent"
},
userMemory: {
enabled: true,
scope: "isolated",
persistence: "session"
}
};
Key Considerations
- Project memory is ideal for team-wide context, such as shared code standards or project-specific AI models.
- User memory ensures privacy and personalization, storing individual preferences or session-specific data.
- Memory scoping can be configured via
memory.configor environment variables.
6. Clearing and Resetting Memory
| Operation | Description | Example |
|---|---|---|
| clearMemory() | Resets the agent's short-term memory, removing all previous context and conversation history. | agent.clearMemory(); |
| resetSession() | Resets the entire session state, including memory and any ongoing tasks or workflows. | agent.resetSession(); |
| setMemoryLimit() | Sets a maximum size or duration for memory retention, triggering automatic clearing when exceeded. | agent.setMemoryLimit({ maxEntries: 100 }); |
Note: Memory clearing does not affect long-term storage or persistent configurations.
Warning: Clearing memory may result in loss of context for ongoing tasks or incomplete workflows.
Memory Management Best Practices
- Use
clearMemory()to reset context between independent tasks. - Call
resetSession()when starting a new workflow or project. - Set
maxEntriesto prevent memory bloat in long-running agents.
7. Debugging Memory Retrieval Issues
Example: Logging Memory Access Patterns
// Log memory access for debugging
const debugMemory = (agent, query) => {
console.log("Query:", query);
console.log("Retrieved memories:", agent.memory.get(query));
return agent.memory.get(query);
};
// Usage
const result = debugMemory(myAgent, "user's last project");
| Issue | Description | Solution |
|---|---|---|
| Memory not retrieved | Query returns no results despite existing data | Check query relevance and memory indexing |
| Stale data returned | Outdated memory entries are retrieved | Implement TTL or refresh logic |
| High latency | Memory retrieval takes too long | Optimize indexing or use caching |
Note: Use
agent.memory.debug() to inspect internal state and logs.
Warning: Avoid querying large memory sets without filters; can cause performance degradation.
Common Debugging Steps
- Verify query string matches memory keys
- Check for memory expiration or deletion
- Review indexing strategy and search algorithms
- Analyze logs for retrieval timing or errors
8. Organizing Memory Files by Topic
| Topic | Description | File Naming Convention | Best Practices |
|---|---|---|---|
| Code Context | Stores recent code snippets and context for agent understanding | context_<timestamp>.json |
Use descriptive timestamps to track changes over time |
| Conversation History | Logs of all interactions between user and AI agent | conversation_<session_id>.json |
Include session IDs to correlate with user sessions |
| Task Metadata | Information about ongoing or completed tasks | task_<task_id>.json |
Store task IDs to enable retrieval and tracking |
| Configuration Settings | Agent-specific settings and preferences | config_<agent_name>.json |
Use agent names to distinguish between different agents |
Example: Memory File Organization
{
"context_2026-04-05_14-30.json": {
"code_snippets": [
"function calculateTotal(items) { return items.reduce((sum, item) => sum + item.price, 0); }"
],
"last_updated": "2026-04-05T14:30:00Z"
},
"conversation_session_abc123.json": {
"messages": [
{ "role": "user", "content": "How do I implement a search function?" },
{ "role": "assistant", "content": "You can use the built-in search API..." }
],
"session_id": "abc123"
},
"task_001.json": {
"id": "001",
"status": "in_progress",
"description": "Implement user authentication"
},
"config_ai_dev_agent.json": {
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 150
}
}