SDK Reference

Python SDK Reference

Complete API reference for the zymemory Python package.

ZymemoryClient

Constructor

ZymemoryClient(
    api_key: str,
    org_email: str,
    user_token: Optional[str] = None,
    api_url: str = "https://api.heymaple.app",
    timeout: int = 30
)
Parameter Type Description
api_key str Your organisation API key
org_email str Your organisation email
user_token Optional[str] End-user token (required for memory operations)
api_url str API base URL (for self-hosted)
timeout int Request timeout in seconds

Methods

Memory Management

Method Returns
create_memory(content, auto_merge=False) Memory
delete_memory(memory_id) dict
list_memories(page=1, page_size=20) MemoryList

Search & Retrieval

Method Returns
search(query, top_k=5) SearchResult
search_memories_only(query, top_k=5) List[Memory]

Memory Links

Method Returns
create_link(source_id, destination_id) dict
get_memory_radius(memory_id, depth=1) dict

Conversations

Method Returns
store_conversation(user_input, assistant_output) dict

User Management

Method Returns
register_user(external_id, name, email=None) User

Memory Details & Editing

Method Returns
get_memory_detail(memory_id) dict
get_current_representation(memory_id) dict
edit_memory(memory_id, repr_data, full_rewrite=False) dict

Version Control

Method Returns
get_all_versions(memory_id) List[dict]
get_version(memory_id, version_num) dict
revert_to_version(memory_id, version_num) dict
delete_memory_history(memory_id) dict

Access Control

Method Returns
get_memory_access(memory_id) dict
invite_user_to_memory(memory_id, user_id, role) dict
revoke_memory_access(memory_id, target_user_id) dict

Utilities

Method Returns
get_all_memories(max_pages=10, page_size=100) List[Memory]

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

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 personalised 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)

Memory Details & Editing

# Get full details of a memory
detail = client.get_memory_detail(memory_id=123)
print(f"Content: {detail['content']}")
print(f"Keywords: {detail['keywords']}")

# Get current representation (user instruction format)
current = client.get_current_representation(memory_id=123)
print(f"Current instruction: {current['representation']}")

# Edit memory representation (partial update)
client.edit_memory(
    memory_id=123,
    repr_data={"content": "Updated preference: I prefer tea over coffee"}
)

# Full rewrite of memory
client.edit_memory(
    memory_id=123,
    repr_data={
        "content": "User prefers herbal tea",
        "keywords": ["tea", "preference", "beverage"]
    },
    full_rewrite=True
)

Version Control

# List all versions of a memory
versions = client.get_all_versions(memory_id=123)
for v in versions:
    print(f"Version {v['version_number']}: {v['created_at']}")

# Get specific version
version_2 = client.get_version(memory_id=123, version_num=2)
print(f"Old content: {version_2['content']}")

# Revert to previous version
client.revert_to_version(memory_id=123, version_num=2)
print("Memory reverted to version 2")

# Delete all version history (keeps current version)
client.delete_memory_history(memory_id=123)
print("Version history cleared")

Access Control

# Get access control list for a memory
acl = client.get_memory_access(memory_id=123)
for user in acl['users']:
    print(f"{user['email']}: {user['role']}")

# Grant access to another user
client.invite_user_to_memory(
    memory_id=123,
    user_id="user-456",
    role="editor"  # or "viewer"
)
print("Access granted")

# Revoke user access
client.revoke_memory_access(
    memory_id=123,
    target_user_id="user-456"
)
print("Access revoked")

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

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

Home Solutions Pricing Blog Security Access