Skip to main content

Moderyo Python SDK

Official Python client library for the Moderyo Content Moderation API.

PyPI version Python 3.8+ License: MIT

Installation

pip install moderyo

Or with Poetry:

poetry add moderyo

Quick Start

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

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

# 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

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

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

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

Response Structure

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

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

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

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

# 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 for details.

Metadata

Release files for moderyo 2.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for moderyo 2.0.7
File Size Uploaded
moderyo-2.0.7.tar.gz 10.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for moderyo 2.0.7
File Interpreter ABI Platform
moderyo-2.0.7-py3-none-any.whl Python 3 none any Details

Total release size: 21.2 kB

Release files / moderyo-2.0.7.tar.gz

Download URL moderyo-2.0.7.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
71ba34c08216e8d6d5677857afc29cf613865cebe835b8367d8653d0136f80f9
BLAKE2b-256 checksum
How to use checksums
293ad0f1568202f589931f1bccf205872002f64c9f0686328b43f8b70b6ad474
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.0

Release files / moderyo-2.0.7-py3-none-any.whl

Download URL moderyo-2.0.7-py3-none-any.whl
Size 10.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fd649815325b015dc920f4abffc24ea27fef57e92a6f082c852135409f86a4cb
BLAKE2b-256 checksum
How to use checksums
ec61132dad222c4a4edfa862840cfb23b0c306388c5008c8d73eb88ad4dd3942
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.0

Release history Release notifications | RSS feed

This release

2.0.7 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page