Skip to main content

Official Python SDK for Moderyo Content Moderation API

Project description

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.

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

moderyo-2.0.7.tar.gz (10.5 kB view details)

Uploaded Source

Built Distribution

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

moderyo-2.0.7-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

Details for the file moderyo-2.0.7.tar.gz.

File metadata

  • Download URL: moderyo-2.0.7.tar.gz
  • Upload date:
  • Size: 10.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for moderyo-2.0.7.tar.gz
Algorithm Hash digest
SHA256 71ba34c08216e8d6d5677857afc29cf613865cebe835b8367d8653d0136f80f9
MD5 9f1164cba7bd60cbb5b734e5261e12ab
BLAKE2b-256 293ad0f1568202f589931f1bccf205872002f64c9f0686328b43f8b70b6ad474

See more details on using hashes here.

File details

Details for the file moderyo-2.0.7-py3-none-any.whl.

File metadata

  • Download URL: moderyo-2.0.7-py3-none-any.whl
  • Upload date:
  • Size: 10.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for moderyo-2.0.7-py3-none-any.whl
Algorithm Hash digest
SHA256 fd649815325b015dc920f4abffc24ea27fef57e92a6f082c852135409f86a4cb
MD5 908674d1471050e25b4d7de9d0ca9c05
BLAKE2b-256 ec61132dad222c4a4edfa862840cfb23b0c306388c5008c8d73eb88ad4dd3942

See more details on using hashes here.

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