> ## Documentation Index
> Fetch the complete documentation index at: https://cortex-ad5578da.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add User Memory

> Store new user memories for future reference.

    This API allows you to add memories in two formats:
    1. Raw text string - A single text-based memory
    2. User/Assistant pairs array - Conversation pairs that will be
       chunked as a single memory

    The stored memories will be chunked, embedded, and indexed for
    semantic search and retrieval.

export const TableOfContents = ({title = 'On this page', items, minHeadingLevel = 2, maxHeadingLevel = 3, className = '', activeClassName = 'text-primary dark:text-primary-light border-primary dark:border-primary-light hover:border-primary dark:hover:border-primary-light', inactiveClassName = 'hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-300'}) => {
  const [toc, setToc] = useState(items ?? []);
  const [activeId, setActiveId] = useState('');
  useEffect(() => {
    if (items && items.length) return;
    if (typeof document === 'undefined') return;
    const selectors = [];
    for (let lvl = minHeadingLevel; lvl <= maxHeadingLevel; lvl++) {
      selectors.push(`h${lvl}`);
    }
    const nodes = Array.from(document.querySelectorAll(selectors.join(','))).filter(el => el.id);
    const built = [];
    let currentTop = null;
    nodes.forEach(el => {
      const level = Number(el.tagName.slice(1));
      const node = {
        id: el.id,
        label: el.textContent.trim(),
        href: `#${el.id}`,
        children: []
      };
      if (level === minHeadingLevel) {
        built.push(node);
        currentTop = node;
      } else if (level > minHeadingLevel && currentTop) {
        currentTop.children.push(node);
      } else {
        built.push(node);
      }
    });
    setToc(built);
  }, [items, minHeadingLevel, maxHeadingLevel]);
  useEffect(() => {
    if (typeof document === 'undefined') return;
    const applyHash = () => {
      const h = window.location.hash.replace('#', '');
      if (h) setActiveId(h);
    };
    applyHash();
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActiveId(entry.target.id);
        }
      });
    }, {
      rootMargin: '0px 0px -70% 0px',
      threshold: 0.1
    });
    const ids = toc.flatMap(i => [i, ...i.children ?? []]).map(i => i.id);
    ids.forEach(id => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    window.addEventListener('hashchange', applyHash);
    return () => {
      window.removeEventListener('hashchange', applyHash);
      observer.disconnect();
    };
  }, [toc]);
  const Item = ({node, depth = 0}) => {
    const isActive = activeId === node.id;
    return <li className="toc-item relative ml-6" data-depth={depth}>
        <a href={node.href} className={`py-1 block font-medium ${isActive ? activeClassName : inactiveClassName}`} style={depth > 0 ? {
      marginLeft: `${depth}rem`
    } : {}} onClick={() => setActiveId(node.id)}>
          {node.label}
        </a>
        {node.children && node.children.length > 0 && <>
            {node.children.map(child => <Item node={child} depth={depth + 1} key={child.href} />)}
          </>}
      </li>;
  };
  const data = toc && toc.length ? toc : items || [];
  return <div className={`text-gray-600 text-sm leading-6 w-[18rem] pb-4 -mt-10 pt-10 hidden xl:block ${className}`} id="table-of-contents-custom">
      <ul id="table-of-contents-custom-content" className="toc">
        <li className="toc-item relative">
          <div className="text-gray-700 dark:text-gray-300 font-medium flex items-center space-x-2 py-1">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" xmlns="http://www.w3.org/2000/svg" className="h-3 w-3">
              <path d="M2.44434 12.6665H13.5554" strokeLinecap="round" strokeLinejoin="round"></path>
              <path d="M2.44434 3.3335H13.5554" strokeLinecap="round" strokeLinejoin="round"></path>
              <path d="M2.44434 8H7.33323" strokeLinecap="round" strokeLinejoin="round"></path>
            </svg>
            <span>{title}</span>
          </div>
        </li>
        {data.map(node => <Item node={node} key={node.href} />)}
      </ul>
    </div>;
};

<Panel>
  <TableOfContents />
</Panel>

<Tip> Hit the `Try it` button to try this API now in our playground. It's the best way to check the full request and response in one place, customize your parameters, and generate ready-to-use code snippets.</Tip>

### Sample Request

```bash theme={null}
curl -X 'POST' \
  'https://api.usecortex.ai/memories/add-memories' \
  -d '{
  "tenant_id": "string",
  "sub_tenant_id": "string",
  "raw_text": "string",
  "user_assistant_pairs": [
    {
      "user": "string",
      "assistant": "string"
    }
  ],
  "expiry_time": 0,
  "infer": false,
  "custom_instructions": "string",
  "user_name": "string",
  "memory_id": "string"
}'
```

### Examples

<Tabs>
  <Tab title="API Request">
    ```bash expandable theme={null}
    # Using raw_text
    curl --request POST \
      --url https://api.usecortex.ai/user_memory/add_user_memory \
      --header 'Authorization: Bearer <token>' \
      --header 'Content-Type: application/json' \
      --data '{
      "tenant_id": "tenant_123",
      "sub_tenant_id": "sub_tenant_123",
      "raw_text": "I wakes up early in the morning and enjoys jogging before work",
      "expiry_time": 600,
      "infer": true,
      "custom_instructions": "John is being referred in this context."
    }'

    # Or with user-assistant pairs:
    curl --request POST \
      --url https://api.usecortex.ai/user_memory/add_user_memory \
      --header 'Authorization: Bearer <token>' \
      --header 'Content-Type: application/json' \
      --data '{
      "tenant_id": "tenant_123",
      "sub_tenant_id": "sub_tenant_123",
      "user_assistant_pairs": [
        {
          "user": "What are general work preferences at startups?",
          "assistant": "People prefer working in the morning and enjoy collaborative projects with clear deadlines."
        },
        {
          "user": "How to handle stress at work?",
          "assistant": "Take regular breaks and practice mindfulness to stay focused and productive."
        }
      ],
      "expiry_time": 600,
      "infer": true,
      "custom_instructions": "User's name is John."
    }'
    ```
  </Tab>

  <Tab title="TypeScript">
    ```ts expandable theme={null}
    // Using raw_text
    const result = await client.userMemory.addUserMemory({
      tenant_id: "tenant_123",
      sub_tenant_id: "sub_tenant_123",
      raw_text: "John wakes up early in the morning and enjoys jogging before work",
      expiry_time: 600,
      infer: true,
      custom_instructions: ""
    });

    // Or with user-assistant pairs:
    const result = await client.userMemory.addUserMemory({
      tenant_id: "tenant_123",
      sub_tenant_id: "sub_tenant_123",
      user_assistant_pairs: [
        {
          user: "What are general work preferences at startups?",
          assistant: "People prefer working in the morning and enjoy collaborative projects with clear deadlines."
        },
        {
          user: "How to handle stress at work?",
          assistant: "Take regular breaks and practice mindfulness to stay focused and productive."
        }
      ],
      expiry_time: 600,
      infer: true,
      custom_instructions: "User's name is John."
    });
    ```
  </Tab>

  <Tab title="Python (Sync)">
    ```python expandable theme={null}
    # Using raw_text
    # Async usage is similar, just use async_client and await
    add_memory = client.user_memory.add_user_memory(
        tenant_id="tenant_123",
        sub_tenant_id="sub_tenant_123",
        raw_text="He wakes up early in the morning and enjoys jogging before work",
        custom_instructions="User's name is John.",
        infer=True,
        expiry_time=10*60,  # Memory will expire after 600 seconds
    )

    # Or with user-assistant pairs:
    # Async usage is similar, just use async_client and await
    add_conversation = client.user_memory.add_user_memory(
        tenant_id="tenant_123",
        sub_tenant_id="sub_tenant_123",
        user_assistant_pairs=[
            {
                UserAssistantPair(
                    user="What are general work preferences at startups?",
                    assistant="People prefer working in the morning and enjoy collaborative projects with clear deadlines.",
                ),
                UserAssistantPair(
                    user="How to handle stress at work?",
                    assistant="Take regular breaks and practice mindfulness to stay focused and productive.",
                )
            }
        ],
        custom_instructions="",
        infer=True,
        expiry_time=10*60,  # Memory will expire after 600 seconds
    )
    ```
  </Tab>
</Tabs>

## Overview

Store personal memories for a specific user to enhance personalization and provide context-aware responses in your AI applications.

## What are User Memories?

User memories are personal, contextual information stored for individual users that help your AI system:

* Remember user preferences and past interactions
* Provide personalized responses based on user history
* Enhance user experience through adaptive behavior

### Memory Types

**Raw Text**: Textual content that you want to save in Cortex as a memory. This can be any descriptive information about a user, such as their preferences, habits, background information, or important context that should be remembered for future interactions.

**User-Assistant Pairs**: Conversational exchanges between a user and an AI assistant (or any similar interaction pattern). These are structured as question-response or prompt-answer pairs that capture the flow of conversations, including responses from an LLM or any similar system.

### Additional Parameters

**Custom Instructions**: Contextual information you provide about the text being indexed that Cortex needs to know. This helps guide how the memory should be interpreted, categorized, or retrieved later. For example, you might specify that certain information is particularly important, should be weighted more heavily, or relates to specific topics.

**Infer**: When set to `true`, Cortex will process and analyze the memory content to improve its indexing and retrieval capabilities. This includes extracting key concepts, understanding context, and optimizing how the memory is stored for better semantic search and recall.

## Functionality

* **Manual Memory Addition**: Allows you to explicitly add specific memories for a user
* **Vector Store Integration**: Stores memories in a searchable vector database for semantic retrieval
* **Tenant Isolation**: Ensures memories are properly isolated by tenant and sub-tenant
* **Automatic Provisioning**: If the tenant/sub-tenant combination doesn't exist for user memory, it will be automatically provisioned on first use

## Use Cases

* **Preference Storage**: Store user preferences like preferred communication style, timezone, or language
* **Context Preservation**: Remember important details from previous conversations
* **Personalization Data**: Store information that helps tailor responses to individual users

## Important Notes

<Warning>
  **Automatic Tenant Provisioning**: If you receive an error stating "Tenant-id/sub-tenant-id combination either does not exist or is not provisioned for user memory", this means the tenant/sub-tenant combination hasn't been set up for user memory functionality yet. This will be automatically provisioned when you add or generate your first user memory for this combination.
</Warning>

<Note>
  **Memory Persistence**: User memories are stored permanently until explicitly deleted. They persist across sessions and can be retrieved using the [Retrieve User Memory](/api-reference/endpoint/retrieve-user-memory) endpoint.
</Note>

<Info>
  **Best Practices**:

  * Use clear, descriptive memory content that will be useful for future AI interactions
  * Consider the context in which memories will be retrieved
  * Avoid storing sensitive information unless necessary
  * Use consistent formatting for similar types of memories
  * **Choose either `raw_text` or `user_assistant_pairs`** - do not provide both in the same request
</Info>

## Error Responses

All endpoints return consistent error responses following the standard format. For detailed error information, see our [Error Responses](/api-reference/error-responses) documentation.


## OpenAPI

````yaml POST /memories/add-memories
openapi: 3.1.0
info:
  title: Cortex SDK API
  description: REST APIs for Cortex AI retrieval engine
  version: 0.0.1
servers:
  - url: /
    description: Local
    x-fern-server-name: cortex-backend-local
  - url: https://api.usecortex.ai
    description: Production
    x-fern-server-name: cortex-prod
    x-fern-audiences:
      - public
  - url: https://preprod.usecortex.ai
    description: Staging
    x-fern-server-name: cortex-staging
security: []
paths:
  /memories/add-memories:
    post:
      tags:
        - Memories
      summary: Add user memory
      description: |-
        Store new user memories for future reference.

            This API allows you to add memories in two formats:
            1. Raw text string - A single text-based memory
            2. User/Assistant pairs array - Conversation pairs that will be
               chunked as a single memory

            The stored memories will be chunked, embedded, and indexed for
            semantic search and retrieval.
      operationId: add_user_memory_memories_add_memories_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AddUserMemoryRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AddUserMemoryResponse'
        '400':
          description: Bad Request - Invalid input parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '401':
          description: Unauthorized - Authentication required
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '403':
          description: Forbidden - Access denied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '404':
          description: Not Found - Resource does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '422':
          description: Unprocessable Entity - Validation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '503':
          description: Service Unavailable
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
      security:
        - HTTPBearer: []
components:
  schemas:
    AddUserMemoryRequest:
      properties:
        tenant_id:
          type: string
          title: Tenant Id
          description: Unique identifier for the tenant/organization
          example: tenant_1234
        sub_tenant_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Sub Tenant Id
          description: >-
            Optional sub-tenant identifier used to organize data within a
            tenant. If omitted, the default sub-tenant created during tenant
            setup will be used.
          example: sub_tenant_4567
        raw_text:
          anyOf:
            - type: string
            - type: 'null'
          title: Raw Text
          description: >-
            Single raw text memory to store. If both raw_text and
            user_assistant_pairs are provided, raw_text will be used.
        user_assistant_pairs:
          anyOf:
            - items:
                $ref: '#/components/schemas/UserAssistantPair'
              type: array
            - type: 'null'
          title: User Assistant Pairs
          description: >-
            Array of user/assistant conversation pairs to store as a single
            memory
        expiry_time:
          anyOf:
            - type: integer
            - type: 'null'
          title: Expiry Time
          description: Expiry time in seconds for the memory (optional)
        infer:
          type: boolean
          title: Infer
          description: >-
            If true, process and compress chunks into inferred representations
            before indexing (default: False)
          default: false
          example: true
        custom_instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Custom Instructions
          description: Custom instructions to guide cortex
        user_name:
          anyOf:
            - type: string
            - type: 'null'
          title: User Name
          description: User's name for personalization
          example: John Doe
        memory_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Memory Id
          description: Optional custom memory ID (auto-generated if not provided)
          example: memory_1234
      type: object
      required:
        - tenant_id
      title: AddUserMemoryRequest
    AddUserMemoryResponse:
      properties:
        success:
          type: boolean
          title: Success
          description: Indicates whether the memory addition operation was successful
          default: true
          example: true
        user_memory_added:
          type: boolean
          title: User Memory Added
          description: Confirms whether the memory was successfully stored in the system
          default: true
          example: true
        memory_id:
          type: string
          title: Memory Id
          description: Unique identifier assigned to the newly created memory
          default: ''
          example: memory_1234
        source_id:
          type: string
          title: Source Id
          description: Source identifier from the memory service
          default: ''
          example: CortexDoc1234
        chunks_created:
          type: integer
          title: Chunks Created
          description: Total number of chunks created from the memory
          default: 0
          example: 1
        original_chunks:
          type: integer
          title: Original Chunks
          description: Number of original (non-inferred) chunks created
          default: 0
          example: 1
        inferred_chunks:
          type: integer
          title: Inferred Chunks
          description: Number of inferred chunks created
          default: 0
          example: 1
      type: object
      title: AddUserMemoryResponse
      description: Response model for adding a new user memory.
    ActualErrorResponse:
      properties:
        detail:
          $ref: '#/components/schemas/ErrorResponse'
      type: object
      required:
        - detail
      title: ActualErrorResponse
    UserAssistantPair:
      properties:
        user:
          type: string
          title: User
          description: User's message in the conversation
          example: <user>
        assistant:
          type: string
          title: Assistant
          description: Assistant's response to the user message
          example: <assistant>
      type: object
      required:
        - user
        - assistant
      title: UserAssistantPair
    ErrorResponse:
      properties:
        success:
          type: boolean
          title: Success
          default: false
        message:
          type: string
          minLength: 1
          title: Message
          default: Error occurred
        error_code:
          anyOf:
            - type: string
            - type: 'null'
          title: Error Code
      type: object
      title: ErrorResponse
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````