MemoryStackMemoryStack/Documentation

    Python SDK

    The official Memorystack SDK for Python. Build memory-enabled applications with full type hints and modern async support.

    ✓ Full Type Hints✓ Python 3.8+✓ Async/Await Support✓ Dataclasses

    Installation

    Install the SDK using your preferred package manager. Type hints are included automatically.

    pip install memorystack

    Memory Operations

    Create, update, delete, and retrieve memories with full CRUD support

    Hybrid Search

    Vector + text search for best accuracy and relevance

    Agent Support

    Auto-detection and scoping for multi-agent systems

    Batch Operations

    Bulk operations with 50% cost savings via batch API

    Auto-Maintenance

    Automated consolidation, reflection, and optimization

    Memory Lineage

    Complete provenance tracking and history

    Contradiction Detection

    Automatic conflict resolution and belief updating

    Export/Import

    Backup and migration support (JSON/CSV)

    Quick Start

    Get started in 30 seconds. Here's a complete example showing how to create and retrieve memories.

    from memorystack import MemoryStackClient
    import os
    
    # Initialize the client
    client = MemoryStackClient(
        api_key=os.environ["MEMORYSTACK_API_KEY"]
    )
    
    # Create memories from a conversation
    result = client.add_conversation(
        "I love Python and prefer dark mode",
        "Great! Python is excellent for data science."
    )
    
    print(f"Created {result.memories_created} memories")
    
    # Retrieve memories
    memories = client.get_personal_memories(limit=10)
    for m in memories.results:
        print(f"[{m.memory_type}] {m.content}")

    Code Examples

    Basic Usage

    Create and retrieve memories in 30 seconds

    from memorystack import MemoryStackClient
    import os
    
    # Initialize client
    client = MemoryStackClient(
        api_key=os.environ["MEMORYSTACK_API_KEY"]
    )
    
    # Create memories
    result = client.add_conversation(
        "I love Python programming",
        "Python is great for AI!"
    )
    
    # Retrieve memories
    memories = client.get_personal_memories(limit=10)
    for m in memories.results:
        print(f"[{m.memory_type}] {m.content}")

    Configuration

    Constructor Parameters

    ParameterTypeRequiredDescription
    api_keystrRequiredYour Memorystack API key
    base_urlstrOptionalCustom API base URL (for self-hosted)

    Example with Custom Base URL

    client = MemoryStackClient(
        api_key=os.environ["MEMORYSTACK_API_KEY"],
        base_url="https://your-domain.com/api/v1"
    )

    API Reference

    Core Methods

    create_memory()

    Create new memories from conversation messages. The AI automatically extracts semantic facts, preferences, and relationships.

    Signature

    create_memory(messages: List[Message], user_id: Optional[str] = None, metadata: Optional[Dict] = None) → CreateMemoryResponse

    Parameters

    FieldTypeRequiredDescription
    messagesList[Message]YesList of conversation messages
    user_idOptional[str]NoEnd-user ID for B2B applications
    metadataOptional[Dict]NoCustom metadata to attach

    Example

    from memorystack import Message
    
    # Create memories from a conversation
    result = client.create_memory(
        messages=[
            Message(
                role="user",
                content="I love Python and prefer dark mode"
            ),
            Message(
                role="assistant",
                content="Great! Python is excellent for data science."
            )
        ],
        user_id="user_123",  # Optional: for multi-tenant apps
        metadata={           # Optional: custom data
            "source": "chat",
            "session_id": "sess_xyz"
        }
    )
    
    # Response
    print(f"Created {result.memories_created} memories")
    print(f"Memory IDs: {result.memory_ids}")

    list_memories()

    Retrieve memories with powerful filtering and pagination. Perfect for fetching relevant context for your AI.

    Signature

    list_memories(user_id: Optional[str] = None, limit: int = 20, ...) → ListMemoriesResponse

    Example

    # List memories with filters
    memories = client.list_memories(
        user_id="user_123",        # Filter by specific user
        limit=20,                  # Max results per page
        memory_type="preference",  # Only preferences
        min_confidence=0.8,        # High confidence only
        order="desc"               # Newest first
    )
    
    # Process results
    print(f"Found {memories.count} memories")
    for m in memories.results:
        print(f"[{m.memory_type}] {m.content}")
        print(f"  Confidence: {m.confidence * 100:.0f}%")

    get_stats()

    Get usage statistics for your account including API calls, memory count, and plan limits.

    Example

    stats = client.get_stats()
    
    print(f"Plan: {stats.plan_tier}")
    print(f"API Calls: {stats.usage['api_calls_used']}")
    print(f"Total Memories: {stats.totals['memories']}")

    Helper Methods

    Convenient shortcuts for common operations.

    add_conversation()

    Quick way to add a user-assistant conversation.

    client.add_conversation(
        "user message",
        "assistant response",
        user_id="user_123"  # optional
    )

    add_message()

    Add a single user message.

    client.add_message(
        "My favorite color is blue",
        user_id="user_123"  # optional
    )

    get_user_memories()

    Get memories for a specific user.

    memories = client.get_user_memories(
        "user_123", limit=20
    )

    get_personal_memories()

    Get your personal memories.

    memories = client.get_personal_memories(
        limit=20
    )

    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: {e.message}")
    except MemoryStackError as e:
        print(f"Error: {e.message}")

    Common Error Codes

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

    Best Practices

    Use Environment Variables

    Store API keys in environment variables, never in code.

    Handle Errors Gracefully

    Always wrap SDK calls in try-except blocks.

    Use Virtual Environments

    Always use venv or virtualenv for project isolation.

    Add Type Hints

    Use type hints for better IDE support and type checking.

    Multi-Agent Systems

    Build collaborative agent systems with memory scoping, agent handoffs, and team coordination.

    Memory Scoping

    Control memory access with personal, team, and project-level scopes:

    from memorystack import MemoryStackClient
    
    # Create agents with different scopes
    writer = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Content Writer",
        project_name="content_team",
        team_name="editorial"
    )
    
    researcher = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Researcher",
        project_name="content_team",
        team_name="editorial"
    )
    
    # Personal memory (private to agent)
    writer.create_memory(
        content="My writing style: conversational and data-driven",
        memory_type="preference",
        scope="personal"  # Only this agent can access
    )
    
    # Team memory (shared with team)
    researcher.create_memory(
        content="Team research: AI market to reach $1.8T by 2030",
        memory_type="fact",
        scope="team"  # All editorial team members can access
    )
    
    # Project memory (shared across project)
    writer.create_memory(
        content="Company brand voice: professional yet approachable",
        memory_type="guideline",
        scope="project"  # All agents in project can access
    )
    
    # Search by scope
    personal_memories = writer.search_memories(query="", scope="personal")
    team_memories = writer.search_memories(query="", scope="team")
    project_memories = writer.search_memories(query="", scope="project")

    🔒 Personal Scope

    Private memories accessible only by the creating agent

    👥 Team Scope

    Shared memories within the same team

    🏢 Project Scope

    Accessible to all agents in the project

    Agent Handoffs

    Transfer conversations between agents with full context preservation:

    # Support agent handles initial inquiry
    support_agent = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Support Agent",
        session_id="customer_123"
    )
    
    # Store conversation context
    support_agent.create_memory(
        content="Customer issue: billing discrepancy for invoice #4521",
        memory_type="issue",
        metadata={"priority": "high", "category": "billing"}
    )
    
    # Prepare handoff context
    handoff_context = {
        "from_agent": "Support Agent",
        "to_agent": "Billing Specialist",
        "reason": "Requires billing system access",
        "customer_id": "customer_123",
        "issue_summary": "Billing discrepancy for invoice #4521"
    }
    
    # Billing specialist takes over with full context
    billing_agent = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Billing Specialist",
        session_id="customer_123"  # Same session for continuity
    )
    
    # Access previous conversation context
    previous_context = billing_agent.search_memories(
        query="billing discrepancy",
        limit=10
    )
    
    # Continue conversation with context
    billing_agent.create_memory(
        content="Resolved: Invoice #4521 corrected, refund processed",
        memory_type="resolution",
        metadata={"handoff_from": "Support Agent"}
    )

    💡 Handoff Best Practices

    • • Use the same session_id for context continuity
    • • Store handoff metadata for tracking and analytics
    • • Include issue summary and priority in handoff context
    • • Search previous memories before responding

    Team Collaboration

    Build collaborative workflows with shared team knowledge:

    # Research agent gathers information
    researcher = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Researcher",
        project_name="content_creation",
        team_name="editorial"
    )
    
    researcher.create_memory(
        content="Research finding: 73% of users prefer AI recommendations",
        memory_type="research",
        scope="team"  # Share with editorial team
    )
    
    # Writer accesses team research
    writer = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Writer",
        project_name="content_creation",
        team_name="editorial"  # Same team
    )
    
    # Access team research
    team_research = writer.search_memories(
        query="research finding",
        scope="team",
        limit=10
    )
    
    # Writer creates draft
    writer.create_memory(
        content="Draft: AI Recommendations article ready for review",
        memory_type="status",
        scope="team"
    )
    
    # Editor reviews
    editor = MemoryStackClient(
        api_key="your_api_key",
        agent_name="Editor",
        project_name="content_creation",
        team_name="editorial"
    )
    
    # Check team drafts
    drafts = editor.search_memories(
        query="draft status",
        scope="team"
    )
    
    # Provide feedback
    editor.create_memory(
        content="Feedback: Add more concrete examples in section 2",
        memory_type="feedback",
        scope="team"
    )

    CrewAI Integration

    Integrate Memorystack with CrewAI for powerful multi-agent workflows:

    from crewai import Agent, Task, Crew
    from memorystack import MemoryStackClient
    from memorystack.integrations.crewai import MemoryStackTool
    
    # Initialize Memorystack client
    memory_client = MemoryStackClient(
        api_key="your_api_key",
        project_name="research_team"
    )
    
    # Create memory tool for agents
    memory_tool = MemoryOSTool(client=memory_client)
    
    # Define agents with memory capabilities
    researcher = Agent(
        role="Research Analyst",
        goal="Gather and analyze market data",
        backstory="Expert in market research and data analysis",
        tools=[memory_tool],
        verbose=True
    )
    
    writer = Agent(
        role="Content Writer",
        goal="Create engaging content from research",
        backstory="Skilled writer with data storytelling expertise",
        tools=[memory_tool],
        verbose=True
    )
    
    # Define tasks
    research_task = Task(
        description="Research AI market trends and store findings",
        agent=researcher,
        expected_output="Market research summary with key statistics"
    )
    
    writing_task = Task(
        description="Write article using research findings from memory",
        agent=writer,
        expected_output="1000-word article on AI market trends"
    )
    
    # Create crew
    crew = Crew(
        agents=[researcher, writer],
        tasks=[research_task, writing_task],
        verbose=True
    )
    
    # Execute workflow
    result = crew.kickoff()
    print(result)

    Next Steps