Memory
Persistent conversation memory with vector search and automatic context integration Learn the setup patterns, APIs, and practical examples needed to build...
Persistent conversation memory with vector search and automatic context integration
Overview
The Memory system provides agents with long-term memory capabilities, enabling them to remember past conversations, learn from interactions, and maintain context across sessions. When memory is enabled, agents automatically store and retrieve relevant information from previous conversations, creating a more personalized and context-aware experience.
Enabling Memory
Enable memory for an agent by setting the memory option to true:
import { Agent } from '@astreus-ai/astreus';
const agent = await Agent.create({
name: 'MemoryAgent',
model: 'gpt-4o',
memory: true // Enable persistent memory
});Basic Usage
Here's a complete example showing how memory works across conversations:
import { Agent } from '@astreus-ai/astreus';
// Create an agent with memory
const agent = await Agent.create({
name: 'PersonalAssistant',
model: 'gpt-4o',
memory: true,
systemPrompt: 'You are a helpful personal assistant who remembers user preferences.'
});
// First conversation
const response1 = await agent.ask('My name is John and I love TypeScript');
console.log(response1);
// Output: "Nice to meet you, John! It's great that you love TypeScript..."
// Later conversation - agent remembers
const response2 = await agent.ask('What programming language do I like?');
console.log(response2);
// Output: "You mentioned that you love TypeScript, John!"
// Memory persists even after restarting
const sameAgent = await Agent.create({
name: 'PersonalAssistant', // Same name retrieves existing memories
model: 'gpt-4o',
memory: true
});
const response3 = await sameAgent.ask('Do you remember my name?');
console.log(response3);
// Output: "Yes, your name is John!"Memory Methods
When memory is enabled, agents have access to these memory management methods:
// Add a memory manually
const memory = await agent.addMemory(
'Important project information: Budget is $50k',
{ type: 'project', category: 'budget' }, // Optional metadata
{ graphId: 'project-123', taskId: 'task-456', sessionId: 'session-789' } // Optional context for memory isolation
);
// Remember conversation with role context
const userMemory = await agent.rememberConversation(
'I prefer TypeScript over JavaScript',
'user'
);
// Get a specific memory by ID
const existingMemory = await agent.getMemory(memory.id);
// Search memories by content (semantic search with embeddings)
const budgetMemories = await agent.searchMemories('budget', {
limit: 5,
startDate: new Date('2024-01-01')
});
// Vector similarity search for semantic matching
const happyMemories = await agent.searchMemoriesBySimilarity('joyful moments', {
similarityThreshold: 0.7, // Minimum similarity score
limit: 10
});
// List all memories with options
const allMemories = await agent.listMemories({
limit: 20,
orderBy: 'createdAt',
order: 'desc'
});
// Update a memory
const updatedMemory = await agent.updateMemory(memory.id, {
content: 'Updated budget: $75k',
metadata: { type: 'project', category: 'budget', updated: true }
});
// Delete a specific memory
const deleted = await agent.deleteMemory(memory.id);
// Generate embedding for existing memory (migration/repair)
const result = await agent.generateEmbeddingForMemory(memory.id);
if (result.success) {
console.log('✅ Embedding generated successfully');
}
// Clear all memories
const deletedCount = await agent.clearMemories();
// Clear memories with options
const deletedCount = await agent.clearMemories({
syncWithContext: false // Prevent context synchronization (default: true)
});Similarity Search Mathematics
When searching memories using vector similarity, the system calculates similarity scores between query and memory embeddings:
Cosine Similarity Score
Where:
- is the query embedding vector
- is the memory embedding vector
- Result ranges from 0 (completely different) to 1 (identical)
Distance-Based Score
For distance metrics, the similarity score is calculated as:
Where is the Euclidean distance between vectors.
Threshold Filtering
Memories are returned only if:
Where is the similarityThreshold parameter (default: 0.7).
Memory Object Structure
interface Memory {
id: string; // Unique memory identifier (UUID)
agentId: string; // ID of the owning agent (UUID)
graphId?: string; // Graph context (for memory isolation)
taskId?: string; // Task context (for memory isolation)
sessionId?: string; // Session context (for memory isolation)
content: string; // Memory content
embedding?: number[]; // Vector embedding (auto-generated)
metadata?: MetadataObject; // Custom metadata
createdAt: Date; // When memory was created
updatedAt: Date; // Last update time
}
interface MemorySearchOptions {
limit?: number; // Max results (default: 10 for search, 100 for list)
offset?: number; // Skip results (default: 0)
pageSize?: number; // Pagination size for large result sets
graphId?: string; // Filter by graph context
taskId?: string; // Filter by task context
sessionId?: string; // Filter by session context
orderBy?: 'createdAt' | 'updatedAt' | 'relevance'; // Sort field
order?: 'asc' | 'desc'; // Sort order (default: 'desc')
startDate?: Date; // Filter from date
endDate?: Date; // Filter to date
similarityThreshold?: number; // Similarity threshold (0-1, default: 0.7)
useEmbedding?: boolean; // Use embedding search (default: true)
}Response Types
Understanding what each memory method returns helps you handle responses correctly in your code.
Memory Object Response
When creating or retrieving memories, you receive a complete Memory object:
const memory = await agent.addMemory("User prefers dark mode", {
type: "preference",
importance: "high"
});
// Response structure:
{
id: "550e8400-e29b-41d4-a716-446655440000", // UUID string
agentId: "agent-uuid-123", // UUID string
content: "User prefers dark mode",
embedding: [0.1, 0.2, 0.3, ..., 0.768], // 1536 dimensions array
metadata: {
type: "preference",
importance: "high"
},
createdAt: Date('2024-01-15T10:30:00Z'),
updatedAt: Date('2024-01-15T10:30:00Z')
}Memory List Response
Search and list methods return an array of Memory objects:
const memories = await agent.searchMemories("preferences", {
limit: 5,
similarityThreshold: 0.7
});
// Response structure:
[
{
id: "memory-uuid-1",
agentId: "agent-uuid",
content: "User prefers dark mode",
embedding: [0.1, 0.2, ...],
metadata: { type: "preference" },
createdAt: Date(...),
updatedAt: Date(...)
},
{
id: "memory-uuid-2",
agentId: "agent-uuid",
content: "User timezone is PST",
embedding: [0.15, 0.25, ...],
metadata: { type: "preference" },
createdAt: Date(...),
updatedAt: Date(...)
}
]Generate Embedding Response
Embedding generation returns a detailed success/failure object:
const result = await agent.generateEmbeddingForMemory(memory.id);
// Response structure:
{
success: true,
message: "Embedding generated successfully",
embedding: [0.1, 0.2, 0.3, ..., 0.768] // Optional: included on success
}
// On failure (possible messages):
{
success: false,
message: "Memory not found" // or "Memory already has embedding", "Failed to generate embedding", etc.
}Delete Response
Delete operations return a boolean indicating success:
const deleted = await agent.deleteMemory(memory.id);
// Returns: true or falseClear Memories Response
Clearing all memories returns the count of deleted items:
const deletedCount = await agent.clearMemories();
// Returns: 15 (number of memories deleted)Last updated: May 26, 2026