examples/memory-per-resource-example/README.md
This example demonstrates resource-scoped working memory in Mastra, where working memory persists across all conversation threads for the same user (resourceId).
scope: 'thread'Install dependencies:
pnpm install
Set up environment:
cp .env.example .env
# Add your OpenAI API key to .env
Run the example:
pnpm dev
const memory = new Memory({
storage, // Persistent storage required (LibSQL, PostgreSQL, or Upstash)
options: {
workingMemory: {
enabled: true,
scope: 'resource', // š NEW: Per-resource instead of per-thread
template: `# User Profile
- **Name**:
- **Interests**:
- **Preferences**:
`,
},
},
});
The following storage adapters support per-resource working memory:
@mastra/libsql)@mastra/pg)@mastra/upstash)| Feature | Thread Scope | Resource Scope |
|---|---|---|
| Memory Persistence | Single conversation thread | All threads for same user |
| Use Case | Session-specific context | Long-term user relationships |
| Storage | Any storage adapter | LibSQL, PostgreSQL, Upstash |
| User Experience | Fresh start each thread | Continuous relationship |
| Data Isolation | Per thread | Per user (resourceId) |
resourceIdresources tableresourceId share working memoryCREATE TABLE mastra_resources (
id TEXT PRIMARY KEY, -- resourceId (user identifier)
workingMemory TEXT, -- JSON working memory data
metadata JSONB, -- Additional metadata
createdAt TIMESTAMP, -- Creation time
updatedAt TIMESTAMP -- Last update time
);
workingMemory: {
enabled: true,
scope: 'resource',
template: `# Customer Profile
- **Name**:
- **Company**:
- **Industry**:
- **Pain Points**:
- **Previous Purchases**:
- **Communication Preferences**:
`,
}
instructions: `You are a sales assistant with persistent memory.
š IMPORTANT: You have resource-scoped working memory that persists
across ALL conversations with this customer. Use this to:
- Build long-term customer relationships
- Remember their business needs and preferences
- Track the sales process across multiple touchpoints
- Provide personalized service
Always update your working memory with new information about the customer.`;