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 - The memory layer for AI applications.

PyPI Website Documentation

What is MemoryStack?

MemoryStack is a semantic memory layer that gives your AI applications persistent, searchable memory. Instead of losing context between conversations, your AI can:

  • Remember user preferences, facts, and conversation history
  • Search through memories using natural language
  • Learn from past interactions to provide personalized responses
  • Scale from personal assistants to multi-tenant B2B applications

Think of it as a brain for your AI - it stores information intelligently and retrieves it when needed.

Installation

pip install memorystack

Quick Start

from memorystack import MemoryStackClient

client = MemoryStackClient(api_key="your-api-key")

# Store a memory
client.add("User prefers dark mode")

# Search memories
results = client.search("user preferences")
print(results["results"])

That's it! Two methods - add() and search() - handle 90% of use cases.

Core API

add() - Store Memories

The add() method accepts either a simple string or a list of messages:

# Simple text
client.add("User likes Python")

# With user ID (for B2B apps)
client.add("User prefers morning meetings", user_id="user_123")

# Conversation format
client.add([
    {"role": "user", "content": "What is my favorite color?"},
    {"role": "assistant", "content": "Based on our conversations, you prefer blue!"}
])

# With metadata
client.add(
    "Important project deadline is Friday",
    user_id="user_123",
    metadata={"category": "work", "priority": "high"}
)

search() - Find Memories

The search() method finds relevant memories using semantic search:

# Simple search
results = client.search("user preferences")

# With user ID filter
results = client.search("favorite color", user_id="user_123")

# Limit results
results = client.search("meetings", limit=5)

Common Use Cases

Chatbot with Memory

from memorystack import MemoryStackClient
from openai import OpenAI

memory = MemoryStackClient(api_key=os.environ["MEMORYSTACK_API_KEY"])
openai = OpenAI()

def chat(user_id: str, message: str) -> str:
    # Get relevant context from memory
    context = memory.search(message, user_id=user_id, limit=5)
    
    # Build prompt with memory context
    memory_context = "\n".join([f"- {m['content']}" for m in context["results"]])
    system_prompt = f"""You are a helpful assistant. Here's what you remember about this user:
{memory_context}"""

    # Generate response
    response = openai.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": message}
        ]
    )

    reply = response.choices[0].message.content

    # Save conversation to memory
    memory.add([
        {"role": "user", "content": message},
        {"role": "assistant", "content": reply}
    ], user_id=user_id)

    return reply

Personal Assistant

# Store preferences
client.add("I wake up at 6am every day")
client.add("I prefer coffee over tea")
client.add("My favorite restaurant is Olive Garden")

# Later, retrieve relevant info
results = client.search("morning routine")
# Returns: "I wake up at 6am every day"

results = client.search("food preferences")
# Returns: "My favorite restaurant is Olive Garden", "I prefer coffee over tea"

Multi-Tenant B2B App

# Each user has isolated memories
client.add("Prefers dark mode", user_id="alice_123")
client.add("Prefers light mode", user_id="bob_456")

# Search only returns that user's memories
alice_prefs = client.search("theme preference", user_id="alice_123")
# Returns: "Prefers dark mode"

Additional Methods

While add() and search() cover most needs, the SDK also provides:

# List all memories with pagination
memories = client.list_memories(limit=50)

# Get usage statistics
stats = client.get_stats()
print(f"Total memories: {stats.totals['total_memories']}")

# Update a memory
client.update_memory("memory-id", content="Updated content")

# Delete a memory
client.delete_memory("memory-id")

Error Handling

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

try:
    client.add("Hello world")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limit exceeded, retry later")
except ValidationError as e:
    print(f"Invalid input: {e.message}")
except MemoryStackError as e:
    print(f"Error: {e.message}")

Configuration Options

client = MemoryStackClient(
    api_key=os.environ["MEMORYSTACK_API_KEY"],
    
    # Optional settings
    base_url="https://www.memorystack.app",  # Custom API URL
    timeout=30,                               # Request timeout (seconds)
    enable_logging=True,                      # Enable debug logging
    
    # Retry configuration
    max_retries=3,
    retry_delay=1.0,
)

Framework Integrations

LangChain

from memorystack import MemoryStackClient
from langchain.memory import ConversationBufferMemory

# Use MemoryStack as your LangChain memory backend
client = MemoryStackClient(api_key=os.environ["MEMORYSTACK_API_KEY"])

# Store conversation
client.add([
    {"role": "user", "content": "My name is Alice"},
    {"role": "assistant", "content": "Nice to meet you, Alice!"}
], user_id="alice")

# Retrieve for context
context = client.search("user name", user_id="alice")

CrewAI

from memorystack import MemoryStackClient
from crewai import Agent, Task, Crew

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

# Agents can share memories
memory.add("Project deadline is next Friday", metadata={"team": "engineering"})

# Search shared context
context = memory.search("deadlines")

Links

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.4.tar.gz (26.7 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.4-py3-none-any.whl (25.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: memorystack-1.0.4.tar.gz
  • Upload date:
  • Size: 26.7 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.4.tar.gz
Algorithm Hash digest
SHA256 4d0daa32fad26b95fd329376004805fc13edbe444f3eef6a3fa15dffbb879e09
MD5 1ab819a66afff6b91068697c68e1e704
BLAKE2b-256 03d2d36caff733f290c085d7afc87de03041159d36309b0dd5136cc7036709b2

See more details on using hashes here.

File details

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

File metadata

  • Download URL: memorystack-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 25.6 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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 e6426564cd0eebf7d899f1b641153b428b63313996eb457ba99b468f4afc64ac
MD5 b0c3bbfef8195aedbef8c102b1ae6f36
BLAKE2b-256 9716e42dd2a3c3368e3c1fc088c9bdfdb31048058723de3357df3740baa1b1d0

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