Chat History Example
Memory allows your agent to remember previous interactions. This example demonstrates how to use theBufferMemory provider to maintain context across multiple runs using sessions.
What You’ll Learn
- How to set up memory for your agent
- How to use sessions to maintain conversation context
- How to access and inspect conversation history
- How memory works across multiple agent runs
Complete Code
Code Breakdown
1. Initialize Memory
Create a memory provider to store conversation history:BufferMemory stores messages in-process (in memory). For production applications, consider:
- RedisMemory: Store in Redis for distributed systems
- DatabaseMemory: Store in a database for persistence
- Custom Memory: Implement your own
MemoryProvider
2. Add Memory to Agent
Attach the memory provider to your agent:3. Use Sessions
Sessions group related conversations. Use a consistentsessionId across runs:
4. Conversation Flow
Here’s what happens in the example: Turn 1:5. Inspect Memory
Access stored conversation history:- messages: Array of conversation messages
- metadata: Custom data associated with the session
Memory Strategies
Buffer Memory (Simple)
Keeps the last N messages:Sliding Window Memory
Keeps recent messages within a token limit:Summarizing Memory
Summarizes old messages to save space:Multi-User Applications
Use unique session IDs per user:Clearing History
Clear a session when needed:Example Output
Running the example produces:- The user’s name (Sammy)
- The user’s favorite language (TypeScript)
- All information from previous turns
Next Steps
- Learn about Memory Strategies in depth
- Explore Sliding Window Memory for token management
- Check out Summarizing Memory for long conversations
- See the Memory API Reference for custom providers