Skip to main content

Official Python SDK for MemoryRelay - persistent memory for AI agents

Project description

MemoryRelay Python SDK

Official Python client for MemoryRelay - persistent memory for AI agents.

PyPI version Python versions License: MIT

Features

  • 🚀 Simple API - Intuitive Pythonic interface
  • Async/Await Support - Full async client for high-performance applications
  • 🔍 Semantic Search - Vector-based memory retrieval
  • 📦 Batch Operations - Create multiple memories efficiently
  • 🏷️ Entity Tracking - Automatic relationship management
  • 🔐 Type Safe - Full Pydantic models and type hints
  • 🐍 Python 3.9+ - Modern Python support
  • Production Tested - Verified against live API

Installation

pip install memoryrelay

Quick Start

Sync Client

from memoryrelay import MemoryRelay

# Initialize client
client = MemoryRelay(api_key="mem_your_api_key_here")

# Create a memory
memory = client.memories.create(
    content="User prefers dark mode",
    agent_id="my-agent"
)

# Search memories
results = client.memories.search(
    query="user preferences",
    limit=5
)

for result in results:
    print(f"Score: {result.score:.3f}")
    print(f"Content: {result.memory.content}")

Async Client

import asyncio
from memoryrelay import AsyncMemoryRelay

async def main():
    async with AsyncMemoryRelay(api_key="mem_your_api_key_here") as client:
        # Create a memory
        memory = await client.memories.create(
            content="User prefers dark mode",
            agent_id="my-agent"
        )
        
        # Search memories
        results = await client.memories.search(
            query="user preferences",
            limit=5
        )
        
        for result in results:
            print(f"Score: {result.score:.3f}")
            print(f"Content: {result.memory.content}")

asyncio.run(main())

Usage

Initialize Client

Sync Client

from memoryrelay import MemoryRelay

# Basic initialization
client = MemoryRelay(api_key="mem_your_api_key_here")

# With custom configuration
client = MemoryRelay(
    api_key="mem_your_api_key_here",
    base_url="https://api.memoryrelay.net",  # Optional
    timeout=30.0,  # Request timeout in seconds
    max_retries=3  # Max retries for failed requests
)

# Or use context manager (recommended)
with MemoryRelay(api_key="mem_...") as client:
    # Your code here
    pass

Async Client

from memoryrelay import AsyncMemoryRelay

# Basic initialization
client = AsyncMemoryRelay(api_key="mem_your_api_key_here")

# Use async context manager (recommended)
async with AsyncMemoryRelay(api_key="mem_...") as client:
    # Your async code here
    memory = await client.memories.create(...)

Create Memories

Sync

# Create a single memory
memory = client.memories.create(
    content="User completed Python tutorial",
    agent_id="learning-agent",
    metadata={"course": "python-101", "completed": True}
)

# Batch create (faster for multiple memories)
response = client.memories.create_batch([
    {"content": "Memory 1", "agent_id": "agent-1"},
    {"content": "Memory 2", "agent_id": "agent-1"},
    {"content": "Memory 3", "agent_id": "agent-1"}
])

print(f"Created {response.succeeded}/{response.total} memories")
print(f"Took {response.timing['total_ms']:.0f}ms")

Async

# Create a single memory
memory = await client.memories.create(
    content="User completed Python tutorial",
    agent_id="learning-agent",
    metadata={"course": "python-101", "completed": True}
)

# Batch create (faster for multiple memories)
response = await client.memories.create_batch([
    {"content": "Memory 1", "agent_id": "agent-1"},
    {"content": "Memory 2", "agent_id": "agent-1"},
    {"content": "Memory 3", "agent_id": "agent-1"}
])

print(f"Created {response.succeeded}/{response.total} memories")
print(f"Took {response.timing['total_ms']:.0f}ms")

Search Memories

# Semantic search
results = client.memories.search(
    query="what programming languages does the user know?",
    agent_id="my-agent",
    limit=10,
    min_score=0.7  # Only return results with score >= 0.7
)

# With metadata filtering
results = client.memories.search(
    query="completed courses",
    metadata_filter={"completed": True}
)

Update & Delete

# Update memory
updated = client.memories.update(
    memory_id="mem_abc123",
    content="Updated content",
    metadata={"updated": True}
)

# Delete memory
client.memories.delete(memory_id="mem_abc123")

List Memories

# List all memories for an agent
memories = client.memories.list(
    agent_id="my-agent",
    limit=100,
    offset=0
)

# List with user filter
memories = client.memories.list(
    user_id="user_123",
    limit=50
)

Entity Management

# Create entity
entity = client.entities.create(
    entity_type="person",
    entity_value="John Doe",
    agent_id="my-agent"
)

# Link entity to memory
client.entities.link(
    entity_id=entity.id,
    memory_id=memory.id
)

# List entities
entities = client.entities.list(
    agent_id="my-agent",
    entity_type="person"
)

Health Check

health = client.health()
print(f"API Status: {health.status}")
print(f"Version: {health.version}")
print(f"Services: {health.services}")

Error Handling

from memoryrelay import (
    MemoryRelay,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
    ValidationError,
    APIError,
)

try:
    memory = client.memories.create(
        content="Test memory",
        agent_id="my-agent"
    )
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after}s")
except NotFoundError:
    print("Resource not found")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
except APIError as e:
    print(f"API error: {e.message} (status: {e.status_code})")

Examples

See the examples/ directory for more usage examples:

Development

Setup

git clone https://github.com/memoryrelay/python-sdk.git
cd python-sdk
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows
pip install -e ".[dev]"

Testing

pytest
pytest --cov=memoryrelay  # With coverage

Code Quality

black .
ruff check .
mypy memoryrelay

API Reference

Full API documentation available at memoryrelay.io/docs

Support

License

MIT License - see LICENSE for details.

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

memoryrelay-0.1.0.tar.gz (18.8 kB view details)

Uploaded Source

Built Distribution

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

memoryrelay-0.1.0-py3-none-any.whl (19.0 kB view details)

Uploaded Python 3

File details

Details for the file memoryrelay-0.1.0.tar.gz.

File metadata

  • Download URL: memoryrelay-0.1.0.tar.gz
  • Upload date:
  • Size: 18.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for memoryrelay-0.1.0.tar.gz
Algorithm Hash digest
SHA256 8ccca63a946272a01eab604240c7d0fc904e857ad4556d350a0ffc5a03078ae4
MD5 4c0f622bc74d163762b5c5efc4bfb8d0
BLAKE2b-256 ef59b0dc5bcf543ea7680a9386c637a8abdae6005d2a474b754c2451ca3849a0

See more details on using hashes here.

Provenance

The following attestation bundles were made for memoryrelay-0.1.0.tar.gz:

Publisher: ci-cd.yml on memoryrelay/python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file memoryrelay-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: memoryrelay-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 19.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for memoryrelay-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c9b1cc3ab186b173d270a16bec5843293b2e34c7da569e32365b456ce3cd2482
MD5 0d5416414789373090ff2ec3b20f0072
BLAKE2b-256 6300dae135b877f6d754776e1f15c8e6738c6f1177993b07a359eb42beb12e59

See more details on using hashes here.

Provenance

The following attestation bundles were made for memoryrelay-0.1.0-py3-none-any.whl:

Publisher: ci-cd.yml on memoryrelay/python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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