Skip to main content

Official Python SDK for MemoryStack - Semantic memory management for AI agents

Project description

MemoryStack - Python SDK

Official Python SDK for MemoryStack - A semantic memory layer for AI applications.

Installation

pip install memorystack

Quick Start

from memorystack import MemoryStackClient

# Initialize the client (only API key required)
client = MemoryStackClient(api_key="your-api-key")

# Add a conversation to memory
result = client.add_conversation(
    "I love Python programming",
    "That's great! Python is excellent for AI and data science.",
    user_id="user_123"  # optional: for B2B use cases
)

print(f"Created {result.memories_created} memories")

Features

  • Simple API: Easy-to-use methods for memory management
  • Multi-Agent Support: Full agent lifecycle, teams, and handoffs
  • Type Hints: Full type annotations for better IDE support
  • Multimodal: Support for text, images, documents, and audio
  • Agent Patterns: Sequential workflows, routing, autonomous agents
  • B2B & B2C: Works for both personal and multi-tenant applications
  • Pagination: Built-in cursor-based pagination
  • Error Handling: Comprehensive exception handling

Usage

Initialize Client

from memorystack import MemoryStackClient
import os

# Only API key is required
client = MemoryStackClient(api_key=os.environ["MEMORYSTACK_API_KEY"])

Create Memories

Simple Conversation

# Add a simple conversation
result = client.add_conversation(
    "What is the capital of France?",
    "The capital of France is Paris."
)

With User ID (B2B)

# For B2B applications with end users
result = client.add_conversation(
    "I prefer dark mode",
    "I'll remember that preference.",
    user_id="alice_123"  # end user ID
)

Single Message

# Add a single message
client.add_message(
    "My favorite color is blue",
    user_id="user_456"
)

List Memories

Personal Memories

# Get your personal memories
memories = client.get_personal_memories(limit=20)

print(f"Found {memories.count} memories")
for memory in memories.results:
    print(f"- {memory.content} ({memory.memory_type})")

User Memories (B2B)

# Get memories for a specific end user
user_memories = client.get_user_memories("alice_123", limit=50)

With Pagination

cursor = None
all_results = []

while True:
    response = client.list_memories(
        user_id="alice_123",
        limit=50,
        cursor=cursor
    )
    
    all_results.extend(response.results)
    cursor = response.next_cursor
    
    if not cursor:
        break

print(f"Total memories: {len(all_results)}")

Search Memories

# Semantic search
results = client.search_memories(
    query="user preferences",
    limit=10,
    mode="hybrid"  # hybrid, vector, or text
)

for memory in results["results"]:
    print(f"- {memory['content']} (score: {memory.get('similarity', 'N/A')})")

Get Usage Statistics

stats = client.get_stats()

print(f"Plan: {stats.plan_tier}")
print(f"API Calls: {stats.usage['current_month_api_calls']} / {stats.usage['monthly_api_limit']}")
print(f"Total Memories: {stats.totals['total_memories']}")

Error Handling

from memorystack import (
    MemoryStackError,
    AuthenticationError,
    RateLimitError,
    ValidationError
)

try:
    client.add_message("Hello world")
except AuthenticationError as e:
    print(f"Auth failed: {e.message}")
except RateLimitError as e:
    print(f"Rate limit: {e.message}")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
except MemoryStackError as e:
    print(f"Error: {e.message}")
    print(f"Status: {e.status_code}")

Common error codes:

  • 401 - Invalid or missing API key
  • 429 - Rate limit exceeded
  • 400 - Invalid request payload
  • 500 - Internal server error

Best Practices

1. Use Environment Variables

import os
from memorystack import MemoryStackClient

client = MemoryStackClient(api_key=os.environ["MEMORYSTACK_API_KEY"])

2. Handle Errors Gracefully

from memorystack import MemoryStackError

try:
    result = client.add_message("Important fact")
    print(f"Success: {result.memories_created}")
except MemoryStackError as e:
    print(f"Failed to save memory: {e.message}")
    # Implement retry logic or fallback

3. Use User IDs for B2B

# Always pass user_id for multi-tenant applications
client.add_conversation(
    user_message,
    assistant_response,
    user_id=request.user.id  # your application's user ID
)

4. Add Metadata for Context

from datetime import datetime

client.create_memory(
    messages=[...],
    user_id="alice_123",
    metadata={
        "session_id": "sess_xyz",
        "source": "mobile_app",
        "version": "1.2.3",
        "timestamp": datetime.utcnow().isoformat()
    }
)

Examples

Chatbot Integration

from memorystack import MemoryStackClient
import os

memory_client = MemoryStackClient(api_key=os.environ["MEMORYSTACK_API_KEY"])

def handle_chat_message(user_id: str, message: str):
    # Your AI logic here
    response = generate_ai_response(message)
    
    # Save to memory
    memory_client.add_conversation(
        message,
        response,
        user_id=user_id
    )
    
    return response

Personal Assistant

# Store user preferences
client.add_message(
    "I prefer meetings in the morning",
    metadata={"category": "preference", "type": "scheduling"}
)

# Retrieve preferences later
preferences = client.list_memories(
    user_id="self",
    memory_type="preference",
    limit=100
)

Support

License

MIT

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

memorystack-1.0.1.tar.gz (27.9 kB view details)

Uploaded Source

Built Distribution

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

memorystack-1.0.1-py3-none-any.whl (27.0 kB view details)

Uploaded Python 3

File details

Details for the file memorystack-1.0.1.tar.gz.

File metadata

  • Download URL: memorystack-1.0.1.tar.gz
  • Upload date:
  • Size: 27.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for memorystack-1.0.1.tar.gz
Algorithm Hash digest
SHA256 210ec200a9cd8b6975cd874ded6e6d0853ac66e5a2a303f8b395896fb75cd61b
MD5 58abc7500ba8d1ff64312922b661af93
BLAKE2b-256 409238b2bb7c3f2f7ef336b98856c1ca113351937ed620a3197e2fff67fafcda

See more details on using hashes here.

File details

Details for the file memorystack-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: memorystack-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 27.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for memorystack-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 184495d4b0b3d9d21f10e346cff7c291fff104066a2fdc7b7c73a65dc00c00bd
MD5 025323963fb47e3dd137ef07e9d50fe2
BLAKE2b-256 12e3d4fb754c90d9635466ca252467e5d17c88b43e5998bcacb4fcd548624a5c

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