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

> Auto-memory, history injection, session persistence, and learning

# Memory Features

PraisonAI agents support several memory features that make conversations smarter over time. Each feature is **opt-in** — disabled by default for zero overhead.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    A["🧠 Agent"] --> B{"MemoryConfig"}
    B --> C["auto_save"]
    B --> D["history"]
    B --> E["auto_memory"]
    B --> F["learn"]
    style A fill:#8B0000,color:#fff
    style B fill:#189AB4,color:#fff
    style C fill:#189AB4,color:#fff
    style D fill:#189AB4,color:#fff
    style E fill:#189AB4,color:#fff
    style F fill:#189AB4,color:#fff
```

***

## Quick Comparison

| Feature          | What it does                             | Config              |
| ---------------- | ---------------------------------------- | ------------------- |
| **auto\_save**   | Saves full conversation to disk          | `auto_save="chat1"` |
| **history**      | Injects past sessions into context       | `history=True`      |
| **auto\_memory** | Extracts facts/preferences automatically | `auto_memory=True`  |
| **learn**        | Captures patterns and insights           | `learn=True`        |

***

## Auto-Save Sessions

Automatically saves the full conversation history to disk after each `start()` / `run()` call.

<Tabs>
  <Tab title="Simple">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig

    agent = Agent(
        name="assistant",
        instructions="Be helpful",
        memory=MemoryConfig(auto_save="my_chat")
    )

    agent.start("Hello!")
    # Session saved to ~/.praisonai/memory/sessions/my_chat.json
    ```
  </Tab>

  <Tab title="Preset">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    # Use the "session" preset (auto_save + history)
    agent = Agent(
        name="assistant",
        instructions="Be helpful",
        memory="session"
    )
    ```
  </Tab>
</Tabs>

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant U as 👤 User
    participant A as 🧠 Agent
    participant M as 💾 FileMemory

    U->>A: "Hello!"
    A->>U: "Hi there!"
    A->>M: auto_save("my_chat", history)
    Note over M: Saved to disk
    U->>A: "Remember my name is John"
    A->>U: "Got it, John!"
    A->>M: auto_save("my_chat", history)
```

***

## History Injection

Automatically loads past session history into context so the agent remembers previous conversations.

<Tabs>
  <Tab title="Basic">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig

    agent = Agent(
        name="assistant",
        instructions="Be helpful",
        memory=MemoryConfig(history=True)
    )

    # First run
    agent.start("My name is Alice")

    # Later run — agent remembers!
    agent.start("What's my name?")
    # → "Your name is Alice"
    ```
  </Tab>

  <Tab title="With Limit">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig

    agent = Agent(
        name="assistant",
        instructions="Be helpful",
        memory=MemoryConfig(
            history=True,
            history_limit=20,  # Load last 20 messages
            session_id="user_123"  # Explicit session ID
        )
    )
    ```
  </Tab>

  <Tab title="Preset">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    # "history" preset — history=True, limit=10
    agent = Agent(name="assistant", memory="history")

    # "chat" preset — history=True, limit=20
    agent = Agent(name="assistant", memory="chat")
    ```
  </Tab>
</Tabs>

<Info>
  When `history=True`, a session ID is auto-generated **per project** — it combines the workspace (git repo root or the current directory) with the agent name. Two `Agent(name="assistant")` calls in different projects get separate history files and never mix.

  Set `session_id="..."` for explicit control over which session to resume, or opt back into name-only global sessions by exporting `PRAISONAI_GLOBAL_SESSIONS=true`.
</Info>

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant S as 📂 Session Store
    participant A as 🧠 Agent
    participant U as 👤 User

    Note over A: chat() called
    A->>S: Load history (session_id)
    S->>A: Past messages
    Note over A: Inject into context
    U->>A: "What's my name?"
    A->>U: "Your name is Alice"
    A->>S: Save new messages
```

### Where sessions live

Every auto-generated session is scoped to your **workspace**, so the same agent name in a different project starts fresh instead of leaking history.

| Signal               | Used as workspace identity                                   |
| -------------------- | ------------------------------------------------------------ |
| Inside a git repo    | The repo's root-commit SHA (stable across clones and paths). |
| Not in a git repo    | The absolute path of your current directory.                 |
| Neither works (rare) | The literal string `global`.                                 |

The final on-disk id is:

```
history_<sha256("<workspace_id>:<agent_name>")[:8]>.json
```

Stored under `~/.praisonai/sessions/` (or wherever `PRAISONAI_HOME` points).

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    Start[Agent memory=history, no session_id]
    Env{PRAISONAI_GLOBAL_SESSIONS=true?}
    Git{Inside a git repo?}
    Cwd{cwd available?}
    Global[workspace = 'global']
    GitId[workspace = 'git:root-commit']
    DirId[workspace = 'dir:realpath']
    Hash[history_ + sha256 workspace:name]

    Start --> Env
    Env -->|Yes| Global --> Hash
    Env -->|No| Git
    Git -->|Yes| GitId --> Hash
    Git -->|No| Cwd
    Cwd -->|Yes| DirId --> Hash
    Cwd -->|No| Global

    classDef config fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef result fill:#10B981,stroke:#7C90A0,color:#fff

    class Start,Env,Git,Cwd config
    class Global,GitId,DirId process
    class Hash result
```

Read the resolved identity from Python:

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

print(workspace_id())
# → "git:8f5c1e…" or "dir:/Users/me/projects/my-app" or "global"
```

<AccordionGroup>
  <Accordion title="Opt out with PRAISONAI_GLOBAL_SESSIONS">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    export PRAISONAI_GLOBAL_SESSIONS=true
    ```

    Reverts to the pre-workspace behaviour: the id becomes `history_<sha256("global:<name>")[:8]>` and same-named agents in any project share one history file. Accepted values (case-insensitive): `1`, `true`, `yes`.
  </Accordion>

  <Accordion title="Upgrading from name-only sessions">
    Existing `history_<name-only>.json` files are **not** adopted automatically when running in workspace scope — otherwise Project A's history would leak into Project B.

    * To keep using an old file everywhere, set `PRAISONAI_GLOBAL_SESSIONS=true`.
    * To keep it in one specific project, rename it to the new workspace-scoped id (or set `session_id="..."` explicitly).
    * Otherwise, agents start fresh in each new workspace.
  </Accordion>

  <Accordion title="Explicit session_id still wins">
    Passing `session_id="..."` is unchanged — it always overrides the auto id and stays global, so use it for deliberate cross-project continuity.
  </Accordion>
</AccordionGroup>

***

## Auto-Memory Extraction

Automatically extracts memorable facts (names, preferences, roles) from conversations and stores them in long-term memory.

<Tabs>
  <Tab title="Enable">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig

    agent = Agent(
        name="assistant",
        instructions="Be helpful",
        memory=MemoryConfig(auto_memory=True)
    )

    agent.start("My name is John and I prefer Python")
    # Auto-extracted: name=John, preference=Python
    ```
  </Tab>

  <Tab title="How It Works">
    ```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    sequenceDiagram
        participant U as 👤 User
        participant A as 🧠 Agent
        participant AM as 🔍 AutoMemory
        participant FM as 💾 FileMemory

        U->>A: "I'm John, I use Python"
        A->>U: "Nice to meet you!"
        A->>AM: process_interaction()
        AM->>AM: Extract facts
        AM->>FM: store name="John"
        AM->>FM: store preference="Python"
        Note over FM: Persisted to disk
    ```
  </Tab>
</Tabs>

<Tip>
  Auto-memory uses lightweight regex-based extraction — no LLM calls needed.
  It only processes messages that contain personal information keywords.
</Tip>

***

## Manual Memory Storage

You can also store memories manually using the `store_memory()` method.

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

agent = Agent(name="assistant", memory=True)

# Store facts manually
agent.store_memory("User prefers dark mode", "long_term")
agent.store_memory("Current task: build a dashboard", "short_term")

# Context is auto-injected into system prompt
response = agent.start("What should I work on?")
```

***

## Memory Presets

Use string shortcuts instead of `MemoryConfig` for common configurations.

| Preset      | Equivalent Config                              |
| ----------- | ---------------------------------------------- |
| `"file"`    | `MemoryConfig(backend="file")`                 |
| `"sqlite"`  | `MemoryConfig(backend="sqlite")`               |
| `"redis"`   | `MemoryConfig(backend="redis")`                |
| `"history"` | `MemoryConfig(history=True, history_limit=10)` |
| `"session"` | `MemoryConfig(history=True, history_limit=10)` |
| `"chat"`    | `MemoryConfig(history=True, history_limit=20)` |
| `"learn"`   | `MemoryConfig(learn=True)`                     |

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

# These are equivalent:
agent1 = Agent(name="a", memory="history")
agent2 = Agent(name="a", memory=MemoryConfig(history=True))
```

***

## Custom Memory Backend

Implement the `AgentMemoryProtocol` to create your own memory backend.

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

class MyRedisMemory:
    """Custom memory backend."""
    
    def get_context(self, query=None):
        # Return stored context for system prompt
        return "User prefers Python"
    
    def save_session(self, name, conversation_history=None, metadata=None):
        # Persist session to your backend
        pass

agent = Agent(
    name="assistant",
    memory=MyRedisMemory()  # Pass custom instance
)
```

<Info>
  Any object with `get_context()` and `save_session()` methods works as a memory backend.
  No inheritance required — PraisonAI uses duck typing via `AgentMemoryProtocol`.
</Info>

***

## Architecture

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TD
    A["Agent"] --> B{"MemoryConfig"}
    B -->|"backend=file"| C["FileMemory"]
    B -->|"backend=sqlite"| D["Memory (SQLite)"]
    B -->|"auto_memory=True"| E["AutoMemory"]
    B -->|"history=True"| F["Session Store"]
    
    C --> G["~/.praisonai/memory/"]
    D --> H["SQLite DB"]
    E --> C
    F --> I["JSON Sessions"]
    
    style A fill:#8B0000,color:#fff
    style B fill:#189AB4,color:#fff
    style C fill:#189AB4,color:#fff
    style D fill:#189AB4,color:#fff
    style E fill:#189AB4,color:#fff
    style F fill:#189AB4,color:#fff
```

`FileMemory` persists to `~/.praisonai/memory/`. *Writes are atomic — see [Storage → Durability](/docs/memory/storage#durability).*

<CardGroup cols={2}>
  <Card title="Session Persistence" icon="clock-rotate-left" href="/docs/memory/session-resume">
    Resume conversations across restarts
  </Card>

  <Card title="Storage Backends" icon="database" href="/docs/memory/storage">
    File, SQLite, Redis, PostgreSQL, MongoDB
  </Card>

  <Card title="Advanced Memory" icon="brain" href="/docs/memory/advanced">
    Long-term, short-term, entity memory
  </Card>

  <Card title="Graph Memory" icon="diagram-project" href="/docs/memory/graph">
    Relationship-aware memory
  </Card>
</CardGroup>
