Skip to main content

Python SDK for Zymemory - Long-term memory for AI applications

Project description

Zymemory Python SDK

Official Python client for the Zymemory API - Long-term memory for AI applications.

Zymemory provides a powerful memory system for AI assistants, chatbots, and agents, enabling them to remember and recall information across conversations.

PyPI version Python 3.8+ License: Proprietary

Features

  • Semantic Memory Search - Find relevant memories using natural language
  • Memory Linking - Connect related memories for graph-based recall
  • Conversation Storage - Automatically cluster conversations into structured memories
  • Smart Clustering - AI-powered organization of information
  • Multi-tenant - Secure isolation for different users and organizations
  • Fast & Scalable - Built on high-performance infrastructure

Installation

pip install zymemory

Quick Start

from zymemory import ZymemoryClient

# Initialize client
client = ZymemoryClient(
    api_key="your-org-api-key",
    org_email="your-org@example.com",
    user_token="user-specific-token"
)

# Search for memories
results = client.search("What are my coffee preferences?")
for memory in results.memories:
    print(f"{memory.content}")
    print(f"   Keywords: {', '.join(memory.keywords)}")

# Create a new memory
memory = client.create_memory("I prefer oat milk lattes in the morning")
print(f"Created memory #{memory.id}")

# Store a conversation
client.store_conversation(
    user_input="What's the weather today?",
    assistant_output="It's sunny and 72°F!"
)

Authentication

Zymemory uses a two-tier authentication system:

  1. Organization API Key - Identifies your organization
  2. User Token - Identifies the end user

Getting Started

  1. Get your organization API key from the Zymemory dashboard
  2. Register your end users:
# First, initialize with just org credentials
client = ZymemoryClient(
    api_key="your-org-key",
    org_email="your-org@example.com"
)

# Register a new end user
user = client.register_user(
    external_id="user_123",  # Your system's user ID
    name="John Doe",
    email="john@example.com"
)

# Save the user token for future requests
print(f"User token: {user.token}")

# Now use it for all memory operations
client.user_token = user.token

Usage Examples

Memory Management

from zymemory import ZymemoryClient

client = ZymemoryClient(
    api_key="your-key",
    org_email="org@example.com",
    user_token="user-token"
)

# Create memories
memory1 = client.create_memory("I love dark roast coffee")
memory2 = client.create_memory("My favorite cafe is Blue Bottle", auto_merge=True)

# List all memories with pagination
result = client.list_memories(page=1, page_size=20)
print(f"Total memories: {result.total}")
for memory in result.memories:
    print(f"  {memory.id}: {memory.content}")

# Delete a memory
client.delete_memory(memory1.id)

Searching Memories

# Simple search
results = client.search("coffee preferences", top_k=5)

# Process results
print(f"Found {len(results.memories)} memories:")
for memory in results.memories:
    print(f"  {memory.content}")
    print(f"     Keywords: {memory.keywords}")
    print(f"     Connections: {memory.link_count}")

# Get just the memories (exclude unassigned conversations)
memories = client.search_memories_only("favorite foods", top_k=10)

Memory Linking

# Create links between related memories
client.create_link(source_id=1, destination_id=2)

# Get connected memories
links = client.get_memory_radius(memory_id=1, depth=2)
print(f"Outgoing links: {len(links['outgoing'])}")
print(f"Incoming links: {len(links['incoming'])}")

# Explore the memory graph
for link in links['outgoing']:
    dest = link['destination']
    print(f"  → {dest['content']}")

Conversation Storage

# Store conversation turns
# The backend automatically processes these into structured memories
client.store_conversation(
    user_input="I want to learn Python",
    assistant_output="Great! Python is perfect for beginners..."
)

client.store_conversation(
    user_input="What's a good first project?",
    assistant_output="Try building a to-do list app..."
)

# Later, search across conversations
results = client.search("learning programming")
# The system will have clustered related conversations into memories

Building a Chatbot with Memory

from zymemory import ZymemoryClient
from anthropic import Anthropic  # or openai, etc.

class MemoryChatbot:
    def __init__(self, zymemory_client, llm_client):
        self.memory = zymemory_client
        self.llm = llm_client

    def chat(self, user_message):
        # 1. Search for relevant memories
        context = self.memory.search(user_message, top_k=5)

        # 2. Build prompt with memory context
        memory_context = "\\n".join([
            f"- {m.content}" for m in context.memories[:3]
        ])

        system_prompt = f"""You are a helpful assistant with long-term memory.

Here's what you remember:
{memory_context}

Use this information to provide personalized responses."""

        # 3. Get LLM response
        response = self.llm.messages.create(
            model="claude-3-haiku-20240307",
            system=system_prompt,
            messages=[{"role": "user", "content": user_message}]
        )

        assistant_message = response.content[0].text

        # 4. Store conversation for future recall
        self.memory.store_conversation(user_message, assistant_message)

        return assistant_message

# Use it
memory_client = ZymemoryClient(api_key="...", org_email="...", user_token="...")
llm = Anthropic(api_key="...")
bot = MemoryChatbot(memory_client, llm)

print(bot.chat("What did I say about coffee?"))

Bulk Operations

# Get all memories (useful for export)
all_memories = client.get_all_memories(max_pages=10)
print(f"Total: {len(all_memories)} memories")

# Export to JSON
import json
with open("memories_backup.json", "w") as f:
    json.dump([{
        "id": m.id,
        "content": m.content,
        "keywords": m.keywords
    } for m in all_memories], f, indent=2)

API Reference

ZymemoryClient

Constructor

ZymemoryClient(
    api_key: str,
    org_email: str,
    user_token: Optional[str] = None,
    api_url: str = "https://api.heymaple.app",
    timeout: int = 30
)

Methods

Memory Management
  • create_memory(content: str, auto_merge: bool = False) -> Memory
  • delete_memory(memory_id: int) -> dict
  • list_memories(page: int = 1, page_size: int = 20) -> MemoryList
Search & Retrieval
  • search(query: str, top_k: int = 5) -> SearchResult
  • search_memories_only(query: str, top_k: int = 5) -> List[Memory]
Memory Links
  • create_link(source_id: int, destination_id: int) -> dict
  • get_memory_radius(memory_id: int, depth: int = 1) -> dict
Conversations
  • store_conversation(user_input: str, assistant_output: str) -> dict
User Management
  • register_user(external_id: str, name: str, email: Optional[str] = None) -> User
Utilities
  • get_all_memories(max_pages: int = 10, page_size: int = 100) -> List[Memory]

Models

Memory

@dataclass
class Memory:
    id: int
    content: str
    keywords: List[str]
    conversations: List[tuple[str, str]]
    created_at: Optional[str]
    link_count: Optional[int]
    metadata: Optional[Dict[str, Any]]

SearchResult

@dataclass
class SearchResult:
    memories: List[Memory]
    unassigned: List[Dict[str, Any]]

MemoryList

@dataclass
class MemoryList:
    memories: List[Memory]
    total: int
    page: int
    page_size: int

Error Handling

from zymemory import ZymemoryClient, ZymemoryError, AuthenticationError, APIError

client = ZymemoryClient(api_key="...", org_email="...", user_token="...")

try:
    memory = client.create_memory("Important information")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except APIError as e:
    print(f"API error {e.status_code}: {e}")
except ZymemoryError as e:
    print(f"Zymemory error: {e}")

Exception Hierarchy

  • ZymemoryError - Base exception
    • AuthenticationError - Invalid credentials
    • APIError - API returned error response
    • ValidationError - Invalid request data
    • NetworkError - Connection/timeout issues
    • RateLimitError - Rate limit exceeded

Advanced Features

Custom API URL (Self-hosted)

client = ZymemoryClient(
    api_key="your-key",
    org_email="org@example.com",
    user_token="user-token",
    api_url="https://your-self-hosted-instance.com"
)

Per-Request User Override

# Use different user token for specific requests
memory = client.create_memory("content", user_token="different-user-token")

Request Timeout

client = ZymemoryClient(
    api_key="your-key",
    org_email="org@example.com",
    timeout=60  # 60 seconds
)

Development

Running Tests

cd zymemory
pip install -e ".[dev]"
pytest tests/

Type Checking

mypy zymemory/

Code Formatting

black zymemory/

Support

License

This software is proprietary and confidential. All rights reserved by Hey Maple.

Redistribution is strictly prohibited. This software may only be used for internal business purposes. You may not redistribute, sublicense, sell, transfer, or make this software available to third parties in any form.

For licensing inquiries, contact: contact@heymaple.app

See LICENSE file for complete terms.

Changelog

v0.1.0 (2024-03-18)

  • Initial release
  • Core memory management
  • Search and retrieval
  • Memory linking
  • Conversation storage
  • User registration

Built with by Hey Maple

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zymemory-0.1.4.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

zymemory-0.1.4-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

Details for the file zymemory-0.1.4.tar.gz.

File metadata

  • Download URL: zymemory-0.1.4.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for zymemory-0.1.4.tar.gz
Algorithm Hash digest
SHA256 d72d827dc63877c0f345db8b3bd417e75f9edf6b1d77dce4fbebe56dbb077392
MD5 e9ceb5315e8510bbe5f7be5ae1bdfe01
BLAKE2b-256 3825758e9a2fe14f0487bbedd4ff40a607f19e3fc6a349a07e48d80d6828d814

See more details on using hashes here.

File details

Details for the file zymemory-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: zymemory-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 12.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for zymemory-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 462a2a602d951360883b6944474f3e01552a20d41888566ce9c76cb930cf2405
MD5 6e5da31903b821ea0ac01cfbfd13ae02
BLAKE2b-256 1646f0b3e6611bc8a343af5dc8520ae565c266860d1937dd4356514a9d4fd55e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page