Docs

Best Practices for Using Sentor ML API

🔧 Code Organization

Project Structure

sentor-project/
├── models/              # Model definitions and weights
├── preprocessing/       # Data preprocessing scripts
├── utils/              # Utility functions
├── config/             # Configuration files
├── tests/              # Test cases
└── docs/               # Documentation

Configuration Management

# config/settings.py
from pydantic import BaseSettings

class Settings(BaseSettings):
    api_key: str
    base_url: str = "https://sentor.app/api"
    timeout: int = 30
    
    class Config:
        env_file = ".env"

🚀 API Integration

Error Handling

try:
    response = client.analyze_sentiment(text)
except SentorAPIError as e:
    if e.status_code == 429:  # Rate limit exceeded
        time.sleep(e.retry_after)
        response = client.analyze_sentiment(text)
    else:
        logger.error(f"API Error: {e.message}")

Request Batching

async def batch_process(texts: List[str], batch_size: int = 50):
    """Process texts in batches to optimize API calls."""
    for i in range(0, len(texts), batch_size):
        batch = texts[i:i + batch_size]
        yield await client.analyze_batch(batch)

📊 Performance Optimization

Caching

from functools import lru_cache
import time

@lru_cache(maxsize=1000)
def cached_sentiment_analysis(text: str):
    """Cache sentiment analysis results for 1 hour."""
    return client.analyze(text)

Async Operations

async def process_multiple_texts(texts: List[str]):
    """Process multiple texts concurrently."""
    tasks = [client.analyze_async(text) for text in texts]
    return await asyncio.gather(*tasks)

🔒 Security Best Practices

API Key Management

# Load API key securely
from dotenv import load_dotenv
import os

load_dotenv()
api_key = os.getenv('SENTOR_API_KEY')
if not api_key:
    raise ValueError("API key not found in environment variables")

Request Validation

from pydantic import BaseModel, Field

class SentimentRequest(BaseModel):
    text: str = Field(..., min_length=1, max_length=5000)
    language: str = Field(default="en", regex="^[a-z]{2}$")

📈 Monitoring & Logging

Request Logging

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def log_request(response):
    logger.info({
        'status_code': response.status_code,
        'processing_time': response.headers.get('X-Processing-Time'),
        'remaining_quota': response.headers.get('X-RateLimit-Remaining')
    })

Performance Monitoring

from time import perf_counter

def measure_performance(func):
    async def wrapper(*args, **kwargs):
        start = perf_counter()
        result = await func(*args, **kwargs)
        duration = perf_counter() - start
        logger.info(f"Operation took {duration:.2f} seconds")
        return result
    return wrapper

🔄 Rate Limiting

Exponential Backoff

import random
import time

def exponential_backoff(retry_count: int, base_delay: float = 1.0):
    """Implement exponential backoff for rate limiting."""
    delay = min(300, (2 ** retry_count) + random.uniform(0, 1))
    time.sleep(delay)

🧪 Testing

Unit Tests

# tests/test_client.py
import pytest
from sentor import Client

@pytest.fixture
def client():
    return Client(api_key="test_key")

def test_sentiment_analysis(client):
    response = client.analyze("Great product!")
    assert response.sentiment == "positive"
    assert 0 <= response.confidence <= 1

📚 Additional Resources

💬 Support