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

# Generate User Memory

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>

### Examples

<Tabs>
  <Tab title="API Request">
    ```bash theme={null}
    curl --request POST \
      --url 'https://api.usecortex.ai/user_memory/generate_user_memory?tenant_id=tenant_1234&sub_tenant_id=sub_tenant_4567' \
      --header 'Authorization: Bearer YOUR_API_KEY' \
      --header 'Content-Type: application/json' \
      --data '{
      "user_message": "<string>",
      "user_name": "<string>"
    }'
    ```
  </Tab>

  <Tab title="TypeScript">
    ```ts theme={null}
    const generatedMemory = await client.userMemory.generateUserMemory({
      tenant_id: "tenant_1234",
      sub_tenant_id: "sub_tenant_4567",
      user_id: "user_123",
      context: "User mentioned they work with Python and prefer REST APIs over GraphQL"
    });
    ```
  </Tab>

  <Tab title="Python (Sync)">
    ```python theme={null}
    # Async usage is similar, just use async_client and await
    generated_memory = client.user_memory.generate_user_memory(
        tenant_id="tenant_1234",
        sub_tenant_id="sub_tenant_4567",
        user_id="user_123",
        context="User mentioned they work with Python and prefer REST APIs over GraphQL"
    )
    ```
  </Tab>
</Tabs>

## Overview

The Generate User Memory endpoint is the most sophisticated user memory endpoint that automatically creates and stores multiple user memories based on a user message. It combines AI-powered message processing, intelligent memory generation, and automatic storage to build a comprehensive memory network for each user.

## What Makes This API Special?

This API goes beyond simple memory storage by:

* **AI-Powered Analysis**: Uses advanced AI to analyze user messages and extract meaningful insights
* **Multiple Memory Generation**: Creates several related memories from a single message
* **Automatic Storage**: Stores all generated memories without requiring separate API calls
* **Memory Network Building**: Creates interconnected memories that form a "second brain" for the user
* **Contextual Understanding**: Generates memories that are contextually relevant and useful for future interactions

## Functionality

* **Intelligent Message Processing**: Analyzes user messages to understand intent and extract key information
* **Multi-Memory Generation**: Creates multiple related memories from a single message
* **Automatic Vector Storage**: Stores all generated memories in the vector database for semantic retrieval
* **User Context Integration**: Incorporates user name and context for personalized memory generation
* **Tenant Isolation**: Ensures all generated memories are properly isolated by tenant and sub-tenant
* **Automatic Provisioning**: Provisions tenant/sub-tenant for user memory if not already set up

## Use Cases

* **Conversation Analysis**: Generate memories from user conversations or chat logs
* **Document Processing**: Extract key insights from user-uploaded documents
* **Meeting Notes**: Convert meeting transcripts into structured user memories
* **Feedback Processing**: Transform user feedback into actionable memory insights
* **Learning Path Creation**: Generate memories that help track user learning progress

### Advanced Usage: Meeting Notes Processing

```bash theme={null}
curl -X POST "https://api.usecortex.ai/user_memory/generate_user_memory" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "company_123",
    "sub_tenant_id": "product_team",
    "user_message": "In today's product meeting, Sarah mentioned she's concerned about user onboarding complexity. She suggested we implement a guided tutorial and reduce the number of required fields in the signup form. The team agreed to prioritize this for the next sprint.",
    "user_name": "Sarah Johnson"
  }'
```

## 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 generate your first user memory for this combination.
</Warning>

<Note>
  **Memory Quality**: The quality of generated memories depends on the clarity and detail of the input message. Provide rich, contextual information for best results.
</Note>

<Info>
  **Best Practices**:

  * Use detailed, contextual messages for better memory generation
  * Include relevant background information in your messages
  * Consider breaking complex topics into multiple focused messages
  * Review generated memories to ensure they capture the intended insights
  * Use this API for processing longer text inputs like documents or conversations
</Info>

<Tip>
  **Pro Tip**: This API is particularly powerful when processing user feedback, meeting notes, or any text that contains multiple insights about a user's preferences, experiences, or context.
</Tip>

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