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.1.tar.gz (19.0 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.1-py3-none-any.whl (19.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: memoryrelay-0.1.1.tar.gz
  • Upload date:
  • Size: 19.0 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.1.tar.gz
Algorithm Hash digest
SHA256 00ea154a27324814668a4ec530668485c43cafac9d17138bad7c9b988644a009
MD5 42d84528dea4171bffab30629981910b
BLAKE2b-256 aefdd3235608955b4f98de644bc66df8119f08eed4dd549ee3fba0915f4d559f

See more details on using hashes here.

Provenance

The following attestation bundles were made for memoryrelay-0.1.1.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.1-py3-none-any.whl.

File metadata

  • Download URL: memoryrelay-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.3 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 98880a0e34b3d2fef2a05d0af74884a147b0b61a673d69bf785e0b46e912c2ba
MD5 3de30d329081819faad02962d35047aa
BLAKE2b-256 591b3286c8b5159564e24bd358b07dde8a51d951479237d98dfe8142150b5fae

See more details on using hashes here.

Provenance

The following attestation bundles were made for memoryrelay-0.1.1-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