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

# Memory

> Enable your agents to remember user preferences and past interactions across conversations.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

**Memory** lets AI agents retain information about a user across conversations and use it to personalize future interactions.

Without memory, agents start fresh with every conversation:

* **Lost context**: agents lose context, requiring users to repeat information
* **Repetitive interactions**: agents ask the same questions in every session
* **Missed opportunities**: agents can't provide personalized recommendations based on past behavior
* **Poor user experience**: the experience may feel impersonal

## How memory works

A user interacts with your agent.
Memory then operates in these stages:

```mermaid theme={"system"}
sequenceDiagram
    participant User
    participant Agent
    participant Memory

    Note over User,Memory: Conversation 1
    User->>Agent: "I'm vegetarian"
    Agent->>Memory: Save: User is vegetarian
    Agent->>User: "I'll remember that"

    Note over User,Memory: Conversation 2 (next day)
    Agent->>Memory: Load memories for user
    Memory->>Agent: User is vegetarian
    User->>Agent: "Recommend restaurants"
    Agent->>User: "Here are vegetarian options..."
```

* **Retrieval** (automatic). The agent loads memories for context in two modes: preload fetches recent memories at conversation start, preflight fetches query-relevant memories before each response.
* **Tools** (optional). During a conversation, agents can use the following memory tools:
  * `algolia_memorize`: saves semantic memories (facts, preferences)
  * `algolia_ponder`: saves episodic memories (experiences, observations)
  * `algolia_memory_search`: searches existing memories

For example,
a user mentions "I'm vegetarian" in one conversation.
In the next conversation, the user asks for restaurant recommendations.
The agent recalls this preference and suggests vegetarian options.

## Memory types

Agent Studio supports two types of memory, inspired by human cognitive architecture:
semantic and episodic.

### Semantic memory

Stores timeless facts, preferences, and general knowledge about the user.
For example:

* "User is allergic to peanuts"
* "User prefers dark mode in apps"
* "User lives in Madrid and speaks Spanish and English"
* "User's job title is Software Engineer"

**Use cases:**

* User profile information
* Preferences and settings
* Dietary restrictions
* Accessibility needs
* Communication style

<Accordion title="Semantic memory structure">
  ```json JSON icon=braces theme={"system"}
  {
    "text": "User prefers organic vegetables and shops at farmer's markets weekly",
    "rawExtract": "I love buying organic vegetables at the farmer's market every Saturday",
    "keywords": ["organic", "vegetables", "farmer's market", "weekly", "shopping"],
    "topics": ["food", "preferences", "shopping"],
    "recallTriggers": ["vegetables", "shopping habits", "organic food"],
    "memoryType": "semantic"
  }
  ```

  Semantic memories are self-contained facts that remain useful across conversations.
</Accordion>

### Episodic memory

Captures the agent's reasoning chain from conversations.
This includes what it observed, thought, did, and learned.
Use episodic memory to extract meta-learnings for process improvement and analysis.

Use episodic memory to understand the agent's reasoning process.
Agent Studio structures this information.
It uses the OTAR pattern:

* **Observation**: what happened (user input, context, problem)
* **Thoughts**: why the agent chose this approach (reasoning, constraints)
* **Action**: what the agent did (tool calls, responses, workflow)
* **Result**: what happened and what the agent learned

**Use cases:**

* Analyze agent performance across user segments
* Identify successful problem-solving patterns
* Review conversations to improve prompts and instructions
* Answer questions like "How does prompt A perform for premium customers asking about returns?"

<Accordion title="Episodic memory structure">
  ```json JSON icon=braces theme={"system"}
  {
    "text": "Experience: Resolved account lockout via password reset",
    "episode": {
      "observation": "User unable to log in despite correct password. Error: 'invalid credentials'. User tried 3 times.",
      "thoughts": "Account lockout likely triggered by security measure after multiple failed attempts. Password reset would unlock account, not just retry.",
      "action": "search_kb(query:'account locked') → found lockout policy → Explained 3-attempt limit → Sent password reset link → User confirmed receipt",
      "result": "User successfully logged in with new password. Learning: account locks after 3 failed attempts always require password reset."
    },
    "keywords": ["login", "account lock", "password reset", "security"],
    "topics": ["technical"],
    "memoryType": "episodic"
  }
  ```

  OTAR captures reasoning chains to inform similar future situations.
</Accordion>

## Enable memory

To enable memory, you must:

* Enable the feature on your agent
* Verify data retention
* Set up user authentication

<Steps>
  <Step title="Enable on your agent">
    <Tabs>
      <Tab title="From the dashboard">
        From the [Agent Studio agent edit view](https://dashboard.algolia.com/generativeAi/agent-studio/agents):

        1. Open your agent's settings
        2. Go to the **Customizations** section
        3. Find the **Memory** toggle
        4. Click **Configure** to check prerequisites
        5. Enable memory once you meet the prerequisites
        6. Save changes

        <Note>
          The dashboard validates prerequisites automatically.
          It also guides you through any missing configuration.
        </Note>
      </Tab>

      <Tab title="With the API">
        Enable memory when creating or updating an agent:

        ```json JSON icon=braces theme={"system"}
        {
          "name": "My Agent",
          "config": {
            "memory": {
              "enabled": true,
              "toolsEnabled": true,
              "preload": {
                "limit": 10,
                "type": "semantic"
              },
              "preflight": {
                "limit": 5,
                "conversationWindow": 3
              }
            }
          }
        }
        ```

        * `enabled`: activates memory retrieval
        * `toolsEnabled`: gives the agent access to memory tools
        * `preload.limit`: number of recent memories to load at conversation start
        * `preload.type`: `"semantic"`, `"episodic"`, or `"all"`
        * `preflight.limit`: maximum memories to retrieve per <SearchQuery /> (semantic search)
        * `preflight.conversationWindow`: recent messages to use as search context

        The `memory` configuration is nested inside `config`.
        It isn't a top-level field.

        For more information, see the [Agent Studio API reference](/doc/rest-api/agent-studio).
      </Tab>
    </Tabs>
  </Step>

  <Step title="Verify data retention">
    Memory learns from conversation history.
    To use it, you must store conversations (set the retention period to more than 0 days).

    From the Algolia dashboard, go to [Agent Studio > Settings](https://dashboard.algolia.com/apps/APP_ID/generativeAi/agent-studio/settings/):

    1. Check the **Retention period** is set to `30`, `60`, or `90` days. If you set it to `0`, Algolia doesn't store conversation history. As a result, memory can't extract information from past conversations.

    <Note>
      Retention applies to all agents in your Algolia application.
      Supported values are `0`, `30`, `60`, and `90` days.

      * **Application-wide setting**: retention applies to all agents in your Algolia application, not individual agents.
    </Note>

    You need this because:

    * Memory extracts information from past conversations
      A longer retention period helps memory.
      It gives memory more conversation history to draw on.
      It can then extract and combine more information from that history.
    * Longer retention enables better memory extraction and consolidation

    <Tip>
      A 30-day retention period balances memory quality, privacy, and compliance.
    </Tip>
  </Step>

  <Step title="Set up user authentication">
    Memory requires user authentication.
    This identifies which user's memories to load and save.
    Memory keeps stored information separate for each user.

    For complete setup instructions, see [User authentication](/doc/guides/algolia-ai/agent-studio/how-to/user-authentication). This guide covers:

    * Getting your secret key from the dashboard
    * Generating JWTs (JSON Web Tokens) on your backend
    * Security guidance and token management

    <Note>
      **The same secure JWTs work for both memory and conversations.**
      You might already have JWT authentication set up for conversations.
      If so, reuse that setup.
    </Note>

    Set this up first.
    Then include the `X-Algolia-Secure-User-Token` header in your completion requests.
    This enables user-scoped memory:

    ```js JavaScript theme={"system"}
    const appID = "ALGOLIA_APPLICATION_ID";
    const agentId = "AGENT_ID";
    const apiKey = "ALGOLIA_SEARCH_API_KEY";

    const response = await fetch(
      `https://${appID}.algolia.net/agent-studio/1/agents/${agentId}/completions`,
      {
        method: 'POST',
        headers: {
          'X-Algolia-Application-Id': appID,
          'X-Algolia-API-Key': apiKey,
          'X-Algolia-Secure-User-Token': userToken  // Enables user-scoped memory
        },
        body: JSON.stringify({
          messages: [{ role: 'user', content: 'Hello' }]
        })
      }
    );
    ```
  </Step>
</Steps>

## Memory tools

Set `toolsEnabled` to `true` to give your agent access to three memory tools.
Each tool has default activation conditions that you can customize in the agent instructions

### `algolia_memorize`

Saves semantic memories (facts and preferences) during conversation.

**Default triggers** (built into tool prompt):

* User explicitly says "remember X"
* Agent detects a stable preference or fact (for example, dietary restrictions, account type)
* User provides information useful for future interactions

For example,
a user might say "I'm allergic to shellfish."
The agent then calls `algolia_memorize`.
This saves the fact for later use.

### `algolia_ponder`

Saves episodic memories (the agent's reasoning chain) during conversation.

**Default triggers** (built into tool prompt):

* User says "remember this conversation" or "learn from this interaction"
* After solving a problem worth learning from
* After a successful workflow that could help similar future cases

For example,
after resolving a support ticket, the agent calls `algolia_ponder`.
It records what it observed.
It also notes how it reasoned and what it did.
It also records what it learned (OTAR pattern).

### `algolia_memory_search`

Searches existing memories during conversation using Algolia Search.

**Default triggers** (built into tool prompt):

* Before claiming "I don't know" about the user
* Before answering questions about user preferences or history
* When user asks "what did I say about X?"
* When context from previous sessions would improve the response

For example,
a user might ask "What restaurants would I like?"
The agent then calls `algolia_memory_search`.
This finds dietary preferences before the agent recommends anything.

### Customizing tool behavior

The default triggers work for most cases.
You can override them in your agent's instructions:

```text theme={"system"}
# Memory guidelines
- Always ponder after resolving support tickets
- Memorize product preferences when users browse categories
- Never memorize payment information
```

This lets you control what the agent remembers and when.

## Use cases

<Accordion title="Personalize user experiences">
  **Problem**: generic responses don't account for individual user preferences and context.

  **Solution**: memory enables agents to tailor responses.
  Agents base these responses on what they know about each user.

  For example,
  an ecommerce agent remembers a user's size preferences and favorite brands.
  It also remembers past purchases.
  Then it provides relevant recommendations without asking repetitive questions.
</Accordion>

<Accordion title="Reduce repetitive questions">
  **Problem**: users get frustrated repeating the same information in every conversation.

  **Solution**: agents recall information shared earlier, eliminating redundant questions.

  For example,
  a support agent remembers a user's account type and previous issues.
  It also remembers the preferred contact method.
  It then jumps straight to solving the current problem.
</Accordion>

<Accordion title="Improve agent performance through analysis">
  **Problem**: you can't see how your agent reasons through problems.
  You also can't identify what approaches work best.

  **Solution**: episodic memory captures the agent's reasoning chain (OTAR) for each conversation.
  This enables analysis across user segments and scenarios.

  For example, you can export episodic memories.
  These come from users who mentioned "returns."
  You might focus especially on those with premium accounts.
  Then, analyze how the agent handled those conversations:

  * Did it resolve return requests effectively?
  * Are there patterns in failed resolutions?
</Accordion>

<Accordion title="Enable continuous conversations">
  **Problem**: conversations reset with every new session, breaking continuity.

  **Solution**: memory retains user context between sessions.
  It does this even long after the initial conversation.

  For example,
  a user was considering a laptop last week.
  The shopping agent recalls this.
  It then proactively asks if they're still interested.
  It also asks if they need more information.
</Accordion>

## How memory extraction works

When the agent calls a memory tool, Agent Studio doesn't store the raw input.
It runs the information through a quality filter, extracts the memory, and generates metadata before storing it.

```mermaid theme={"system"}
flowchart LR
    A[Agent calls tool] --> B{Quality filter}
    B -->|Passes| C[Extract memory]
    B -->|Fails| D[Discard]
    C --> E[Generate metadata]
    E --> F[Store memory]
```

Quality filters evaluate whether information is useful enough to store.

* **Utility**: would this fact improve future responses?
* **Specificity**: is it concrete and factual (not mood or chitchat)?
* **Effect on behavior**: can you think of a query where it changes behavior?

What gets extracted:

* Factual statements about user preferences
* Important events and interactions
* Skills, knowledge, and relationships
* Patterns inferred from past experiences

What gets filtered out:

* Greetings and pleasantries ("Hello", "I appreciate it")
* Generic traits without specifics ("User is friendly")
* Temporary moods or states
* Duplicate information already stored

## Memory lifecycle

Memory retrieval happens automatically before the agent generates a response.
You can configure two retrieval modes:
**preload** (recent memories) and **preflight** (query-relevant memories).

### Retrieval modes compared

| Feature       | Preload                         | Preflight                   | Tools                    |
| ------------- | ------------------------------- | --------------------------- | ------------------------ |
| Timing        | Conversation start              | Before each response        | During response          |
| Search method | Most recent N                   | Query-based semantic search | Agent-initiated          |
| Extra latency | None                            | None                        | +1 roundtrip             |
| Best for      | Always-on context, few memories | Large memory sets (100+)    | Dynamic, explicit recall |

You can enable both modes together.
Preload provides baseline context, and preflight adds query-specific memories.

### Recent memories (preload)

Preload retrieves up to the configured number of recent memories when a conversation starts.
It does this no matter what the user asks.

1. **Identify user**: extract user ID from the JWT token
2. **Retrieve memories**: fetch up to N recent memories (configurable limit)
3. **Filter by type**: semantic, episodic, or both
4. **Include in context**: the agent adds memories to its initial prompt

**Configuration example:**

```json JSON icon=braces theme={"system"}
{
  "memory": {
    "enabled": true,
    "preload": {
      "limit": 10,
      "type": "semantic"
    }
  }
}
```

**When to use preload:**

* Small memory sets where all memories fit in context
* Always-on personalization (user preferences should always be available)
* Predictable use cases where recent memories are likely relevant

### Query-based retrieval (preflight)

Preflight searches memories based on what the user is asking.
It doesn't rely on recency alone.
It runs before the agent responds.
It adds memories retrieved for the current query to the agent's context.

```mermaid theme={"system"}
sequenceDiagram
    participant User
    participant Agent
    participant Memory

    User->>Agent: "What restaurants would I like?"
    Agent->>Memory: Preflight search: restaurants, food preferences
    Memory->>Agent: "User is vegetarian", "User likes Thai food"
    Agent->>User: "Based on your preferences, here are vegetarian Thai restaurants..."
```

**Configuration example:**

```json JSON icon=braces theme={"system"}
{
  "memory": {
    "enabled": true,
    "preflight": {
      "limit": 5,
      "conversationWindow": 3
    }
  }
}
```

* `limit`: maximum memories to retrieve per query
* `conversationWindow`: number of recent messages to analyze for search context

**When to use preflight:**

* Large memory sets (100+ memories) where loading all recent memories is less useful
* Diverse memory content where only some memories apply to each query
* When you want to maximize relevant context without wasting tokens

### During conversation (tools)

Agents can dynamically save and search memories during the conversation.
They do this using memory tools.

For example,
a user might report an error.
It could be similar to one resolved before.
The agent then calls `algolia_memory_search` to find past resolutions with matching symptoms.

## Common integration issues

<Accordion title="Memory not enabled - prerequisites not met">
  **Symptoms**: can't enable memory toggle in dashboard.

  If you can't enable the memory toggle in the dashboard,
  check the following:

  1. Verify data retention is greater than 0 days
  2. Ensure you have `settingsRanking` permission to modify retention settings

  **Solution**: follow the configuration modal's guidance to set up missing prerequisites.
</Accordion>

<Accordion title="Agent doesn't remember information">
  **Symptoms**: the agent doesn't recall previous information.
  This happens even when memory is enabled.

  **Possible causes**:

  * **No JWT token passed**: conversations must include `X-Algolia-Secure-User-Token` header
  * **Memory tools not enabled**: set `toolsEnabled: true` in the agent configuration
  * **Preload limit too low**: increase the number of memories loaded at conversation start
  * **Wrong memory type**: if you set the preload type to semantic, episodic memories won't load

  **Solution**: verify JWT authentication is working, and ensure memory tools are enabled.
  Then, adjust your preload configuration.
</Accordion>

<Accordion title="Memories not relevant to user's query">
  **Symptoms**: the agent loads memories.
  They aren't relevant to what the user is asking about.

  **Possible causes**:

  * **Using preload with large memory sets**: preload fetches recent memories, not the most relevant
  * **Preflight not configured**: query-based retrieval isn't enabled

  **Solution**: for users with many memories (100+), enable preflight to retrieve query-relevant memories:

  ```json JSON icon=braces theme={"system"}
  {
    "memory": {
      "enabled": true,
      "preflight": {
        "limit": 5,
        "conversationWindow": 3
      }
    }
  }
  ```

  You can use both preload and preflight together.
  Preload provides baseline context, and preflight adds query-specific memories.
</Accordion>

## See also

* [Agent configuration](/doc/guides/algolia-ai/agent-studio/how-to/agent-configuration)
