> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Memory System

> Give Agents semantic memory to recall relevant information

Memory gives your Agents the ability to recall relevant information from past interactions. Unlike sessions (which store sequential history), memory enables semantic search - finding information by meaning, not just recency.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Agent[Agent] --> Mem[Memory]
    Mem --> Recall([Recall])

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff

    class Agent,Mem agent
    class Recall tool
    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff

```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import { Agent, Memory } from 'praisonai';

    const memory = new Memory();

    const agent = new Agent({
      name: 'Memory Agent',
      instructions: 'You remember important information from conversations.',
      memory  // Agent uses semantic memory
    });

    // Agent learns information
    await agent.chat('My favorite color is blue and I work as a software engineer');
    await agent.chat('I prefer morning meetings and use TypeScript daily');

    // Later, Agent can recall relevant info
    await agent.chat('What do you know about my work?');
    // Agent recalls: software engineer, TypeScript, morning meetings
    ```
  </Step>

  <Step title="With Configuration">
    ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    const memory = new Memory({ maxEntries: 1000, maxTokens: 50000 });

    const agent = new Agent({
      name: 'Memory Agent',
      instructions: 'You remember important information from conversations.',
      memory,
      verbose: true,
    });
    ```
  </Step>
</Steps>

## Agent with Memory Search Tool

Give your Agent explicit control over memory:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Memory, createTool } from 'praisonai';

const memory = new Memory();

// Tool to save to memory
const rememberTool = createTool({
  name: 'remember',
  description: 'Save important information to memory for later recall',
  parameters: {
    type: 'object',
    properties: {
      information: { type: 'string', description: 'Information to remember' },
      category: { type: 'string', description: 'Category (preferences, facts, tasks)' }
    },
    required: ['information']
  },
  execute: async ({ information, category = 'general' }) => {
    await memory.add(information, 'memory', { category });
    return `Remembered: ${information}`;
  }
});

// Tool to search memory
const recallTool = createTool({
  name: 'recall',
  description: 'Search memory for relevant information',
  parameters: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'What to search for' }
    },
    required: ['query']
  },
  execute: async ({ query }) => {
    const results = await memory.search(query);
    if (results.length === 0) return 'No relevant memories found';
    return results.map(r => r.entry.content).join('\n');
  }
});

const agent = new Agent({
  name: 'Learning Agent',
  instructions: `You can remember and recall information.
Use 'remember' to save important facts the user tells you.
Use 'recall' to find relevant information when answering questions.`,
  tools: [rememberTool, recallTool]
});

await agent.chat('Remember that I am allergic to peanuts');
await agent.chat('What food restrictions do I have?'); // Agent recalls allergy
```

## Multi-Agent Shared Memory

Agents can share a memory pool:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Memory, Agents } from 'praisonai';

const sharedMemory = new Memory();

// Agent 1: Learns from documents
const learnerAgent = new Agent({
  name: 'Learner',
  instructions: 'Extract and remember key facts from documents.',
  memory: sharedMemory
});

// Agent 2: Answers questions using shared memory
const answererAgent = new Agent({
  name: 'Answerer',
  instructions: 'Answer questions using information from memory.',
  memory: sharedMemory
});

// Learner processes documents
await learnerAgent.chat('Learn: The company was founded in 2020. CEO is Jane Smith. HQ in Austin.');

// Answerer can access learned information
await answererAgent.chat('Who is the CEO?'); // Recalls: Jane Smith
await answererAgent.chat('Where is the headquarters?'); // Recalls: Austin
```

## Agent with Long-Term Memory

Persist memory across sessions:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Memory, createUpstashRedis } from 'praisonai';

const redis = createUpstashRedis({ url, token });

// Memory with persistence
class PersistentMemory extends Memory {
  private redis: any;
  private userId: string;
  
  constructor(redis: any, userId: string) {
    super();
    this.redis = redis;
    this.userId = userId;
  }
  
  async add(content: string, role: string, metadata?: any) {
    await super.add(content, role, metadata);
    // Persist to Redis
    const memories = this.toJSON();
    await this.redis.set(`memory:${this.userId}`, memories);
  }
  
  async load() {
    const data = await this.redis.get(`memory:${this.userId}`);
    if (data) this.fromJSON(data);
  }
}

const memory = new PersistentMemory(redis, 'user-123');
await memory.load(); // Load previous memories

const agent = new Agent({
  name: 'Long-Term Memory Agent',
  instructions: 'You remember everything about the user across all sessions.',
  memory
});

// Agent remembers from previous sessions
await agent.chat('What do you remember about me?');
```

## Agent Context Building

Build context from memory for Agent prompts:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Memory } from 'praisonai';

const memory = new Memory();

// Add various information
await memory.add('User prefers dark mode', 'system');
await memory.add('User is learning React', 'user');
await memory.add('User works at TechCorp', 'user');
await memory.add('User timezone is PST', 'system');

const agent = new Agent({
  name: 'Context-Aware Agent',
  instructions: 'Personalize responses based on user context.'
});

async function contextualChat(message: string) {
  // Search memory for relevant context
  const relevantMemories = await memory.search(message);
  
  // Build context string
  const context = memory.buildContext({
    entries: relevantMemories.slice(0, 5),
    format: 'bullet'
  });
  
  // Agent responds with context
  return await agent.chat(`
User Context:
${context}

User Message: ${message}
  `);
}

await contextualChat('Help me with a coding problem');
// Agent knows: user is learning React, works at TechCorp
```

## Agent Memory with Embeddings

Semantic search with vector embeddings:

<Note>
  The sync `embed(...)` / `embeddings(...)` functions now throw instead of returning noise — see [Sync vs. Async](/docs/js/embeddings#sync-vs-async) for the async replacement.
</Note>

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Memory } from 'praisonai';

const memory = new Memory({
  embeddingProvider: {
    embed: async (text) => {
      // Use OpenAI embeddings
      const response = await openai.embeddings.create({
        model: 'text-embedding-3-small',
        input: text
      });
      return response.data[0].embedding;
    },
    embedBatch: async (texts) => {
      const response = await openai.embeddings.create({
        model: 'text-embedding-3-small',
        input: texts
      });
      return response.data.map(d => d.embedding);
    }
  }
});

const agent = new Agent({
  name: 'Semantic Memory Agent',
  instructions: 'You have semantic memory - you can find information by meaning.',
  memory
});

// Add diverse information
await memory.add('The quarterly revenue was $5.2 million', 'data');
await memory.add('Customer satisfaction score improved to 4.8/5', 'data');
await memory.add('We hired 15 new engineers this quarter', 'data');

// Semantic search finds relevant info
await agent.chat('How is the company doing financially?');
// Finds: quarterly revenue $5.2 million (by semantic similarity)
```

## ChromaMemory embedder default

ChromaMemory now embeds with the real async embedder by default — you get semantic similarity out of the box, no custom `embedder` needed.

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, ChromaMemory } from 'praisonai';

const agent = new Agent({
  name: 'Memory Agent',
  instructions: 'You remember what the user tells you.',
  memory: new ChromaMemory(),   // real embeddings by default
});

await agent.chat('I prefer TypeScript and morning meetings.');
await agent.chat('What do you know about how I work?');
```

<Note>
  Older versions of the SDK used a placeholder embedder that returned `Math.random()` vectors, so users who did not pass a custom `embedder` got meaningless similarity results. [PraisonAI PR #4925](https://github.com/MervinPraison/PraisonAI/pull/4925) fixes this — upgrading gives real semantic matches silently, with no code change.
</Note>

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant ChromaMemory
    participant Embedder as praisonai/llm/embeddings

    User->>Agent: chat("I prefer TS")
    Agent->>ChromaMemory: store(text)
    ChromaMemory->>Embedder: await embed(text)
    Embedder-->>ChromaMemory: real vector
    ChromaMemory-->>Agent: stored
    User->>Agent: chat("what do you know?")
    Agent->>ChromaMemory: search(query)
    ChromaMemory->>Embedder: await embed(query)
    Embedder-->>ChromaMemory: real vector
    ChromaMemory-->>Agent: top-k semantic matches
    Agent-->>User: personalized reply
```

Override the default with your own `embedder` — the type is `MaybePromise<number[]>`, so sync and async both work:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
new ChromaMemory({
  embedder: async (text, model) => {
    const { embed } = await import('praisonai/llm/embeddings');
    const { embedding } = await embed(text, { model });
    return embedding;
  },
});
```

## Memory Configuration

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
const memory = new Memory({
  maxEntries: 1000,        // Maximum memories to store
  maxTokens: 50000,        // Token limit for context
  embeddingProvider: {...} // Optional: for semantic search
});
```

## Related

<CardGroup cols={2}>
  <Card title="Sessions" icon="lock" href="/docs/js/sessions">
    Sequential conversation history
  </Card>

  <Card title="Knowledge Base" icon="book" href="/docs/js/knowledge-base">
    Document-based Agent knowledge
  </Card>

  <Card title="Vector Stores" icon="database" href="/docs/js/vector-stores">
    Scalable memory storage
  </Card>
</CardGroup>
