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 |
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"
)
memory1 = client.create_memory("I love dark roast coffee")
memory2 = client.create_memory("My favorite cafe is Blue Bottle", auto_merge=True)
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}")
client.delete_memory(memory1.id)
Searching Memories
results = client.search("coffee preferences", top_k=5)
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}")
memories = client.search_memories_only("favorite foods", top_k=10)
Memory Linking
client.create_link(source_id=1, destination_id=2)
links = client.get_memory_radius(memory_id=1, depth=2)
print(f"Outgoing links: {len(links['outgoing'])}")
print(f"Incoming links: {len(links['incoming'])}")
for link in links['outgoing']:
dest = link['destination']
print(f" → {dest['content']}")
Conversation Storage
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..."
)
results = client.search("learning programming")
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):
context = self.memory.search(user_message, top_k=5)
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."""
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
self.memory.store_conversation(user_message, assistant_message)
return assistant_message
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
all_memories = client.get_all_memories(max_pages=10)
print(f"Total: {len(all_memories)} memories")
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)
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
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
)
Development
cd zymemory
pip install -e ".[dev]"
pytest tests/
mypy zymemory/
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