Python SDK

Easily integrate with the Omni API using our Python SDK

Installation

Install the Omni Python SDK using pip:

pip install omnimoderate

Getting Started

First, import the SDK and create a client instance with your API key:

Basic Usage

Here's a simple example of how to moderate text content:

# Moderate a single text item
result = client.moderate(
    input=[
        {"type": "text", "text": "This is a sample text to moderate."}
    ]
)

print(f"Moderation result: {result['flagged']}")

And here's how to moderate both text and images:

import base64
from pathlib import Path

# Function to convert an image file to base64
def image_to_base64(image_path):
    image_path = Path(image_path)
    mime_type = f"image/{image_path.suffix[1:]}"  # Remove the dot from extension
    
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
        return f"data:{mime_type};base64,{encoded_string}"

# Moderate text and image
def moderate_mixed_content(text_content, image_path):
    # Convert image to base64
    image_base64 = image_to_base64(image_path)
    
    result = client.moderate(
        input=[
            {"type": "text", "text": text_content},
            {"type": "image", "base64": image_base64}
        ],
        analyze_images=True
    )
    
    print(f"Moderation result: {result['flagged']}")
    
    # Check text result
    print(f"Text flagged: {result['results'][0]['flagged']}")
    
    # Check image result
    print(f"Image flagged: {result['results'][1]['flagged']}")
    
    # Check vision analysis
    if "vision_analysis" in result:
        print(f"Image analysis: {result['vision_analysis'][0]['analysis']}")
    
    return result

# Example usage
result = moderate_mixed_content(
    "This restaurant has amazing food!",
    "path/to/image.jpg"
)

Advanced Usage

Verifying Response Signatures

The SDK automatically verifies response signatures if you provide your signature secret:

# Create a client instance with signature verification
client = OmniClient(
    api_key="your_api_key_here",
    signature_secret="your_signature_secret_here"
)

# The SDK will automatically verify signatures
result = client.moderate(
    input=[
        {"type": "text", "text": "This is a sample text to moderate."}
    ]
)

Handling Rate Limits

The SDK includes built-in retry logic for rate limit errors:

# Create a client instance with retry options
client = OmniClient(
    api_key="your_api_key_here",
    max_retries=3,
    retry_delay=1.0,  # 1 second
    max_retry_delay=10.0  # 10 seconds
)

# The SDK will automatically retry rate-limited requests
result = client.moderate(
    input=[
        {"type": "text", "text": "This is a sample text to moderate."}
    ]
)

Custom Request Options

You can customize the request options used by the SDK:

# Create a client instance with custom request options
client = OmniClient(
    api_key="your_api_key_here",
    timeout=10.0,  # 10 seconds
    headers={
        "User-Agent": "My Custom App/1.0"
    }
)

Flask Integration

Here's an example of how to integrate the SDK with a Flask application:

from flask import Flask, request, jsonify
from omnimoderate import OmniClient
import os

app = Flask(__name__)

# Create a client instance
client = OmniClient(api_key=os.environ.get("OMNI_API_KEY"))

@app.route("/api/moderate", methods=["POST"])
def moderate_content():
    try:
        # Get the request data
        data = request.json
        
        if not data or "content" not in data:
            return jsonify({"error": "Missing content parameter"}), 400
        
        content = data["content"]
        
        # Prepare input array
        input_data = []
        
        # Add text if provided
        if "text" in content and content["text"]:
            input_data.append({"type": "text", "text": content["text"]})
        
        # Add image if provided
        if "image" in content and content["image"]:
            input_data.append({"type": "image", "base64": content["image"]})
        
        if not input_data:
            return jsonify({"error": "No valid content provided"}), 400
        
        # Submit for moderation
        result = client.moderate(
            input=input_data,
            analyze_images=data.get("analyze_images", False)
        )
        
        return jsonify(result)
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)

Django Integration

Here's an example of how to integrate the SDK with a Django view:

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
from omnimoderate import OmniClient
import os

# Create a client instance
client = OmniClient(api_key=os.environ.get("OMNI_API_KEY"))

@csrf_exempt
@require_POST
def moderate_content(request):
    try:
        # Get the request data
        data = json.loads(request.body)
        
        if not data or "content" not in data:
            return JsonResponse({"error": "Missing content parameter"}, status=400)
        
        content = data["content"]
        
        # Prepare input array
        input_data = []
        
        # Add text if provided
        if "text" in content and content["text"]:
            input_data.append({"type": "text", "text": content["text"]})
        
        # Add image if provided
        if "image" in content and content["image"]:
            input_data.append({"type": "image", "base64": content["image"]})
        
        if not input_data:
            return JsonResponse({"error": "No valid content provided"}, status=400)
        
        # Submit for moderation
        result = client.moderate(
            input=input_data,
            analyze_images=data.get("analyze_images", False)
        )
        
        return JsonResponse(result)
    
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)

Next Steps