ClassifAI

Examples

Real-world code examples for using ClassifAI in your applications

Python Examples

Installation

pip install classifai-sdk

Basic Sentiment Analysis

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

def classify_sentiment(text: str) -> dict:
    return client.classify(
        content=text,
        labels=["positive", "negative", "neutral"]
    )

# Example usage
result = classify_sentiment("This is the best product I've ever bought!")
print(f"Sentiment: {result['label']} ({result['labels'][result['label']]:.0%} confidence)")

Classify with Feedback Loop

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

# Classify
result = client.classify(
    content="Great service!",
    labels=["positive", "negative"],
    project_id="my-sentiment-project"
)

# Submit feedback
client.submit_feedback(
    detection_id=result["detection_id"],
    ground_truth="positive"
)

Image Classification

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

# Classify from local file (automatically reads and encodes)
result = client.classify(
    content="product.jpg",
    labels=["apparel", "electronics", "home_goods", "other"]
)

print(f"Category: {result['label']}")

JavaScript/TypeScript Examples

Next.js API Route

// app/api/classify/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { text } = await request.json();

  const response = await fetch('https://api.classifai.dev/classify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.CLASSIFAI_API_KEY || '',
    },
    body: JSON.stringify({
      content: [{ type: 'text', content: text }],
      labels: ['spam', 'not_spam'],
      project_id: 'spam-detector',
    }),
  });

  const data = await response.json();
  return NextResponse.json(data);
}

React Hook

import { useState } from 'react';

export function useClassification() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const classify = async (text: string) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/classify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text }),
      });

      if (!response.ok) throw new Error('Classification failed');

      const data = await response.json();
      return data;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
      return null;
    } finally {
      setLoading(false);
    }
  };

  return { classify, loading, error };
}

// Usage in component
function SpamDetector() {
  const { classify, loading } = useClassification();
  const [result, setResult] = useState(null);

  const handleSubmit = async (text: string) => {
    const classification = await classify(text);
    setResult(classification);
  };

  return (
    <div>
      {loading && <p>Classifying...</p>}
      {result && <p>Result: {result.label}</p>}
    </div>
  );
}

Use Case Examples

Customer Support Routing

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

def route_support_ticket(ticket_text: str, customer_email: str):
    """Route support tickets to the right team"""

    result = client.classify(
        content=ticket_text,
        description="Customer support tickets categorized by department and urgency",
        project_id="support-routing"
    )

    # Route based on classification
    routing_map = {
        "billing": "billing@company.com",
        "technical": "support@company.com",
        "sales": "sales@company.com",
        "urgent": "escalations@company.com"
    }

    team_email = routing_map.get(result['label'], "support@company.com")

    # Send to appropriate team
    send_email(
        to=team_email,
        subject=f"[{result['label'].upper()}] Support Request",
        body=f"From: {customer_email}\n\n{ticket_text}"
    )

    return result

Content Moderation Pipeline

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

def moderate_content(text: str, image_url: str = None) -> dict:
    """Check if content violates policies"""

    # Build content list (SDK handles URL downloads automatically)
    content_items = [text]
    if image_url:
        content_items.append(image_url)

    result = client.classify(
        content=content_items,
        labels=["safe", "spam", "hate_speech", "explicit_content", "violence"],
        project_id="content-moderation"
    )

    # Take action based on classification
    if result['label'] != 'safe' and result['labels'][result['label']] > 0.8:
        return {
            "approved": False,
            "reason": result['label'],
            "confidence": result['labels'][result['label']]
        }

    return {"approved": True}

Multi-Language Sentiment Analysis

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

def analyze_reviews(reviews: list[dict]) -> dict:
    """Analyze product reviews in batch"""

    results = []
    for review in reviews:
        result = client.classify(
            content=review['text'],
            labels=["positive", "negative", "neutral"],
            project_id="product-reviews"
        )

        results.append({
            "review_id": review['id'],
            "sentiment": result['label'],
            "confidence": result['labels'][result['label']],
            "detection_id": result['detection_id']
        })

    # Calculate aggregate sentiment
    sentiments = [r['sentiment'] for r in results]
    positive_rate = sentiments.count('positive') / len(sentiments)

    return {
        "total_reviews": len(reviews),
        "positive_rate": positive_rate,
        "classifications": results
    }

Best Practices

Use Project IDs

Always use consistent project_id values to build up classification history:

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

# Good - reuses same project
client.classify(content=text, project_id="my-sentiment-analyzer")

# Bad - creates new project each time
client.classify(content=text)  # Random project_id generated

Submit Feedback Regularly

The more feedback you provide, the better the accuracy:

from classifai import ClassifAI

client = ClassifAI(api_key="your_api_key")

# After classification
result = client.classify(content=text, labels=["spam", "not_spam"])

# Later, when you verify the classification
if user_marked_as_spam:
    client.submit_feedback(result['detection_id'], "spam")

Handle Rate Limits

Implement exponential backoff for rate limit errors:

import time
from classifai import ClassifAI, RateLimitError

client = ClassifAI(api_key="your_api_key")

def classify_with_retry(content, labels, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.classify(content=content, labels=labels)
        except RateLimitError:
            if attempt == max_retries - 1:
                raise
            wait_time = 2 ** attempt  # Exponential backoff
            time.sleep(wait_time)

Use Environment Variables

Never hardcode API keys:

import os
from classifai import ClassifAI

client = ClassifAI(api_key=os.getenv("CLASSIFAI_API_KEY"))

Next Steps