Daydreams Logo
Concepts

Memory

How Daydreams agents store, recall, and learn from information.

What is Memory?

Memory is how your agent remembers things between conversations. Just like you remember what you talked about yesterday, agents need memory to be helpful over time.

Real Examples

Here are different types of memory your agent uses:

Short-Term Memory (This Conversation)

short-term-memory.ts
// What happened in the current conversation
const workingMemory = {
  messages: [
    { user: "What's the weather?" },
    { agent: "Let me check..." },
    { action: "getWeather", result: "72°F, sunny" },
    { agent: "It's 72°F and sunny!" },
  ],
  // This gets cleared when conversation ends
};

Long-Term Memory (Persistent Data)

long-term-memory.ts
// What the agent remembers about you
const contextMemory = {
  userId: "alice",
  preferences: {
    favoriteColor: "blue",
    timezone: "America/New_York",
    wantsDetailedWeather: true,
  },
  chatHistory: [
    "Discussed weather preferences on 2024-01-15",
    "Helped with todo list on 2024-01-16",
  ],
  // This persists forever
};

Experience Memory (Learning from Past)

experience-memory.ts
// What the agent learned from previous interactions
const episodicMemory = [
  {
    situation: "User asked about weather in winter",
    action: "Provided temperature + suggested warm clothes",
    result: "User was happy and thanked me",
    lesson: "Winter weather queries benefit from clothing suggestions",
  },
  // Agent can recall and apply these lessons to new situations
];

The Problem: Agents Without Memory Are Useless

Without memory, every conversation starts from scratch:

forgetful-agent.txt
Day 1:
User: "My name is Alice and I like detailed weather reports"
Agent: "Nice to meet you Alice! I'll remember you like detailed weather."

Day 2:
User: "What's the weather?"
Agent: "Hi! I'm not sure who you are. What kind of weather info do you want?"
// ❌ Forgot everything about Alice
// ❌ Has to ask the same questions again
// ❌ Terrible user experience

The Solution: Memory Makes Agents Smart

With memory, agents get better over time:

smart-agent.txt
Day 1:
User: "My name is Alice and I like detailed weather reports"
Agent: "Nice to meet you Alice! I'll remember you like detailed weather."
→ Saves: { user: "Alice", preferences: { detailedWeather: true } }

Day 2:
User: "What's the weather?"
Agent: → Loads: { user: "Alice", preferences: { detailedWeather: true } }
Agent: "Hi Alice! It's 72°F and sunny with 15mph winds from the west,
       humidity at 45%, and clear skies expected all day."
// ✅ Remembered Alice and her preferences
// ✅ Provided detailed weather automatically
// ✅ Great user experience

How Memory Works in Your Agent

1. Agent Automatically Saves Important Information

automatic-memory.ts
// Your agent's context automatically saves important info
const chatContext = context({
  type: "chat",
  schema: z.object({ userId: z.string() }),
 
  create: () => ({
    preferences: {},
    chatHistory: [],
    firstMet: new Date().toISOString(),
  }),
 
  // This memory persists between conversations
});
 
// When user says: "I prefer metric units"
// Agent automatically saves: preferences.units = "metric"
// Next conversation: Agent uses metric units automatically

2. Different Types of Memory for Different Needs

memory-types.ts
const agent = createDreams({
  model: openai("gpt-4o"),
 
  // Configure where memory gets saved
  memory: createMemory(
    // Long-term storage (user preferences, chat history)
    await createMongoMemoryStore({ uri: "mongodb://localhost:27017" }),
 
    // Experience storage (what worked well in the past)
    createChromaVectorStore("agent-experiences")
  ),
 
  // Enable automatic learning from conversations
  generateMemories: true,
});

3. Agent Recalls Relevant Memories

memory-recall.txt
New user question: "How do I cook pasta?"

Agent thinks:
1. Check if I know this user (loads context memory)
2. Recall similar past conversations (searches experience memory)
3. Found: "Previous users liked step-by-step cooking instructions"
4. Respond with detailed cooking steps

Result: Agent gives better answer based on past experience!

Setting Up Memory in Your Agent

Here's how to add memory to your agent:

Basic Memory (In-Memory)

basic-memory.ts
import {
  createDreams,
  createMemory,
  createMemoryStore,
} from "@daydreamsai/core";
 
const agent = createDreams({
  model: openai("gpt-4o"),
 
  // Basic memory - data lost when agent restarts
  memory: createMemory(
    createMemoryStore(), // Stores in RAM
    createVectorStore() // No persistent experience storage
  ),
});

Persistent Memory (Database)

persistent-memory.ts
import { createMongoMemoryStore } from "@daydreamsai/mongo";
import { createChromaVectorStore } from "@daydreamsai/chroma";
 
const agent = createDreams({
  model: openai("gpt-4o"),
 
  // Persistent memory - data survives restarts
  memory: createMemory(
    // Save to MongoDB
    await createMongoMemoryStore({
      uri: "mongodb://localhost:27017",
      dbName: "my-agent-memory",
    }),
 
    // Save experiences to ChromaDB for learning
    createChromaVectorStore("my-agent-experiences")
  ),
 
  // Enable automatic learning
  generateMemories: true,
});

Working with Context Memory

Context memory is what your agent remembers about specific conversations:

context-memory-usage.ts
const userProfileContext = context({
  type: "user-profile",
  schema: z.object({ userId: z.string() }),
 
  // Define what to remember about each user
  create: () => ({
    name: null,
    preferences: {
      language: "en",
      timezone: null,
      communicationStyle: "friendly",
    },
    chatSummary: [],
    lastSeen: null,
  }),
 
  // How this memory appears to the LLM
  render: (state) => `
User Profile: ${state.args.userId}
Name: ${state.memory.name || "Unknown"}
Preferences: ${JSON.stringify(state.memory.preferences)}
Last interaction: ${state.memory.lastSeen || "First time"}
 
Recent chat summary:
${state.memory.chatSummary.slice(-3).join("\n")}
  `,
});

Actions Can Update Memory

memory-updating-action.ts
const updatePreferenceAction = action({
  name: "update-user-preference",
  description: "Updates a user's preference",
  schema: z.object({
    key: z.string(),
    value: z.string(),
  }),
 
  handler: async ({ key, value }, ctx) => {
    // Update the user's memory
    ctx.memory.preferences[key] = value;
    ctx.memory.lastSeen = new Date().toISOString();
 
    // Memory automatically saves after this action
    return {
      success: true,
      message: `Updated ${key} to ${value}`,
    };
  },
});

Experience Memory: Learning from the Past

Your agent can learn from previous conversations:

experience-learning.ts
// Enable automatic experience generation
const agent = createDreams({
  model: openai("gpt-4o"),
  memory: createMemory(
    await createMongoMemoryStore({ uri: "mongodb://localhost:27017" }),
    createChromaVectorStore("experiences")
  ),
 
  // Agent automatically creates "episodes" from conversations
  generateMemories: true,
 
  // Optional: Export training data for fine-tuning
  exportTrainingData: true,
  trainingDataPath: "./agent-training.jsonl",
});
 
// Now when user asks: "How do I bake a cake?"
// Agent recalls: "I helped someone bake a cake before. They liked step-by-step instructions with temperatures."
// Agent provides: Detailed baking instructions with exact temperatures and times

Memory in Action: Complete Example

Here's how all the memory types work together:

complete-memory-example.ts
// 1. User starts conversation
User: "Hi, I'm Sarah. I'm learning to cook."
 
// 2. Agent creates/loads context memory
Context Memory: {
  name: null,  // Will be updated
  interests: [], // Will be updated
  skillLevel: null // Will be updated
}
 
// 3. Agent processes and updates memory
Action: updateUserProfile({
  name: "Sarah",
  interests: ["cooking"],
  skillLevel: "beginner"
})
 
// 4. Later conversation
User: "How do I make pasta?"
 
// 5. Agent loads Sarah's memory
Context Memory: {
  name: "Sarah",
  interests: ["cooking"],
  skillLevel: "beginner"  // Agent knows she's a beginner!
}
 
// 6. Agent recalls similar past experiences
Experience Memory: "When helping beginners with pasta, detailed steps work best"
 
// 7. Agent responds appropriately
Agent: "Hi Sarah! Since you're learning to cook, I'll give you detailed step-by-step pasta instructions..."
 
// ✅ Personalized response based on memory!

Best Practices

1. Choose the Right Memory Storage

memory-storage-choice.ts
// ✅ Good for development - simple setup
memory: createMemory(
  createMemoryStore(), // In-memory, lost on restart
  createVectorStore() // No learning capabilities
);
 
// ✅ Good for production - data persists
memory: createMemory(
  await createMongoMemoryStore({ uri: process.env.MONGODB_URI }),
  createChromaVectorStore("prod-experiences")
);

2. Design Clear Memory Structures

clear-memory-structure.ts
// ✅ Good - clear, organized structure
interface UserMemory {
  profile: {
    name: string;
    email: string;
    joinDate: string;
  };
  preferences: {
    language: string;
    timezone: string;
    notifications: boolean;
  };
  activityHistory: Array<{
    action: string;
    timestamp: string;
    result: string;
  }>;
}
 
// ❌ Bad - everything mixed together
interface MessyMemory {
  stuff: any;
  data: any;
  things: any;
}

3. Don't Store Too Much

memory-size-management.ts
// ✅ Good - keep recent, relevant data
render: (state) => {
  const recentChats = state.memory.chatHistory.slice(-5); // Last 5 only
  const importantPrefs = {
    language: state.memory.preferences.language,
    timezone: state.memory.preferences.timezone,
  };
 
  return `Recent activity: ${recentChats.join("\n")}`;
};
 
// ❌ Bad - dump everything
render: (state) => JSON.stringify(state.memory); // Overwhelming!

4. Handle Memory Gracefully

graceful-memory-handling.ts
handler: async ({ userId }, ctx) => {
  try {
    // Try to load user memory
    const userPrefs = ctx.memory.preferences || {};
 
    // Provide defaults if memory is empty
    const language = userPrefs.language || "en";
    const timezone = userPrefs.timezone || "UTC";
 
    return { language, timezone };
  } catch (error) {
    // Handle memory errors gracefully
    console.error("Memory error:", error);
    return { language: "en", timezone: "UTC" }; // Safe defaults
  }
};

Memory Types Summary

Memory TypePurposeLifetimeExample
Working MemoryCurrent conversationSingle conversation"User just asked about weather"
Context MemoryUser/session dataPersists forever"Alice prefers detailed weather"
Action MemoryAction-specific statePersists forever"Weather API called 47 times today"
Experience MemoryLearning from pastPersists forever"Users like step-by-step cooking help"

Key Takeaways

  • Memory makes agents smart - Without it, every conversation starts from scratch
  • Multiple memory types - Short-term (conversation), long-term (user data), experience (learning)
  • Automatic persistence - Agent saves important information without extra code
  • Experience learning - Agent gets better over time by remembering what works
  • Choose storage wisely - In-memory for development, database for production
  • Keep it organized - Clear memory structures make agents more reliable

Memory transforms your agent from a stateless chatbot into an intelligent assistant that learns, remembers, and gets better with every interaction.