moderyo 2.0.7
Official Python SDK for Moderyo Content Moderation API
License: MIT
Requires Python: <4.0,>=3.8
Keywords: moderation, content-moderation, ai, safety, moderyo

# Moderyo Python SDK

Official Python client library for the Moderyo Content Moderation API.

[![PyPI version](https://badge.fury.io/py/moderyo.svg)](https://badge.fury.io/py/moderyo)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Installation

```bash
pip install moderyo
```

Or with Poetry:

```bash
poetry add moderyo
```

## Quick Start

```python
from moderyo import Moderyo

# Initialize client
client = Moderyo(api_key="sk_live_xxxxx")

# Moderate content
result = client.moderate("Hello, this is a test message")

print(result.flagged)        # True/False
print(result.action)         # 'allow', 'flag', 'block'
print(result.categories)     # Category breakdown
print(result.explanation)    # Human-readable explanation
```

## Async Support

```python
import asyncio
from moderyo import AsyncModeryo

async def main():
    client = AsyncModeryo(api_key="sk_live_xxxxx")
    
    result = await client.moderate("Check this content")
    print(result.action)

asyncio.run(main())
```

## Batch Processing

```python
# Moderate multiple items efficiently
results = client.moderate_batch([
    "First message",
    "Second message",
    "Third message"
])

for result in results:
    print(f"{result.id}: {result.action}")
```

## Configuration Options

```python
client = Moderyo(
    api_key="sk_live_xxxxx",
    
    # Optional settings
    base_url="https://api.moderyo.com",  # Custom API endpoint
    timeout=30,                           # Request timeout in seconds
    max_retries=3,                        # Retry count on failure
    
    # Callbacks
    on_error=lambda e: print(f"Error: {e}"),
    on_rate_limit=lambda info: print(f"Rate limited: {info}")
)
```

## Error Handling

```python
from moderyo import Moderyo
from moderyo.exceptions import (
    ModeryoError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    APIError
)

client = Moderyo(api_key="sk_live_xxxxx")

try:
    result = client.moderate("Some content")
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 APIError as e:
    print(f"API error: {e.status_code} - {e.message}")
except ModeryoError as e:
    print(f"General error: {e}")
```

## Context & Metadata

```python
result = client.moderate(
    content="User message here",
    context={
        "user_id": "user_123",
        "content_type": "chat",
        "platform": "mobile",
        "language": "en"
    }
)
```

## Response Structure

```python
result = client.moderate("Some content")

# Core fields
result.id           # Unique request ID
result.flagged      # bool - Any category triggered?
result.action       # 'allow' | 'flag' | 'block'

# Detailed scores
result.categories   # Dict of category -> bool
result.scores       # Dict of category -> float (0-1)

# Explanation (Explainability 2.0)
result.explanation  # Human-readable explanation

# Policy info
result.policy_decision  # Policy engine result
result.safety_score     # 0-100 safety score
```

## Framework Integrations

### FastAPI

```python
from fastapi import FastAPI, HTTPException, Depends
from moderyo.integrations.fastapi import ModeryoDep

app = FastAPI()

@app.post("/messages")
async def create_message(
    content: str,
    moderation = Depends(ModeryoDep(api_key="sk_live_xxx"))
):
    result = await moderation.check(content)
    
    if result.action == "block":
        raise HTTPException(400, detail=result.explanation)
    
    return {"status": "ok", "flagged": result.flagged}
```

### Django

```python
from moderyo.integrations.django import moderate_content

@moderate_content(field='message', on_block='reject')
def create_message(request):
    # Only reached if content is allowed or flagged
    Message.objects.create(content=request.POST['message'])
    return JsonResponse({'status': 'ok'})
```

### Flask

```python
from flask import Flask, request, jsonify
from moderyo.integrations.flask import require_moderation

app = Flask(__name__)

@app.route('/messages', methods=['POST'])
@require_moderation(api_key="sk_live_xxx", field='content')
def create_message():
    return jsonify({'status': 'ok'})
```

## Development

```bash
# Clone repository
git clone https://github.com/moderyo/moderyo-python.git
cd moderyo-python

# Install dependencies
poetry install

# Run tests
poetry run pytest

# Run linting
poetry run ruff check .
poetry run mypy moderyo
```

## License

MIT License - see [LICENSE](LICENSE) for details.