Skip to content

Moderyo/moderyo-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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="mod_your_api_key")

# 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="mod_your_api_key")
    
    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="mod_your_api_key",
    
    # 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="mod_your_api_key")

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="mod_your_api_key"))
):
    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="mod_your_api_key", 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

Examples

See the playground-examples repository for a complete working FastAPI server example.

Links

License

MIT License - see LICENSE for details.

Packages

 
 
 

Contributors

Languages