Installation

pip install supermemory

Basic Usage

To use the SDK, you’ll need an API key from Supermemory. Learn how to get one from Getting Started.

from supermemory import Supermemory

# Initialize the client with your API key
client = Supermemory(api_key="YOUR_API_KEY")

# Search for memories
response = client.search.execute(q="documents related to python")
print(response.results)

Creating Memories

You can create new memories by providing content to the API:

# Create a new memory
memory = client.memory.create(
    content="This is a detailed article about machine learning concepts..."
)
print(f"Created memory with ID: {memory.id}")

Type Hints

The Python SDK provides type hints for better IDE support and code completion:

from supermemory import Supermemory
from supermemory.types import MemoryCreateParams, MemoryCreateResponse

client = Supermemory(api_key="YOUR_API_KEY")

# Using type hints for parameters and responses
params: MemoryCreateParams = {
    "content": "This is a detailed article about machine learning concepts..."
}

memory: MemoryCreateResponse = client.memory.create(params)

Error Handling

The SDK throws exceptions when API requests fail. You can catch and handle these exceptions to provide better error handling in your application:

from supermemory import Supermemory
from supermemory.errors import APIError, BadRequestError, AuthenticationError

client = Supermemory(api_key="YOUR_API_KEY")

try:
    memory = client.memory.create(
        content="This is a detailed article about machine learning concepts..."
    )
except BadRequestError as e:
    print(f"Bad request: {e.status} - {e.message}")
except AuthenticationError as e:
    print(f"Authentication failed: {e.status} - {e.message}")
except APIError as e:
    print(f"API error: {e.status} - {e.message}")

Error Types

The SDK provides specific error types for different error scenarios:

  • BadRequestError (400)
  • AuthenticationError (401)
  • PermissionDeniedError (403)
  • NotFoundError (404)
  • UnprocessableEntityError (422)
  • RateLimitError (429)
  • InternalServerError (500+)
  • APIConnectionError (network issues)
  • APIConnectionTimeoutError (request timeout)

Retries and Timeouts

Automatic Retries

Certain errors are automatically retried with exponential backoff:

# Configure retries for all requests
client = Supermemory(
    api_key="YOUR_API_KEY",
    max_retries=0  # Default is 2
)

# Configure retries for a specific request
memory = client.memory.create(
    content="This is a detailed article about machine learning concepts...",
    max_retries=5
)

Configuring Timeouts

Requests time out after 60 seconds by default. You can configure this timeout:

# Configure timeout for all requests
client = Supermemory(
    api_key="YOUR_API_KEY",
    timeout=20  # 20 seconds (default is 60)
)

# Configure timeout for a specific request
memory = client.memory.create(
    content="This is a detailed article about machine learning concepts...",
    timeout=5  # 5 seconds
)

Advanced Usage

Accessing Raw Response Data

You can access the raw response data from the API:

# Get the raw response
response = client.memory.create(
    content="This is a detailed article about machine learning concepts..."
).raw_response

print(response.headers)
print(response.status_code)

Custom HTTP Client

You can provide a custom HTTP client for the SDK to use:

import httpx
from supermemory import Supermemory

# Create a custom client with specific settings
http_client = httpx.Client(
    timeout=30,
    proxies={"http://": "http://proxy.example.com:8080"}
)

# Use the custom client
client = Supermemory(
    api_key="YOUR_API_KEY",
    http_client=http_client
)

Logging

The SDK provides logging capabilities to help with debugging:

import logging
from supermemory import Supermemory

# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("supermemory")

# Use the logger with the client
client = Supermemory(
    api_key="YOUR_API_KEY",
    logger=logger,
    log_level="debug"  # Options: debug, info, warn, error, off
)

Searching Memories

Search for memories with semantic search:

# Basic search
results = client.search.execute(q="machine learning concepts")

# Search with filters
results = client.search.execute(
    q="machine learning concepts",
    filters={
        "tags": ["AI", "ML"],
        "created_after": "2023-01-01T00:00:00Z"
    },
    limit=10
)

# Print search results
for item in results.results:
    print(f"Score: {item.score}, Content: {item.content[:100]}...")

Working with Tags

You can add tags to memories for better organization and filtering:

# Create a memory with tags
memory = client.memory.create(
    content="This is a detailed article about machine learning concepts...",
    tags=["AI", "ML", "Tutorial"]
)

# Update tags for an existing memory
updated_memory = client.memory.update(
    id=memory.id,
    tags=["AI", "ML", "Tutorial", "Advanced"]
)

# Search memories by tags
results = client.search.execute(
    q="machine learning",
    filters={"tags": ["Tutorial"]}
)

Async Support

The SDK provides async support for non-blocking operations:

import asyncio
from supermemory.async_client import AsyncSupermemory

async def main():
    # Initialize the async client
    client = AsyncSupermemory(api_key="YOUR_API_KEY")
    
    # Create a memory asynchronously
    memory = await client.memory.create(
        content="This is a detailed article about machine learning concepts..."
    )
    print(f"Created memory with ID: {memory.id}")
    
    # Search memories asynchronously
    results = await client.search.execute(q="machine learning")
    for item in results.results:
        print(f"Score: {item.score}, Content: {item.content[:100]}...")

# Run the async function
asyncio.run(main())

API Reference

For a complete API reference, please refer to the API documentation on the Supermemory website.