Skip to content

Text Classification API

The Text Classification API provides AI-powered text classification for shipping statuses, delivery notifications, and custom categorization tasks.

Overview

The Classification API enables you to:

  • Classify Shipping Status: Identify delivery status from tracking notifications
  • Multi-Language Support: Automatic language detection for international text
  • Caching Results: Redis-based caching for faster repeated queries
  • Custom Models: Support for custom classification models
  • Request History: Track all classification requests for audit and analytics

Authentication

This API uses API Key authentication. Include your API key in the Authorization header:

bash
Authorization: Bearer your-api-key

API Scope

Classification endpoints use API Key authentication only. JWT tokens from user authentication are not supported here.

Endpoints

Classify Text

POST /v1/classifications

Classify text using a specified model.

Request Body:

json
{
    "model": "shipping-status-classifier",
    "query": "Your package has been delivered to the front desk and signed for by the building manager.",
    "examples": [
        ["Package delivered to recipient signature required", "Delivered_Delivered"],
        ["Package available for pickup at post office", "Delivered_AvailableForPickup"]
    ],
    "language": "auto"
}

Parameters:

ParameterTypeDefaultDescription
modelstringModel identifier to use for classification
querystringText to classify
examplesarraynullOptional few-shot learning examples
languagestring"auto"Language code or "auto" for detection

Available Models:

Model IDDescriptionCategories
shipping-status-classifierShipping and delivery status classification100+ status categories

Response:

json
{
    "object": "classification",
    "model": "shipping-status-classifier",
    "query": "Your package has been delivered to the front desk...",
    "label": "Delivered_Delivered",
    "scores": {
        "Delivered_Delivered": 0.94,
        "Delivered_Other": 0.03,
        "InTransit_OutForDelivery": 0.02,
        "InfoReceived_InfoReceived": 0.01
    }
}

Response Fields:

FieldTypeDescription
objectstringAlways "classification"
modelstringModel used for classification
querystringOriginal input text
labelstringPredicted category label
scoresobjectConfidence scores for top categories

Common Shipping Status Labels

Category LabelDescription
Delivered_DeliveredPackage successfully delivered
Delivered_AvailableForPickupAvailable for pickup at location
Delivered_IndirectSignatureDelivered with indirect signature
Delivered_OtherOther delivery status
InTransit_OutForDeliveryOut for delivery today
InTransit_InTransitIn transit to destination
InTransit_ArrivedAtFacilityArrived at sorting facility
InTransit_DepartedFacilityDeparted sorting facility
InTransit_PickedUpPackage picked up
InfoReceived_InfoReceivedShipping label created
Exception_AttemptFailDelivery attempt failed
Exception_DamagePackage damaged
Exception_ReturnedPackage being returned
Exception_RefusedDelivery refused
Exception_OtherOther exception

Language Detection

The API automatically detects the language of input text when language: "auto" is specified.

Supported Languages:

  • English (en)
  • Spanish (es)
  • French (fr)
  • German (de)
  • Italian (it)
  • Portuguese (pt)
  • Dutch (nl)
  • Chinese (zh)
  • Japanese (ja)
  • Korean (ko)

Example with language specified:

json
{
    "model": "shipping-status-classifier",
    "query": "Paquete entregado en la oficina de correos",
    "language": "es"
}

Few-Shot Learning

Provide custom examples to guide classification for your use case:

json
{
    "model": "shipping-status-classifier",
    "query": "Package held at customs awaiting clearance",
    "examples": [
        ["Package held customs inspection required", "Exception_CustomsHold"],
        ["Package delayed import processing", "Exception_CustomsHold"],
        ["Package delivered", "Delivered_Delivered"]
    ]
}

Each example is an array of [text, label] pairs.

Caching

Classification results are cached in Redis for 1 hour to improve performance for repeated queries.

Cache Key Structure:

classify:{hash(query)}:{detected_language}:{model_id}

Cache hits skip model inference and return results immediately. Cache misses trigger model inference and store the result.

Usage Examples

Python Example

python
import requests

API_KEY = "your-api-key"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://api.alaikis.com/v1/classifications",
    json={
        "model": "shipping-status-classifier",
        "query": "Your package will be delivered today between 9AM and 12PM",
        "language": "en"
    },
    headers=headers
)

result = response.json()
print(f"Status: {result['label']}")
print(f"Confidence: {result['scores'][result['label']]:.2f}")

JavaScript Example

javascript
const API_KEY = "your-api-key";

const response = await fetch("https://api.alaikis.com/v1/classifications", {
    method: "POST",
    headers: {
        "Authorization": `Bearer ${API_KEY}`,
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        model: "shipping-status-classifier",
        query: "Paket wird heute zugestellt",
        language: "de"
    })
});

const result = await response.json();
console.log(`Classification: ${result.label}`);

Batch Processing

python
queries = [
    "Package delivered to front desk",
    "Package out for delivery today",
    "Package arrived at local facility",
    "Shipping label created, awaiting pickup"
]

results = []
for query in queries:
    response = requests.post(
        "https://api.alaikis.com/v1/classifications",
        json={
            "model": "shipping-status-classifier",
            "query": query,
            "language": "auto"
        },
        headers=headers
    )
    results.append(response.json())

# Aggregate results
status_counts = {}
for r in results:
    status = r["label"].split("_")[0]
    status_counts[status] = status_counts.get(status, 0) + 1

print(f"Delivered: {status_counts.get('Delivered', 0)}")
print(f"InTransit: {status_counts.get('InTransit', 0)}")

Error Handling

Model Not Found

json
{
    "detail": "Model unknown-model not found or inactive"
}

Invalid API Key

json
{
    "detail": "Invalid API key"
}

Model Inference Error

json
{
    "detail": "Prediction failed: error message"
}

Rate Limits

TierRequests/minuteCache TTL
Free601 hour
Basic3001 hour
Enterprise100024 hours

Performance

OperationTypical Time
Cache hit< 5ms
Cache miss (small text)50-100ms
Cache miss (long text)100-300ms

Best Practices

1. Use Descriptive Queries

Provide complete context for best results:

python
# Good - complete context
"Package #12345 delivered to 123 Main St signed by John Smith"

# Poor - incomplete
"delivered"

2. Batch Similar Queries

Group queries by language for better cache utilization:

python
# Group queries by language
for lang, queries in grouped_queries.items():
    for query in queries:
        classify(query, language=lang)

3. Check Confidence Scores

Use confidence thresholds for critical decisions:

python
result = classify(query)
confidence = result["scores"][result["label"]]

if confidence > 0.9:
    auto_process(result["label"])
elif confidence > 0.7:
    flag_for_review(result)
else:
    require_manual_review(result)

4. Add Custom Examples

For domain-specific terminology, provide few-shot examples:

json
{
    "query": "AWB #789 cleared customs at JFK",
    "examples": [
        ["Customs clearance completed JFK", "InTransit_CustomsCleared"],
        ["Package cleared import processing", "InTransit_CustomsCleared"],
        ["Held for customs inspection", "Exception_CustomsHold"]
    ]
}

Request History

All classification requests are logged to the database with:

  • User ID and API Key ID
  • Model used
  • Input text
  • Output label
  • Detected language
  • Processing time
  • HTTP status code

This data is available for analytics and audit purposes through internal APIs.