📢 Announcing our research paper: Zentry achieves 26% higher accuracy than OpenAI Memory, 91% lower latency, and 90% token savings! Read the paper to learn how we're revolutionizing AI agent memory.

🎉 Looking for TypeScript support? Zentry has you covered! Check out an example here.

1. Installation

pip install Zentryai

2. API Key Setup

  1. Sign in to Zentry Platform
  2. Copy your API Key from the dashboard

3. Instantiate Client

import os
from Zentry import MemoryClient

os.environ["Zentry_API_KEY"] = "your-api-key"

client = MemoryClient()

3.1 Instantiate Async Client (Python only)

For asynchronous operations in Python, you can use the AsyncMemoryClient:

Python
import os
from Zentry import AsyncMemoryClient

os.environ["Zentry_API_KEY"] = "your-api-key"

client = AsyncMemoryClient()


async def main():
    messages = [
        {"role": "user", "content": "I'm travelling to SF"}
    ]
    response = await client.add(messages, user_id="john")
    print(response)

await main()

4. Memory Operations

Zentry provides a simple and customizable interface for performing CRUD operations on memory.

4.1 Create Memories

Long-term memory for a user

These memory instances persist across multiple sessions. Ideal for maintaining memory over long time spans.

messages = [
    {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
    {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
]

client.add(messages, user_id="alex", metadata={"food": "vegan"})

When passing user_id, memories are primarily created based on user messages, but may be influenced by assistant messages for contextual understanding. For example, in a conversation about food preferences, both the user’s stated preferences and their responses to the assistant’s questions would form user memories. Similarly, when using agent_id, assistant messages are prioritized, but user messages might influence the agent’s memories based on context. This approach ensures comprehensive memory creation while maintaining appropriate attribution to either users or agents.

Example:

User: My favorite cuisine is Italian
Assistant: Nice! What about Indian cuisine?
User: Don't like it much since I cannot eat spicy food

Resulting user memories:
memory1 - Likes Italian food
memory2 - Doesn't like Indian food since cannot eat spicy 

(memory2 comes from user's response about Indian cuisine)
Metadata allows you to store structured information (location, timestamp, user state) with memories. Add it during creation to enable precise filtering and retrieval during searches.

Short-term memory for a user session

These memory instances persist only for the duration of a user session. Ideal for non-repetitive interactions and managing context windows efficiently.

messages = [
    {"role": "user", "content": "I'm planning a trip to Japan next month."},
    {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"},
    {"role": "user", "content": "Yes, please! Especially in Tokyo."},
    {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."}
]

client.add(messages, user_id="alex", run_id="trip-planning-2024")

Long-term memory for agents

Add a memory layer for the assistants and agents so that their responses remain consistent across sessions.

messages = [
    {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."},
    {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."}
]

client.add(messages, agent_id="ai-tutor")

The agent_id retains memories exclusively based on messages generated by the assistant or those explicitly provided as input to the assistant. Messages outside these criteria are not stored as memory.

Long-term memory for both users and agents

When you provide both user_id and agent_id, Zentry will store memories for both identifiers separately:

  • Memories from messages with "role": "user" are automatically tagged with the provided user_id
  • Memories from messages with "role": "assistant" are automatically tagged with the provided agent_id
  • During retrieval, you can provide either user_id or agent_id to access the respective memories
  • You can continuously enrich existing memory collections by adding new memories to the same user_id or agent_id in subsequent API calls, either together or separately, allowing for progressive memory building over time
  • This dual-tagging approach enables personalized experiences for both users and AI agents in your application
messages = [
    {"role": "user", "content": "I'm travelling to San Francisco"},
    {"role": "assistant", "content": "That's great! I'm going to Dubai next month."},
]

client.add(messages=messages, user_id="user1", agent_id="agent1")

Monitor Memories

You can monitor memory operations on the platform dashboard:

4.2 Search Memories

Pass user messages, interactions, and queries into our search method to retrieve relevant memories.

The search method supports two output formats: v1.0 (default) and v1.1. To use the latest format, which provides more detailed information about each memory operation, set the output_format parameter to v1.1:
query = "What should I cook for dinner today?"

client.search(query, user_id="alex")

Use category and metadata filters:

query = "What do you know about me?"

client.search(query, categories=["food_preferences"], metadata={"food": "vegan"})

Search using custom filters

Our advanced search allows you to set custom search filters. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and text. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see V2 Search Memories.

Here you need to define version as v2 in the search method.

Example 1: Search using user_id and agent_id filters

query = "What do you know about me?"
filters = {
   "OR":[
      {
         "user_id":"alex"
      },
      {
         "agent_id":{
            "in":[
               "travel-assistant",
               "customer-support"
            ]
         }
      }
   ]
}
client.search(query, version="v2", filters=filters)

Example 2: Search using date filters

query = "What do you know about me?"
filters = {
    "AND": [
        {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}},
        {"user_id": "alex"}
    ]
}
client.search(query, version="v2", filters=filters)

Example 3: Search using metadata and categories Filters

query = "What do you know about me?"
filters = {
    "AND": [
        {"metadata": {"food": "vegan"}},
        {
         "categories":{
            "contains": "food_preferences"
         }
    }
    ]
}
client.search(query, version="v2", filters=filters)

Example 4: Search using NOT filters

query = "What do you know about me?"
filters = {
    "NOT": [
        {
            "categories": {
                "contains": "food_preferences"
            }
        }
    ]
}
client.search(query, version="v2", filters=filters)

4.3 Get All Users

Get all users, agents, and runs which have memories associated with them.

client.users()

4.4 Get All Memories

Fetch all memories for a user, agent, or run using the getAll() method.

The get_all method supports two output formats: v1.0 (default) and v1.1. To use the latest format, which provides more detailed information about each memory operation, set the output_format parameter to v1.1:
We’re soon deprecating the default output format for get_all() method, which returned a list. Once the changes are live, paginated response will be the only supported format, with 100 memories per page by default. You can customize this using the page and page_size parameters.

The following examples showcase the paginated output format.

Get all memories of a user

memories = client.get_all(user_id="alex", page=1, page_size=50)

Get all memories of an AI Agent

agent_memories = client.get_all(agent_id="ai-tutor", page=1, page_size=50)

Get the short-term memories for a session

short_term_memories = client.get_all(user_id="alex", run_id="trip-planning-2024", page=1, page_size=50)

Get specific memory

memory = client.get(memory_id="582bbe6d-506b-48c6-a4c6-5df3b1e63428")

Get all memories by categories

You can filter memories by their categories when using get_all:

# Get memories with specific categories
memories = client.get_all(user_id="alex", categories=["likes"])

# Get memories with multiple categories
memories = client.get_all(user_id="alex", categories=["likes", "food_preferences"])

# Custom pagination with categories
memories = client.get_all(user_id="alex", categories=["likes"], page=1, page_size=50)

# Get memories with specific keywords
memories = client.get_all(user_id="alex", keywords="to play", page=1, page_size=50)

Get all memories using custom filters

Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see v2 Get Memories.

Here you need to define version as v2 in the get_all method.

Example 1. Get all memories using user_id and date filters

filters = {
   "AND":[
      {
         "user_id":"alex"
      },
      {
         "created_at":{
            "gte":"2024-07-01",
            "lte":"2024-07-31"
         }
      },
      {
         "categories":{
            "contains": "food_preferences"
         }
      }
   ]
}

# Default (No Pagination)
client.get_all(version="v2", filters=filters)

# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)

Example 2: Search using metadata and categories Filters

filters = {
    "AND": [
        {"metadata": {"food": "vegan"}},
        {
         "categories":{
            "contains": "food_preferences"
         }
    }
    ]
}
# Default (No Pagination)
client.get_all(version="v2", filters=filters)

# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)

Example 3: Get all memories using NOT filters

filters = {
    "NOT": [
        {
            "categories": {
                "contains": "food_preferences"
            }
        }
    ]
}

# Default (No Pagination)
client.get_all(version="v2", filters=filters)

# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)

4.5 Memory History

Get history of how a memory has changed over time.

# Add some message to create history
messages = [{"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}]
client.add(messages, user_id="alex")

# Add second message to update history
messages.append({'role': 'user', 'content': 'I turned vegetarian now.'})
client.add(messages, user_id="alex")

# Get history of how memory changed over time
memory_id = "<memory-id-here>"
history = client.history(memory_id)

4.6 Update Memory

Update a memory with new data.

message = "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."
client.update(memory_id, message)

4.7 Delete Memory

Delete specific memory.

client.delete(memory_id)

Delete all memories of a user.

client.delete_all(user_id="alex")

Delete all users.

client.delete_users()

Delete specific user or agent or app or run.

# Delete specific user
client.delete_users(user_id="alex")

# Delete specific agent
# client.delete_users(agent_id="travel-assistant")

4.8 Reset Client

client.reset()

Fun fact: You can also delete the memory using the add() method by passing a natural language command:

messages = [
    {"role": "user", "content": "Delete all of my food preferences"}
]
client.add(messages, user_id="alex")

4.9 Batch Update Memories

Update multiple memories in a single API call. You can update up to 1000 memories at once.

update_memories = [
    {
        "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496",
        "text": "Watches football"
    },
    {
        "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07",
        "text": "Loves to travel"
    }
]

response = client.batch_update(update_memories)
print(response)

4.10 Batch Delete Memories

Delete multiple memories in a single API call. You can delete up to 1000 memories at once.

delete_memories = [
    {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"},
    {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"}
]

response = client.batch_delete(delete_memories)
print(response)

4.11 Working with Zentry in TypeScript

Manage memories using TypeScript with Zentry. Zentry has completet TypeScript support Below is an example demonstrating how to add and search memories.

import MemoryClient, { Message, SearchOptions, MemoryOptions }  from 'Zentryai';

const apiKey = 'your-api-key-here';
const client = new MemoryClient(apiKey);

// Messages
const messages: Message[] = [
    { role: "user", content: "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts." },
    { role: "assistant", content: "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions." }
];

// ADD
const memoryOptions: MemoryOptions = {
    user_id: "alex",
    agent_id: "travel-assistant"
}

client.add(messages, memoryOptions)
  .then(result => console.log(result))
  .catch(error => console.error(error));

// SEARCH
const query: string = "What do you know about me?";
const searchOptions: SearchOptions = {
    user_id: "alex",
    filters: {
        OR: [
          { agent_id: "travel-assistant" },
          { user_id: "alex" }
        ]
      },
      threshold: 0.1,
      api_version: 'v2'
}
  
client.search(query, searchOptions)
.then(results => console.log(results))
.catch(error => console.error(error));

If you have any questions, please feel free to reach out to us using one of the following methods: