agent-memory-client


Nameagent-memory-client JSON
Version 0.9.1 PyPI version JSON
download
home_pageNone
SummaryPython client for the Agent Memory Server REST API
upload_time2025-07-11 20:39:43
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Agent Memory Client

A Python client library for the [Agent Memory Server](https://github.com/redis-developer/agent-memory-server) REST API, providing comprehensive memory management capabilities for AI agents and applications.

## Features

- **Complete API Coverage**: Full support for all Agent Memory Server endpoints
- **Memory Lifecycle Management**: Explicit control over working → long-term memory promotion
- **Batch Operations**: Efficient bulk operations with built-in rate limiting
- **Auto-Pagination**: Seamless iteration over large result sets
- **Client-Side Validation**: Pre-flight validation to catch errors early
- **Enhanced Convenience Methods**: Simplified APIs for common operations
- **Type Safety**: Full type hints for better development experience
- **Async-First**: Built for modern async Python applications

## Installation

```bash
pip install agent-memory-client
```

## Quick Start

```python
import asyncio
from agent_memory_client import create_memory_client, ClientMemoryRecord, MemoryTypeEnum

async def main():
    # Create a client instance
    client = await create_memory_client(
        base_url="http://localhost:8000",
        default_namespace="my-app"
    )

    try:
        # Create some memories
        memories = [
            ClientMemoryRecord(
                text="User prefers dark mode",
                memory_type=MemoryTypeEnum.SEMANTIC,
                topics=["preferences", "ui"]
            ),
            ClientMemoryRecord(
                text="User completed onboarding on 2024-01-15",
                memory_type=MemoryTypeEnum.EPISODIC,
                topics=["onboarding", "milestones"]
            )
        ]

        # Store in long-term memory
        await client.create_long_term_memory(memories)

        # Search memories
        results = await client.search_long_term_memory(
            text="user interface preferences",
            limit=10
        )

        print(f"Found {len(results.memories)} relevant memories")
        for memory in results.memories:
            print(f"- {memory.text} (distance: {memory.dist})")

    finally:
        await client.close()

# Run the example
asyncio.run(main())
```

## Core API

### Client Setup

```python
from agent_memory_client import MemoryAPIClient, MemoryClientConfig

# Manual configuration
config = MemoryClientConfig(
    base_url="http://localhost:8000",
    timeout=30.0,
    default_namespace="my-app"
)
client = MemoryAPIClient(config)

# Or use the helper function
client = await create_memory_client(
    base_url="http://localhost:8000",
    default_namespace="my-app"
)
```

### Working Memory Operations

```python
from agent_memory_client import WorkingMemory, MemoryMessage

# Create working memory with messages
working_memory = WorkingMemory(
    session_id="user-session-123",
    messages=[
        MemoryMessage(role="user", content="Hello!"),
        MemoryMessage(role="assistant", content="Hi there! How can I help?")
    ],
    namespace="chat-app"
)

# Store working memory
response = await client.put_working_memory("user-session-123", working_memory)

# Retrieve working memory
memory = await client.get_working_memory("user-session-123")

# Convenience method for data storage
await client.set_working_memory_data(
    session_id="user-session-123",
    data={"user_preferences": {"theme": "dark", "language": "en"}}
)
```

### Long-Term Memory Operations

```python
from agent_memory_client import ClientMemoryRecord, MemoryTypeEnum

# Create memories
memories = [
    ClientMemoryRecord(
        text="User enjoys science fiction books",
        memory_type=MemoryTypeEnum.SEMANTIC,
        topics=["books", "preferences"],
        user_id="user-123"
    )
]

# Store memories
await client.create_long_term_memory(memories)

# Search with filters
from agent_memory_client.filters import Topics, UserId

results = await client.search_long_term_memory(
    text="science fiction",
    topics=Topics(any=["books", "entertainment"]),
    user_id=UserId(eq="user-123"),
    limit=20
)
```

## Enhanced Features

### Memory Lifecycle Management

```python
# Explicitly promote working memories to long-term storage
await client.promote_working_memories_to_long_term(
    session_id="user-session-123",
    memory_ids=["memory-1", "memory-2"]  # Optional: specific memories
)
```

### Batch Operations

```python
# Bulk create with rate limiting
memory_batches = [batch1, batch2, batch3]
results = await client.bulk_create_long_term_memories(
    memory_batches=memory_batches,
    batch_size=50,
    delay_between_batches=0.1
)
```

### Auto-Pagination

```python
# Iterate through all results automatically
async for memory in client.search_all_long_term_memories(
    text="user preferences",
    batch_size=100
):
    print(f"Memory: {memory.text}")
```

### Client-Side Validation

```python
from agent_memory_client.exceptions import MemoryValidationError

try:
    # Validate before sending
    client.validate_memory_record(memory)
    client.validate_search_filters(limit=10, offset=0)
except MemoryValidationError as e:
    print(f"Validation error: {e}")
```

### Enhanced Convenience Methods

```python
# Update working memory data with merge strategies
await client.update_working_memory_data(
    session_id="user-session-123",
    data_updates={"new_setting": "value"},
    merge_strategy="deep_merge"  # "replace", "merge", or "deep_merge"
)

# Append messages
new_messages = [
    {"role": "user", "content": "What's the weather?"},
    {"role": "assistant", "content": "It's sunny today!"}
]

await client.append_messages_to_working_memory(
    session_id="user-session-123",
    messages=new_messages
)
```

## Advanced Filtering

```python
from agent_memory_client.filters import (
    SessionId, Namespace, Topics, Entities,
    CreatedAt, LastAccessed, UserId, MemoryType
)
from datetime import datetime, timezone

# Complex search with filters
results = await client.search_long_term_memory(
    text="machine learning",
    session_id=SessionId(in_=["session-1", "session-2"]),
    namespace=Namespace(eq="ai-research"),
    topics=Topics(any=["ml", "ai"], none=["deprecated"]),
    entities=Entities(all=["tensorflow", "python"]),
    created_at=CreatedAt(gte=datetime(2024, 1, 1, tzinfo=timezone.utc)),
    user_id=UserId(eq="researcher-123"),
    memory_type=MemoryType(eq="semantic"),
    distance_threshold=0.8,
    limit=50
)
```

## Error Handling

```python
from agent_memory_client.exceptions import (
    MemoryClientError,
    MemoryValidationError,
    MemoryNotFoundError,
    MemoryServerError
)

try:
    memory = await client.get_working_memory("nonexistent-session")
except MemoryNotFoundError:
    print("Session not found")
except MemoryServerError as e:
    print(f"Server error {e.status_code}: {e}")
except MemoryClientError as e:
    print(f"Client error: {e}")
```

## Context Manager Usage

```python
async with create_memory_client("http://localhost:8000") as client:
    # Client will be automatically closed when exiting the context
    results = await client.search_long_term_memory("search query")
```

## Development

### Running Tests

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=agent_memory_client
```

### Code Quality

```bash
# Lint code
ruff check agent_memory_client/

# Format code
ruff format agent_memory_client/

# Type checking
mypy agent_memory_client/
```

## Requirements

- Python 3.10+
- httpx >= 0.25.0
- pydantic >= 2.0.0
- python-ulid >= 3.0.0

## License

Apache 2.0 License - see [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Please see the [main repository](https://github.com/redis-developer/agent-memory-server) for contribution guidelines.

## Links

- [Agent Memory Server](https://github.com/redis-developer/agent-memory-server) - The server this client connects to
- [Documentation](https://agent-memory-client.readthedocs.io) - Full API documentation
- [Issues](https://github.com/redis-developer/agent-memory-client/issues) - Bug reports and feature requests

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "agent-memory-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Agent Memory Server Team <support@agentmemory.com>",
    "download_url": "https://files.pythonhosted.org/packages/d2/c5/0d730f4db71b2da2ce38273c0de95bd336ba859c75a312098f667d6aab6a/agent_memory_client-0.9.1.tar.gz",
    "platform": null,
    "description": "# Agent Memory Client\n\nA Python client library for the [Agent Memory Server](https://github.com/redis-developer/agent-memory-server) REST API, providing comprehensive memory management capabilities for AI agents and applications.\n\n## Features\n\n- **Complete API Coverage**: Full support for all Agent Memory Server endpoints\n- **Memory Lifecycle Management**: Explicit control over working \u2192 long-term memory promotion\n- **Batch Operations**: Efficient bulk operations with built-in rate limiting\n- **Auto-Pagination**: Seamless iteration over large result sets\n- **Client-Side Validation**: Pre-flight validation to catch errors early\n- **Enhanced Convenience Methods**: Simplified APIs for common operations\n- **Type Safety**: Full type hints for better development experience\n- **Async-First**: Built for modern async Python applications\n\n## Installation\n\n```bash\npip install agent-memory-client\n```\n\n## Quick Start\n\n```python\nimport asyncio\nfrom agent_memory_client import create_memory_client, ClientMemoryRecord, MemoryTypeEnum\n\nasync def main():\n    # Create a client instance\n    client = await create_memory_client(\n        base_url=\"http://localhost:8000\",\n        default_namespace=\"my-app\"\n    )\n\n    try:\n        # Create some memories\n        memories = [\n            ClientMemoryRecord(\n                text=\"User prefers dark mode\",\n                memory_type=MemoryTypeEnum.SEMANTIC,\n                topics=[\"preferences\", \"ui\"]\n            ),\n            ClientMemoryRecord(\n                text=\"User completed onboarding on 2024-01-15\",\n                memory_type=MemoryTypeEnum.EPISODIC,\n                topics=[\"onboarding\", \"milestones\"]\n            )\n        ]\n\n        # Store in long-term memory\n        await client.create_long_term_memory(memories)\n\n        # Search memories\n        results = await client.search_long_term_memory(\n            text=\"user interface preferences\",\n            limit=10\n        )\n\n        print(f\"Found {len(results.memories)} relevant memories\")\n        for memory in results.memories:\n            print(f\"- {memory.text} (distance: {memory.dist})\")\n\n    finally:\n        await client.close()\n\n# Run the example\nasyncio.run(main())\n```\n\n## Core API\n\n### Client Setup\n\n```python\nfrom agent_memory_client import MemoryAPIClient, MemoryClientConfig\n\n# Manual configuration\nconfig = MemoryClientConfig(\n    base_url=\"http://localhost:8000\",\n    timeout=30.0,\n    default_namespace=\"my-app\"\n)\nclient = MemoryAPIClient(config)\n\n# Or use the helper function\nclient = await create_memory_client(\n    base_url=\"http://localhost:8000\",\n    default_namespace=\"my-app\"\n)\n```\n\n### Working Memory Operations\n\n```python\nfrom agent_memory_client import WorkingMemory, MemoryMessage\n\n# Create working memory with messages\nworking_memory = WorkingMemory(\n    session_id=\"user-session-123\",\n    messages=[\n        MemoryMessage(role=\"user\", content=\"Hello!\"),\n        MemoryMessage(role=\"assistant\", content=\"Hi there! How can I help?\")\n    ],\n    namespace=\"chat-app\"\n)\n\n# Store working memory\nresponse = await client.put_working_memory(\"user-session-123\", working_memory)\n\n# Retrieve working memory\nmemory = await client.get_working_memory(\"user-session-123\")\n\n# Convenience method for data storage\nawait client.set_working_memory_data(\n    session_id=\"user-session-123\",\n    data={\"user_preferences\": {\"theme\": \"dark\", \"language\": \"en\"}}\n)\n```\n\n### Long-Term Memory Operations\n\n```python\nfrom agent_memory_client import ClientMemoryRecord, MemoryTypeEnum\n\n# Create memories\nmemories = [\n    ClientMemoryRecord(\n        text=\"User enjoys science fiction books\",\n        memory_type=MemoryTypeEnum.SEMANTIC,\n        topics=[\"books\", \"preferences\"],\n        user_id=\"user-123\"\n    )\n]\n\n# Store memories\nawait client.create_long_term_memory(memories)\n\n# Search with filters\nfrom agent_memory_client.filters import Topics, UserId\n\nresults = await client.search_long_term_memory(\n    text=\"science fiction\",\n    topics=Topics(any=[\"books\", \"entertainment\"]),\n    user_id=UserId(eq=\"user-123\"),\n    limit=20\n)\n```\n\n## Enhanced Features\n\n### Memory Lifecycle Management\n\n```python\n# Explicitly promote working memories to long-term storage\nawait client.promote_working_memories_to_long_term(\n    session_id=\"user-session-123\",\n    memory_ids=[\"memory-1\", \"memory-2\"]  # Optional: specific memories\n)\n```\n\n### Batch Operations\n\n```python\n# Bulk create with rate limiting\nmemory_batches = [batch1, batch2, batch3]\nresults = await client.bulk_create_long_term_memories(\n    memory_batches=memory_batches,\n    batch_size=50,\n    delay_between_batches=0.1\n)\n```\n\n### Auto-Pagination\n\n```python\n# Iterate through all results automatically\nasync for memory in client.search_all_long_term_memories(\n    text=\"user preferences\",\n    batch_size=100\n):\n    print(f\"Memory: {memory.text}\")\n```\n\n### Client-Side Validation\n\n```python\nfrom agent_memory_client.exceptions import MemoryValidationError\n\ntry:\n    # Validate before sending\n    client.validate_memory_record(memory)\n    client.validate_search_filters(limit=10, offset=0)\nexcept MemoryValidationError as e:\n    print(f\"Validation error: {e}\")\n```\n\n### Enhanced Convenience Methods\n\n```python\n# Update working memory data with merge strategies\nawait client.update_working_memory_data(\n    session_id=\"user-session-123\",\n    data_updates={\"new_setting\": \"value\"},\n    merge_strategy=\"deep_merge\"  # \"replace\", \"merge\", or \"deep_merge\"\n)\n\n# Append messages\nnew_messages = [\n    {\"role\": \"user\", \"content\": \"What's the weather?\"},\n    {\"role\": \"assistant\", \"content\": \"It's sunny today!\"}\n]\n\nawait client.append_messages_to_working_memory(\n    session_id=\"user-session-123\",\n    messages=new_messages\n)\n```\n\n## Advanced Filtering\n\n```python\nfrom agent_memory_client.filters import (\n    SessionId, Namespace, Topics, Entities,\n    CreatedAt, LastAccessed, UserId, MemoryType\n)\nfrom datetime import datetime, timezone\n\n# Complex search with filters\nresults = await client.search_long_term_memory(\n    text=\"machine learning\",\n    session_id=SessionId(in_=[\"session-1\", \"session-2\"]),\n    namespace=Namespace(eq=\"ai-research\"),\n    topics=Topics(any=[\"ml\", \"ai\"], none=[\"deprecated\"]),\n    entities=Entities(all=[\"tensorflow\", \"python\"]),\n    created_at=CreatedAt(gte=datetime(2024, 1, 1, tzinfo=timezone.utc)),\n    user_id=UserId(eq=\"researcher-123\"),\n    memory_type=MemoryType(eq=\"semantic\"),\n    distance_threshold=0.8,\n    limit=50\n)\n```\n\n## Error Handling\n\n```python\nfrom agent_memory_client.exceptions import (\n    MemoryClientError,\n    MemoryValidationError,\n    MemoryNotFoundError,\n    MemoryServerError\n)\n\ntry:\n    memory = await client.get_working_memory(\"nonexistent-session\")\nexcept MemoryNotFoundError:\n    print(\"Session not found\")\nexcept MemoryServerError as e:\n    print(f\"Server error {e.status_code}: {e}\")\nexcept MemoryClientError as e:\n    print(f\"Client error: {e}\")\n```\n\n## Context Manager Usage\n\n```python\nasync with create_memory_client(\"http://localhost:8000\") as client:\n    # Client will be automatically closed when exiting the context\n    results = await client.search_long_term_memory(\"search query\")\n```\n\n## Development\n\n### Running Tests\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run tests with coverage\npytest --cov=agent_memory_client\n```\n\n### Code Quality\n\n```bash\n# Lint code\nruff check agent_memory_client/\n\n# Format code\nruff format agent_memory_client/\n\n# Type checking\nmypy agent_memory_client/\n```\n\n## Requirements\n\n- Python 3.10+\n- httpx >= 0.25.0\n- pydantic >= 2.0.0\n- python-ulid >= 3.0.0\n\n## License\n\nApache 2.0 License - see [LICENSE](LICENSE) file for details.\n\n## Contributing\n\nContributions are welcome! Please see the [main repository](https://github.com/redis-developer/agent-memory-server) for contribution guidelines.\n\n## Links\n\n- [Agent Memory Server](https://github.com/redis-developer/agent-memory-server) - The server this client connects to\n- [Documentation](https://agent-memory-client.readthedocs.io) - Full API documentation\n- [Issues](https://github.com/redis-developer/agent-memory-client/issues) - Bug reports and feature requests\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python client for the Agent Memory Server REST API",
    "version": "0.9.1",
    "project_urls": {
        "Documentation": "https://github.com/redis-developer/agent-memory-server/tree/main/docs",
        "Homepage": "https://github.com/redis-developer/agent-memory-server",
        "Issues": "https://github.com/redis-developer/agent-memory-server/issues",
        "Repository": "https://github.com/redis-developer/agent-memory-server"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "dfaa884421fd2106844b70ce41fc2f838cf99d90859112918acb5352a62a55cc",
                "md5": "362f4a9025106ca231b930541be709ad",
                "sha256": "556767a89317c72d4b9a0a54d0b4950d660deaf7f6828d97a25b2887680de7ec"
            },
            "downloads": -1,
            "filename": "agent_memory_client-0.9.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "362f4a9025106ca231b930541be709ad",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 28028,
            "upload_time": "2025-07-11T20:39:41",
            "upload_time_iso_8601": "2025-07-11T20:39:41.942839Z",
            "url": "https://files.pythonhosted.org/packages/df/aa/884421fd2106844b70ce41fc2f838cf99d90859112918acb5352a62a55cc/agent_memory_client-0.9.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "d2c50d730f4db71b2da2ce38273c0de95bd336ba859c75a312098f667d6aab6a",
                "md5": "b58bfdc0445121fbd800823b083adc9f",
                "sha256": "3be6b6dc98e93eecdc9b60703fdf4331872b792ae9259f3fc7545325f4cfa932"
            },
            "downloads": -1,
            "filename": "agent_memory_client-0.9.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b58bfdc0445121fbd800823b083adc9f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 57786,
            "upload_time": "2025-07-11T20:39:43",
            "upload_time_iso_8601": "2025-07-11T20:39:43.068815Z",
            "url": "https://files.pythonhosted.org/packages/d2/c5/0d730f4db71b2da2ce38273c0de95bd336ba859c75a312098f667d6aab6a/agent_memory_client-0.9.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-11 20:39:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "redis-developer",
    "github_project": "agent-memory-server",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "agent-memory-client"
}
        
Elapsed time: 0.83948s