> ## 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 Module

> Documentation for the praisonaiagents.memory module - Multi-tiered memory system with quality scoring

# Memory

Multi-tiered memory system with short-term, long-term, entity, and user-specific memory.

## Quick Start

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# Enable memory with defaults
agent = Agent(instructions="You are a helpful assistant", memory=True)

# Use preset
agent = Agent(instructions="...", memory="sqlite")

# Use URL
agent = Agent(instructions="...", memory="mongodb://localhost:27017")
```

## Usage Forms Table

| Form                  | Example                                         | When to Use                 |
| --------------------- | ----------------------------------------------- | --------------------------- |
| **Bool**              | `memory=True`                                   | Enable with defaults (file) |
| **String preset**     | `memory="sqlite"`                               | Use predefined backend      |
| **URL**               | `memory="mongodb://localhost:27017"`            | Backend-specific connection |
| **Dict**              | `memory={"backend": "chroma", "user_id": "u1"}` | Custom config               |
| **Array + overrides** | `memory=["sqlite", {"user_id": "u1"}]`          | Preset + customization      |
| **Config instance**   | `memory=MemoryConfig(backend="sqlite")`         | Full control                |

## Presets & Options

| Preset        | Backend    | Description                               |
| ------------- | ---------- | ----------------------------------------- |
| `"file"`      | Local file | File-based storage (default)              |
| `"sqlite"`    | SQLite     | Local database                            |
| `"chroma"`    | ChromaDB   | Vector search (aliases `chromadb`, `rag`) |
| `"mem0"`      | Mem0       | External memory service                   |
| `"mongodb"`   | MongoDB    | Document-based                            |
| `"dakera"`    | Dakera     | Self-hosted decay-weighted memory         |
| `"in_memory"` | In-memory  | In-process store (alias `none`)           |

<Warning>
  `"redis"`, `"postgres"`, and `"valkey"` are **not** valid memory backends and raise a `ValueError`. Use `memory=MemoryConfig(db=db(url="redis://..."))` — see [Redis persistence](/docs/features/persistence-redis).
</Warning>

### URL Schemes

| Scheme           | Backend       |
| ---------------- | ------------- |
| `sqlite://`      | SQLite        |
| `mongodb://`     | MongoDB       |
| `mongodb+srv://` | MongoDB Atlas |

<Note>
  `postgresql://` and `redis://` string URLs are no longer accepted by `MemoryConfig` and raise a `ValueError`. Pass them through `db(url=...)` instead.
</Note>

## Precedence Ladder

<Info>
  **Resolution Order**: Instance > Config > Array > Dict > String > Bool > Default

  When you pass `memory=`, the resolver checks in this order:

  1. **Instance** - MemoryManager instance? Use as-is
  2. **Config** - MemoryConfig instance? Use as-is
  3. **Array** - `["preset", {"override": value}]`? Apply overrides
  4. **Dict** - `{"key": value}`? Convert to config
  5. **String** - URL or preset? Parse URL or look up preset
  6. **Bool** - `True`? Use defaults. `False`? Disable
</Info>

## Memory Tiers

| Tier                 | Purpose              | Storage           | Retention |
| -------------------- | -------------------- | ----------------- | --------- |
| **Short-Term (STM)** | Active conversation  | SQLite            | Ephemeral |
| **Long-Term (LTM)**  | Persistent knowledge | SQLite + Vector   | Permanent |
| **Entity Memory**    | Structured entities  | LTM subset        | Permanent |
| **User Memory**      | User preferences     | LTM with user\_id | Permanent |

## Classes

### MemoryClient

| Method                               | Description         |
| ------------------------------------ | ------------------- |
| `store_in_short_memory(memory, ...)` | Store in STM        |
| `store_in_long_memory(memory, ...)`  | Store in LTM        |
| `search_memories(query, ...)`        | Search across tiers |
| `get_short_memories(...)`            | Retrieve STM        |
| `get_long_memories(...)`             | Retrieve LTM        |
| `clear_short_memory(...)`            | Clear STM           |
| `clear_long_memory(...)`             | Clear LTM           |

### Quality Scoring Functions

#### compute\_quality\_score

Calculate overall quality score from individual metrics.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
def compute_quality_score(
    completeness: float,
    relevance: float,
    clarity: float,
    accuracy: float,
    weights: Optional[Dict[str, float]] = None
) -> float
```

#### calculate\_quality\_metrics

Use LLM to evaluate output quality against expectations.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
def calculate_quality_metrics(
    output: str,
    expected_output: str,
    llm=None,
    custom_prompt: Optional[str] = None
) -> Dict[str, float]
```

## Memory Tiers

### 1. Short-Term Memory (STM)

* **Purpose**: Immediate context and active conversation
* **Storage**: SQLite database (`.praison/short_term.db`)
* **Retention**: Ephemeral, cleared between sessions
* **Use Cases**: Current task context, recent interactions

### 2. Long-Term Memory (LTM)

* **Purpose**: Persistent knowledge across sessions
* **Storage**: SQLite + optional vector store
* **Retention**: Permanent with quality filtering
* **Use Cases**: Learned facts, important outcomes

### 3. Entity Memory

* **Purpose**: Structured information about entities
* **Storage**: Subset of LTM with special formatting
* **Format**: `Entity {name}({type}): {desc} | relationships: {relations}`
* **Use Cases**: People, organizations, locations

### 4. User Memory

* **Purpose**: User-specific preferences and history
* **Storage**: LTM with user\_id filtering
* **Isolation**: Strict user separation
* **Use Cases**: Personalization, preferences

## Configuration

### Basic Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
config = {
    "provider": "rag",  # Options: rag, mem0, none
    "use_embedding": True,
    "rag_db_path": ".praison/chroma"
}
```

### Advanced Configuration with Graph Support

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
config = {
    "provider": "mem0",
    "config": {
        "graph_store": {
            "provider": "neo4j",
            "config": {
                "url": "neo4j+s://your-instance.neo4j.io",
                "username": "neo4j",
                "password": "your-password"
            }
        },
        "vector_store": {
            "provider": "chroma",
            "config": {
                "collection_name": "agent_memory"
            }
        },
        "llm": {
            "provider": "openai",
            "config": {
                "model": "gpt-4o-mini"
            }
        }
    }
}
```

### Graph Database Options

#### Neo4j Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
"graph_store": {
    "provider": "neo4j",
    "config": {
        "url": "neo4j+s://...",
        "username": "neo4j",
        "password": "..."
    }
}
```

#### Memgraph Configuration

````python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
"graph_store": {
    "provider": "memgraph",
    "config": {
        "url": "bolt://localhost:7687",
        "username": "memgraph",
        "password": "..."
    }
=======
title: "Memory"
sidebarTitle: "Memory"
description: "Multi-tiered memory system with graph support for intelligent agents"
icon: "brain"
---

## Overview

The Memory module provides a sophisticated multi-tiered memory system that enables agents to maintain context across conversations, store and retrieve information efficiently, and even utilize graph databases for complex relationship mapping.

```mermaid
flowchart TB
    subgraph "Memory Tiers"
        STM[Short-term Memory<br/>Recent Interactions]
        LTM[Long-term Memory<br/>Important Information]
        ETM[Entity Memory<br/>People, Places, Things]
        USM[User Memory<br/>Preferences & History]
    end
    
    subgraph "Storage Backends"
        SQL[SQLite<br/>Local Storage]
        VEC[ChromaDB<br/>Vector Storage]
        MEM[Mem0<br/>Managed Service]
        GRA[Neo4j/Memgraph<br/>Graph Database]
    end
    
    subgraph "Quality Management"
        QS[Quality Scoring<br/>0.0 - 1.0]
        QF[Quality Filtering<br/>Threshold: 0.7]
    end
    
    STM --> SQL
    LTM --> VEC
    ETM --> GRA
    USM --> SQL
    
    STM --> QS
    LTM --> QS
    QS --> QF
    
    style STM fill:#189AB4,color:#fff
    style LTM fill:#2E8B57,color:#fff
    style GRA fill:#8B0000,color:#fff
    style QS fill:#DAA520,color:#fff
````

## Quick Start

<Steps>
  <Step>
    Install with memory support

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install praisonaiagents
    ```
  </Step>

  <Step>
    Basic memory usage

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Memory

    # Initialize memory system
    memory = Memory()

    # Store information
    memory.add(
        text="The user prefers Python over JavaScript",
        memory_type="long"
    )

    # Search memories
    results = memory.search("programming preferences")

    # Build context for agents
    context = memory.build_context_for_task(
        task_description="Help with a Python project",
        max_items=5
    )
    ```
  </Step>

  <Step>
    Advanced graph memory

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Memory

    # Initialize with graph support
    memory = Memory(
        graph_enabled=True,
        graph_uri="bolt://localhost:7687",
        graph_user="neo4j",
        graph_password="password"
    )

    # Store entity relationships
    memory.add(
        text="John works at TechCorp as a Senior Developer",
        memory_type="entity"
    )

    # Query graph relationships
    results = memory.search("Who works at TechCorp?")
    ```
  </Step>
</Steps>

## Configuration

### Basic Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
memory = Memory(
    provider="rag",  # Options: "rag", "mem0", "none"
    use_embedding=True,
    api_key=None,  # For mem0 provider
    memory={"user_id": "default_user"},
    debug=False
)
```

### Advanced Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
memory = Memory(
    # Storage paths
    rag_db_path="custom/path/chroma_db",
    short_db="custom/path/short_term.db",
    long_db="custom/path/long_term.db",
    entity_db="custom/path/entity.db",
    user_db="custom/path/user.db",
    
    # Graph configuration
    graph_enabled=True,
    graph_uri="bolt://localhost:7687",
    graph_user="neo4j",
    graph_password="password",
    
    # Quality settings
    quality_threshold=0.7,
    
    # Debug mode
    debug=True
)
```

## Memory Types

<Cards>
  <Card title="Short-term Memory" icon="clock">
    **Recent interactions and temporary context**

    * Last 10-20 interactions
    * Conversation flow
    * Temporary task state
    * Auto-expires old entries
  </Card>

  <Card title="Long-term Memory" icon="archive">
    **Important persistent information**

    * Key facts and learnings
    * User preferences
    * Historical patterns
    * Quality-filtered storage
  </Card>

  <Card title="Entity Memory" icon="diagram-project">
    **Structured entity relationships**

    * People, organizations, places
    * Relationships between entities
    * Graph-based storage
    * Complex queries
  </Card>

  <Card title="User Memory" icon="user">
    **User-specific information**

    * Personal preferences
    * Interaction history
    * Custom settings
    * Privacy-focused
  </Card>
</Cards>

## API Reference

### Constructor

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
Memory(
    provider: str = "rag",
    use_embedding: bool = True,
    api_key: Optional[str] = None,
    user_id: str = "default_user",
    rag_db_path: str = "memory_chroma_db",
    short_db: str = "short_term_memory.db",
    long_db: str = "long_term_memory.db",
    entity_db: str = "entity_memory.db",
    user_db: str = "user_memory.db",
    graph_enabled: bool = False,
    graph_uri: Optional[str] = None,
    graph_user: Optional[str] = None,
    graph_password: Optional[str] = None,
    quality_threshold: float = 0.7,
    debug: bool = False
)
```

### Core Methods

#### add()

Store information in memory with optional quality scoring.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
add(
    text: str,
    memory_type: str = "short",
    quality_score: Optional[float] = None,
    metadata: Optional[Dict[str, Any]] = None
) -> None
```

**Parameters:**

* `text` - Content to store
* `memory_type` - Type: "short", "long", "entity", or "user"
* `quality_score` - Quality rating (0.0-1.0, auto-calculated if None)
* `metadata` - Additional metadata

#### search()

Search across all memory types for relevant information.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
search(
    query: str,
    memory_type: Optional[str] = None,
    limit: int = 5
) -> List[Dict[str, Any]]
```

**Returns list of:**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
    'text': str,          # Memory content
    'memory_type': str,   # Type of memory
    'timestamp': str,     # Creation time
    'quality_score': float,  # Quality rating
    'metadata': dict      # Additional data
}
```

#### update()

Update an existing memory entry.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
update(
    memory_id: str,
    text: str,
    memory_type: str = "short",
    quality_score: Optional[float] = None
) -> None
```

#### delete()

Delete a specific memory entry.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
delete(
    memory_id: str,
    memory_type: str = "short"
) -> None
```

### Context Building

#### build\_context\_for\_task()

Build formatted context for a specific task.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
build_context_for_task(
    task_description: str,
    max_items: int = 10
) -> str
```

**Example output:**

```
Based on memory:
- User prefers Python for data science projects
- Previous experience with pandas and numpy
- Interested in machine learning applications
```

#### get\_context()

Get all memories formatted as context.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
get_context(
    memory_type: Optional[str] = None,
    limit: int = 10
) -> str
```

### Quality Management

#### calculate\_quality\_score()

Calculate quality score for a memory entry.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
calculate_quality_score(
    text: str,
    memory_type: str = "short"
) -> float
```

**Scoring factors:**

* Information density
* Specificity
* Relevance indicators
* Entity mentions
* Temporal relevance

#### get\_quality\_memories()

Retrieve only high-quality memories.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
get_quality_memories(
    memory_type: str = "long",
    min_quality: float = 0.7,
    limit: int = 10
) -> List[Dict[str, Any]]
```

### Utility Methods

#### get\_memories()

Retrieve raw memories from storage.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
get_memories(
    memory_type: str = "short",
    limit: int = 10
) -> List[Dict[str, Any]]
```

#### clear()

Clear all memories of a specific type.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
clear(memory_type: str = "all") -> None
```

Options: "short", "long", "entity", "user", "all"

#### get\_stats()

Get memory system statistics.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
get_stats() -> Dict[str, Any]
```

**Returns:**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
    'total_memories': int,
    'by_type': {
        'short': int,
        'long': int,
        'entity': int,
        'user': int
    },
    'quality_distribution': dict,
    'storage_info': dict

}
```

## Usage Examples

### Basic Memory Operations

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import MemoryClient

# Initialize memory
memory = MemoryClient(verbose=2)

# Store memories
memory.store_in_short_memory("User asked about pricing")
memory.store_in_long_memory(
    "Company pricing: $99/month for pro plan",
    quality_score=0.9
)

# Search memories
results = memory.search_memories("pricing", k=5)
```

### Quality-Based Storage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import calculate_quality_metrics, compute_quality_score

# Evaluate output quality
metrics = calculate_quality_metrics(
    output="Generated report content...",
    expected_output="Comprehensive analysis with data"
)

# Calculate overall score
score = compute_quality_score(
    completeness=metrics['completeness'],
    relevance=metrics['relevance'],
    clarity=metrics['clarity'],
    accuracy=metrics['accuracy']
)

# Store only high-quality outputs
if score > 0.7:
    memory.store_in_long_memory(output, quality_score=score)
```

### Entity Memory Management

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Store entity information
memory.store_entity_memory(
    name="Acme Corp",
    entity_type="Company",
    desc="Leading provider of AI solutions",
    relations=["Founded by John Doe", "Partnered with TechCo"],
    memory={"user_id": "user123"}
)

# Retrieve entity context
context = memory.build_context_for_task(
    "Tell me about Acme Corp's partnerships"
)
```

### Agent Integration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# Agent with memory
agent = Agent(
    name="Assistant",
    role="Helpful AI assistant",
    memory={
        "provider": "rag",
        "use_embedding": True
    }
)

# Memory is automatically managed during conversations
response = agent.chat("Remember that my favorite color is blue")
```

### Graph-Enhanced Memory

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Configure with Neo4j
memory = MemoryClient({
    "provider": "mem0",
    "config": {
        "graph_store": {
            "provider": "neo4j",
            "config": {...}
        }
    }
})

# Store with relationships
memory.memory.add(
    "John Doe is the CEO of Acme Corp",
    metadata={"entities": ["John Doe", "Acme Corp"]}
)

# Graph-aware search
results = memory.search_memories(
    "Who works at Acme Corp?",
    rerank=True
)
```

## Quality Metrics

### Completeness (0-1)

How thoroughly the content addresses the requirements.

### Relevance (0-1)

How well the content matches the expected output.

### Clarity (0-1)

How clear and well-structured the content is.

### Accuracy (0-1)

Factual correctness of the information.

### Custom Weights

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
weights = {
    "completeness": 0.3,
    "relevance": 0.4,
    "clarity": 0.2,
    "accuracy": 0.1
}
score = compute_quality_score(**metrics, weights=weights)
```

## Best Practices

1. **Use Quality Filtering** - Set appropriate `min_quality` thresholds
2. **Scope Memories** - Use user\_id and agent\_id for proper isolation
3. **Regular Cleanup** - Clear short-term memory between sessions
4. **Graph for Relationships** - Use graph stores for complex entity relationships
5. **Monitor Storage** - Check database sizes periodically
6. **Test Retrieval** - Verify context building produces relevant results
   \=======

### Basic Memory Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Memory

# Create memory system
memory = Memory(memory={"user_id": "user_123"})

# Create agent with memory
agent = Agent(
    name="Assistant",
    role="Personal AI Assistant",
    memory=memory
)

# Conversation that builds memory
agent.chat("I prefer morning meetings")
# Automatically stored in memory

agent.chat("Schedule something for tomorrow")
# Uses memory: "Scheduling morning meeting as you prefer"
```

### Quality-Based Storage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Memory

memory = Memory(quality_threshold=0.8)

# High-quality information
memory.add(
    "User's API key: sk-abc123def456",
    memory_type="long",
    quality_score=0.9
)

# Low-quality information (won't be stored in long-term)
memory.add(
    "User said hello",
    memory_type="long",
    quality_score=0.3
)

# Get only high-quality memories
important = memory.get_quality_memories(min_quality=0.8)
```

### Graph Memory Example

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Memory

# Setup graph memory
memory = Memory(
    graph_enabled=True,
    graph_uri="bolt://localhost:7687",
    graph_user="neo4j",
    graph_password="password"
)

# Store entity relationships
memory.add(
    "Alice manages Bob and Charlie at DataCorp",
    memory_type="entity"
)

memory.add(
    "DataCorp acquired SmallStartup in 2024",
    memory_type="entity"
)

# Query relationships
results = memory.search("Who does Alice manage?")
# Returns information about Bob and Charlie

results = memory.search("DataCorp acquisitions")
# Returns information about SmallStartup acquisition
```

### Multi-Agent Memory Sharing

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Memory, Agent, AgentTeam

# Shared memory system
shared_memory = Memory(config={"provider": "rag"})

# Create agents with shared memory
researcher = Agent(
    name="Researcher",
    role="Research Analyst",
    memory=shared_memory
)

writer = Agent(
    name="Writer",
    role="Content Creator",
    memory=shared_memory
)

# Researcher stores findings
researcher.chat("Found that 73% of users prefer dark mode")

# Writer can access the same memory
response = writer.chat("Write about user preferences")
# Uses the 73% statistic from shared memory
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Memory Type Selection" icon="layer-group">
    **Short-term**: Conversation context, temporary state
    **Long-term**: Facts, preferences, important information
    **Entity**: People, places, organizations, relationships
    **User**: Personal data, settings, history
  </Card>

  <Card title="Quality Management" icon="chart-line">
    * Set appropriate quality thresholds (0.7-0.8 recommended)
    * Manually score critical information higher
    * Periodically review and clean low-quality memories
    * Use quality scores for retrieval filtering
  </Card>

  <Card title="Performance Optimization" icon="rocket">
    * Limit memory searches to necessary types
    * Use appropriate search limits
    * Clear short-term memory periodically
    * Index frequently accessed memories
  </Card>

  <Card title="Privacy & Security" icon="shield">
    * Separate user memories by user\_id
    * Avoid storing sensitive data in plain text
    * Implement access controls for shared memory
    * Regular cleanup of old user data
  </Card>
</CardGroup>

## Provider Comparison

<Table>
  <TableHeader>
    <TableRow>
      <TableHeaderCell>Feature</TableHeaderCell>
      <TableHeaderCell>RAG (Default)</TableHeaderCell>
      <TableHeaderCell>Mem0</TableHeaderCell>
      <TableHeaderCell>None</TableHeaderCell>
    </TableRow>
  </TableHeader>

  <TableBody>
    <TableRow>
      <TableCell>Local Storage</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>❌</TableCell>
      <TableCell>✅</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>Embeddings</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>❌</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>Graph Support</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>❌</TableCell>
      <TableCell>❌</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>Quality Scoring</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>⚠️</TableCell>
      <TableCell>✅</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>API Required</TableCell>
      <TableCell>❌</TableCell>
      <TableCell>✅</TableCell>
      <TableCell>❌</TableCell>
    </TableRow>

    <TableRow>
      <TableCell>Scalability</TableCell>
      <TableCell>Medium</TableCell>
      <TableCell>High</TableCell>
      <TableCell>Low</TableCell>
    </TableRow>
  </TableBody>
</Table>

## Troubleshooting

**Common Issues:**

<Accordion>
  <AccordionItem title="Graph connection failed">
    Check Neo4j/Memgraph is running and credentials are correct
  </AccordionItem>

  <AccordionItem title="Memory search slow">
    Reduce search limit or disable embedding search
  </AccordionItem>

  <AccordionItem title="Quality scores too low">
    Adjust threshold or scoring algorithm
  </AccordionItem>

  <AccordionItem title="Storage full">
    Implement cleanup strategy for old memories
  </AccordionItem>

  <AccordionItem title="Mem0 API errors">
    Verify API key and check rate limits
  </AccordionItem>
</Accordion>

## Advanced Configuration

### Custom Quality Scoring

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Memory

class CustomMemory(Memory):
    def calculate_quality_score(self, text: str, memory_type: str) -> float:
        # Base score
        score = super().calculate_quality_score(text, memory_type)
        
        # Custom adjustments
        if "important" in text.lower():
            score += 0.2
        if len(text) > 200:  # Favor detailed information
            score += 0.1
        if memory_type == "entity":  # Boost entity memories
            score += 0.15
            
        return min(score, 1.0)

# Use custom memory
memory = CustomMemory(quality_threshold=0.75)
```

### Memory Middleware

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Memory
from datetime import datetime

class AuditedMemory(Memory):
    def add(self, text: str, memory_type: str = "short", **kwargs):
        # Add audit metadata
        kwargs['metadata'] = kwargs.get('metadata', {})
        kwargs['metadata']['added_at'] = datetime.now().isoformat()
        kwargs['metadata']['source'] = 'agent_conversation'
        
        # Log addition
        print(f"[AUDIT] Adding {memory_type} memory: {text[:50]}...")
        
        super().add(text, memory_type, **kwargs)

# Use with agents
memory = AuditedMemory()
agent = Agent(name="Audited", memory=memory)
```

## Summary

The Memory module provides a comprehensive solution for agent memory management:

✅ **Multi-tiered Architecture** - Different memory types for different needs\
✅ **Quality Management** - Automatic scoring and filtering\
✅ **Graph Support** - Complex relationship mapping with Neo4j/Memgraph\
✅ **Flexible Storage** - Multiple backend options\
✅ **Context Building** - Automatic context generation for tasks

Perfect for building agents that:

* Maintain conversation context
* Remember user preferences
* Track entity relationships
* Build knowledge over time
