SAMO-DL API Documentation

View on GitHub

Overview

The SAMO-DL API provides enterprise-grade emotion detection capabilities with >90% F1 score and sub-50ms latency. This document provides comprehensive information about all available endpoints, request/response formats, error handling, and usage examples.

Base URL

https://samo-emotion-api-xxxxx-ew.a.run.app

Authentication

Currently, the API uses IP-based rate limiting. For enterprise customers, API key authentication is available.

Rate Limiting

  • Default: 1000 requests per minute per IP
  • Burst: 100 requests per second
  • Headers: Rate limit information is included in response headers

Endpoints

1. Health Check

Endpoint: GET /health

Description: Check the health status of the API and model

Request:

curl -X GET https://samo-emotion-api-xxxxx-ew.a.run.app/health

Response:

{
  "status": "healthy",
  "model_loaded": true,
  "uptime": "99.9%",
  "version": "2.0.0",
  "endpoints": ["/predict", "/health", "/metrics"],
  "timestamp": "2025-08-06T10:30:00Z"
}

Status Codes:

  • 200: Service is healthy
  • 503: Service is unhealthy or model not loaded

2. Emotion Detection

Endpoint: POST /predict

Description: Analyze text and return detected emotions with confidence scores

Request Headers:

Content-Type: application/json

Request Body:

{
  "text": "I am feeling really happy today!"
}

Request Parameters:

ParameterTypeRequiredDescriptionExample
textstringYesText to analyze for emotions"I'm excited about this project!"

Response:

[
  {
    "emotion": "joy",
    "confidence": 0.89
  },
  {
    "emotion": "excitement",
    "confidence": 0.76
  },
  {
    "emotion": "optimism",
    "confidence": 0.65
  }
]

Response Format:

FieldTypeDescription
emotionstringDetected emotion name
confidencefloatConfidence score (0.0 to 1.0)

Supported Emotions:

EMOTIONS = [
    'admiration', 'amusement', 'anger', 'annoyance', 'approval', 'caring',
    'confusion', 'curiosity', 'desire', 'disappointment', 'disapproval',
    'disgust', 'embarrassment', 'excitement', 'fear', 'gratitude', 'grief',
    'joy', 'love', 'nervousness', 'optimism', 'pride', 'realization',
    'relief', 'remorse', 'sadness', 'surprise', 'neutral'
]

Example Usage:

curl -X POST https://samo-emotion-api-xxxxx-ew.a.run.app/predict \
  -H "Content-Type: application/json" \
  -d '{"text": "I am feeling really happy today!"}'

3. Metrics

Endpoint: GET /metrics

Description: Get Prometheus-formatted metrics for monitoring

Request:

curl -X GET https://samo-emotion-api-xxxxx-ew.a.run.app/metrics

Response:

# HELP samo_emotion_requests_total Total number of emotion detection requests
# TYPE samo_emotion_requests_total counter
samo_emotion_requests_total 1234

# HELP samo_emotion_request_duration_seconds Duration of emotion detection requests
# TYPE samo_emotion_request_duration_seconds histogram
samo_emotion_request_duration_seconds_bucket{le="0.01"} 100
samo_emotion_request_duration_seconds_bucket{le="0.05"} 500
samo_emotion_request_duration_seconds_bucket{le="0.1"} 1000
samo_emotion_request_duration_seconds_bucket{le="+Inf"} 1234

# HELP samo_emotion_model_loaded Model loaded status
# TYPE samo_emotion_model_loaded gauge
samo_emotion_model_loaded 1

Error Handling

Error Response Format

All error responses follow this format:

{
  "error": "Error message description",
  "code": "ERROR_CODE",
  "details": {
    "field": "Additional error details"
  },
  "timestamp": "2025-08-06T10:30:00Z"
}

HTTP Status Codes

Status CodeDescriptionCommon Causes
200SuccessRequest processed successfully
400Bad RequestInvalid input format or missing required fields
413Payload Too LargeText exceeds maximum length (1000 characters)
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error or model loading issue
503Service UnavailableService temporarily unavailable

Error Codes

Error CodeDescriptionHTTP Status
INVALID_INPUTInvalid or missing input text400
TEXT_TOO_LONGText exceeds maximum length413
RATE_LIMIT_EXCEEDEDRate limit exceeded429
MODEL_NOT_LOADEDEmotion detection model not available503
INTERNAL_ERRORInternal server error500

Error Examples

Invalid Input:

{
  "error": "Text field is required and cannot be empty",
  "code": "INVALID_INPUT",
  "details": {
    "field": "text"
  },
  "timestamp": "2025-08-06T10:30:00Z"
}

Rate Limit Exceeded:

{
  "error": "Rate limit exceeded. Please try again later.",
  "code": "RATE_LIMIT_EXCEEDED",
  "details": {
    "limit": 1000,
    "window": "1 minute",
    "retry_after": 30
  },
  "timestamp": "2025-08-06T10:30:00Z"
}

Text Too Long:

{
  "error": "Text exceeds maximum length of 1000 characters",
  "code": "TEXT_TOO_LONG",
  "details": {
    "max_length": 1000,
    "actual_length": 1500
  },
  "timestamp": "2025-08-06T10:30:00Z"
}

Response Headers

Standard Headers

HeaderDescriptionExample
Content-TypeResponse content typeapplication/json
X-Request-IDUnique request identifierreq_1234567890
X-Response-TimeRequest processing time45ms

Rate Limiting Headers

HeaderDescriptionExample
X-RateLimit-LimitRate limit per window1000
X-RateLimit-RemainingRemaining requests in window999
X-RateLimit-ResetTime when rate limit resets1640995200
Retry-AfterSeconds to wait before retrying30

Usage Examples

Python

import requests
import json

def detect_emotion(text: str) -> dict:
    """Detect emotions in text using SAMO-DL API"""
    url = "https://samo-emotion-api-xxxxx-ew.a.run.app/predict"
    headers = {"Content-Type": "application/json"}
    data = {"text": text}
    
    try:
        response = requests.post(url, json=data, headers=headers, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"API Error: {e}")
        return {"error": "Failed to analyze emotions"}

# Example usage
emotions = detect_emotion("I'm feeling excited about this project!")
print(json.dumps(emotions, indent=2))

JavaScript

async function detectEmotion(text) {
    const url = 'https://samo-emotion-api-xxxxx-ew.a.run.app/predict';
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ text })
    };
    
    try {
        const response = await fetch(url, options);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API Error:', error);
        return { error: 'Failed to analyze emotions' };
    }
}

// Example usage
const emotions = await detectEmotion("I'm feeling excited about this project!");
console.log(emotions);

cURL

# Basic emotion detection
curl -X POST https://samo-emotion-api-xxxxx-ew.a.run.app/predict \
  -H "Content-Type: application/json" \
  -d '{"text": "I am feeling really happy today!"}'

# Health check
curl -X GET https://samo-emotion-api-xxxxx-ew.a.run.app/health

# Get metrics
curl -X GET https://samo-emotion-api-xxxxx-ew.a.run.app/metrics

Node.js with Axios

const axios = require('axios');

async function detectEmotion(text) {
    try {
        const response = await axios.post(
            'https://samo-emotion-api-xxxxx-ew.a.run.app/predict',
            { text },
            {
                headers: { 'Content-Type': 'application/json' },
                timeout: 10000
            }
        );
        return response.data;
    } catch (error) {
        console.error('API Error:', error.message);
        return { error: 'Failed to analyze emotions' };
    }
}

// Example usage
const emotions = await detectEmotion("I'm feeling excited about this project!");
console.log(emotions);

Performance Characteristics

Latency

  • Average Response Time: <50ms
  • 95th Percentile: <100ms
  • 99th Percentile: <200ms

Throughput

  • Maximum Requests/Second: 100 (burst)
  • Sustained Requests/Minute: 1000
  • Concurrent Connections: 1000+

Model Performance

  • F1 Score: >90%
  • Accuracy: >92%
  • Precision: >89%
  • Recall: >91%

Best Practices

Input Validation

  1. Text Length: Keep text under 1000 characters for optimal performance
  2. Content: Avoid HTML tags, scripts, or malicious content
  3. Language: Currently optimized for English text
  4. Encoding: Use UTF-8 encoding

Error Handling

  1. Always check HTTP status codes
  2. Implement retry logic with exponential backoff
  3. Handle rate limiting gracefully
  4. Log errors for debugging

Performance Optimization

  1. Use connection pooling for high-volume requests
  2. Implement caching for repeated text analysis
  3. Batch requests when possible
  4. Monitor response times and error rates

Security

  1. Validate all input text
  2. Sanitize user input before sending to API
  3. Use HTTPS for all requests
  4. Implement proper error handling to avoid information leakage

Monitoring and Observability

Health Checks

Monitor the /health endpoint to ensure service availability:

# Check service health
curl -f https://samo-emotion-api-xxxxx-ew.a.run.app/health || echo "Service unhealthy"

Metrics Collection

Use the /metrics endpoint for Prometheus monitoring:

# prometheus.yml
scrape_configs:
  - job_name: 'samo-emotion-api'
    static_configs:
      - targets: ['samo-emotion-api-xxxxx-ew.a.run.app']
    metrics_path: '/metrics'
    scrape_interval: 30s

Key Metrics to Monitor

  • Request Rate: samo_emotion_requests_total
  • Response Time: samo_emotion_request_duration_seconds
  • Error Rate: samo_emotion_errors_total
  • Model Status: samo_emotion_model_loaded

Support and Resources

Documentation

Examples

Testing

Support

Changelog

Version 2.0.0 (Current)

  • Performance: 2.3x speedup with ONNX optimization
  • Accuracy: >90% F1 score
  • Features: Enhanced error handling and monitoring
  • Security: Improved input validation and rate limiting

Version 1.0.0

  • Initial Release: Basic emotion detection API
  • Features: Core emotion detection functionality
  • Performance: Baseline PyTorch implementation

License

This API is part of the SAMO-DL project. See the main project repository for licensing information.