Skip to main content

Official Python SDK for PiyAPI Memory - AI-native memory and context management

Project description

PiyAPI Memory Python SDK

Official Python SDK for PiyAPI Memory - AI-native memory and context management for your applications.

Installation

pip install piyapi-memory

For async support:

pip install piyapi-memory[async]

Quick Start

from piyapi_memory import PiyAPIClient

# Initialize the client
client = PiyAPIClient(api_key="your-api-key")

# Create a memory
memory = client.create_memory(
    content="The user prefers dark mode and uses Python primarily.",
    metadata={"category": "preferences", "source": "onboarding"},
    namespace="user-123"
)

# Search memories
results = client.semantic_search(
    query="What are the user's preferences?",
    namespace="user-123",
    limit=5
)

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

Async Usage

import asyncio
from piyapi_memory import AsyncPiyAPIClient

async def main():
    client = AsyncPiyAPIClient(api_key="your-api-key")
    
    # Create a memory
    memory = await client.create_memory(
        content="User completed the tutorial",
        namespace="user-123"
    )
    
    # Search
    results = await client.semantic_search(
        query="tutorial progress",
        namespace="user-123"
    )
    
    await client.close()

asyncio.run(main())

Features

  • Memory CRUD: Create, read, update, and delete memories
  • Semantic Search: Find relevant memories using natural language
  • Keyword Search: Traditional text-based search
  • Hybrid Search: Combine semantic and keyword search
  • Namespaces: Organize memories by user, project, or any grouping
  • Metadata Filtering: Filter search results by metadata
  • Automatic Retry: Built-in retry with exponential backoff for rate limits
  • Type Safety: Full type hints and Pydantic models

API Reference

Client Initialization

from piyapi_memory import PiyAPIClient

client = PiyAPIClient(
    api_key="your-api-key",
    base_url="https://api.piyapi.cloud",  # Optional, defaults to production
    timeout=30.0,  # Request timeout in seconds
    max_retries=3,  # Max retries on rate limit
)

Memory Operations

# Create
memory = client.create_memory(
    content="Memory content",
    metadata={"key": "value"},  # Optional
    namespace="default"  # Optional
)

# Get
memory = client.get_memory(memory_id="mem_123")

# Update
memory = client.update_memory(
    memory_id="mem_123",
    content="Updated content",
    metadata={"updated": True}
)

# Delete
client.delete_memory(memory_id="mem_123")

# List
memories = client.list_memories(
    namespace="user-123",
    limit=20,
    cursor="cursor_token"  # For pagination
)

Search Operations

# Semantic search
results = client.semantic_search(
    query="natural language query",
    namespace="user-123",
    limit=10,
    threshold=0.7,  # Minimum similarity score
    metadata_filter={"category": "preferences"}
)

# Keyword search
results = client.keyword_search(
    query="exact keywords",
    namespace="user-123",
    limit=10
)

# Hybrid search (combines semantic + keyword)
results = client.hybrid_search(
    query="search query",
    namespace="user-123",
    limit=10,
    semantic_weight=0.7  # 0-1, weight for semantic vs keyword
)

Memory Versioning

Track changes and rollback to previous versions:

# Get version history
history = client.get_versions("mem_123", limit=10)
print(f"Total versions: {history['totalVersions']}")
for version in history["versions"]:
    print(f"Version {version['version']}: {version['content'][:50]}...")

# Get specific version
version2 = client.get_version("mem_123", 2)
print(f"Version 2 content: {version2['version']['content']}")

# Rollback to previous version
result = client.rollback("mem_123", 2)
print(f"Rolled back to version {result['rollback']['restoredVersion']}")

Related Memories

Get parent-child memory relationships:

# Get related memories
related = client.get_related("mem_123", direction="both", depth=2)

if related.get("parent"):
    print(f"Parent: {related['parent']['content']}")
print(f"Children: {len(related['children'])}")

Error Handling

The SDK raises typed exceptions for different error conditions:

from piyapi_memory import PiyAPIClient
from piyapi_memory.exceptions import (
    AuthenticationError,
    RateLimitError,
    ValidationError,
    NotFoundError,
    ServerError,
)

client = PiyAPIClient(api_key="your-api-key")

try:
    memory = client.create_memory(content="test")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
except NotFoundError:
    print("Resource not found")
except ServerError:
    print("Server error, please retry")

Configuration

Environment Variables

PIYAPI_API_KEY=your-api-key
PIYAPI_BASE_URL=https://api.piyapi.cloud  # Optional
import os
from piyapi_memory import PiyAPIClient

# Client will use PIYAPI_API_KEY from environment
client = PiyAPIClient()

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

piyapi_memory-0.2.0.tar.gz (43.7 kB view details)

Uploaded Source

Built Distribution

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

piyapi_memory-0.2.0-py3-none-any.whl (18.0 kB view details)

Uploaded Python 3

File details

Details for the file piyapi_memory-0.2.0.tar.gz.

File metadata

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

File hashes

Hashes for piyapi_memory-0.2.0.tar.gz
Algorithm Hash digest
SHA256 1360e89e289cae67c7a16b4ab13edc121d1cc42957b09ca6269a0e1640517bcd
MD5 1866609bb0eb527aa1a232cce3352c5e
BLAKE2b-256 671bd0446f0236bb7d7f7b5eeb81cf818932d497656581bb7cca892479b6b75f

See more details on using hashes here.

Provenance

The following attestation bundles were made for piyapi_memory-0.2.0.tar.gz:

Publisher: publish-sdk.yml on piyso/PiyAPI

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

File details

Details for the file piyapi_memory-0.2.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for piyapi_memory-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a3b93a6ad8d3361b1a0db0057a8f4f3a6eb860a38c553375a364318506f4b2da
MD5 ff1bcc3c85fb0fb189fac81c2b255e2b
BLAKE2b-256 b254e67fef19478abab036244a19a73e88a5e90c0d16793742a0c31d4e04cd01

See more details on using hashes here.

Provenance

The following attestation bundles were made for piyapi_memory-0.2.0-py3-none-any.whl:

Publisher: publish-sdk.yml on piyso/PiyAPI

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