Skip to main content

Base URL

All ML endpoints are prefixed with /v1/ml and typically accessed through the API gateway:
https://api.sgivu.com/v1/ml
For direct access during development:
http://localhost:8000/v1/ml

Authentication

All endpoints require authentication via JWT token or internal service key.

JWT Token (External Clients)

curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  https://api.sgivu.com/v1/ml/predict

Internal Service Key

curl -H "X-Internal-Service-Key: YOUR_SERVICE_KEY" \
  http://sgivu-ml:8000/v1/ml/predict

Endpoints

Health Check

/health
GET
Basic health check endpoint without authentication.

Request

GET /health

Response

{
  "status": "ok",
  "version": "v1"
}

Predict Demand

/v1/ml/predict
POST
Generate demand forecast for a specific vehicle segment.
Required Permissions: sgivu.ml.predict or internal service key

Request Schema

{
  "vehicle_type": "CAR",
  "brand": "TOYOTA",
  "model": "COROLLA",
  "line": "XEI 2.0",
  "horizon_months": 6,
  "confidence": 0.95
}

Request Parameters

vehicle_type
string
required
Vehicle category: CAR or MOTORCYCLE
brand
string
required
Vehicle manufacturer (e.g., TOYOTA, HONDA, FORD)
model
string
required
Vehicle model name (e.g., COROLLA, CIVIC, F-150)
line
string
required
Specific vehicle trim/version (e.g., “XEI 2.0”, “EX-L”, “LARIAT”)
The line field is mandatory and cannot be empty. All segments must have a defined line.
horizon_months
integer
default:"6"
Number of months to forecast ahead (1-24)
  • Minimum: 1
  • Maximum: 24
  • Default: 6
confidence
float
default:"0.95"
Confidence level for prediction intervals (0.5-0.99)
  • Minimum: 0.50 (50%)
  • Maximum: 0.99 (99%)
  • Default: 0.95 (95%)
  • Common values: 0.80, 0.90, 0.95, 0.99

Response Schema

{
  "predictions": [
    {
      "month": "2026-04-01",
      "demand": 45.3,
      "lower_ci": 38.1,
      "upper_ci": 52.5
    },
    {
      "month": "2026-05-01",
      "demand": 47.8,
      "lower_ci": 40.2,
      "upper_ci": 55.4
    }
  ],
  "model_version": "20260306_143022",
  "metrics": {
    "rmse": 3.24,
    "mae": 2.15,
    "mape": 0.087,
    "r2": 0.89,
    "residual_std": 2.8
  }
}

Response Fields

predictions
array
Array of monthly forecast points
model_version
string
Timestamp-based version identifier of the model used (format: YYYYMMDD_HHMMSS)
metrics
object
Performance metrics from model training
  • rmse: Root Mean Squared Error
  • mae: Mean Absolute Error
  • mape: Mean Absolute Percentage Error
  • r2: R-squared (coefficient of determination)
  • residual_std: Standard deviation of residuals (used for CI calculation)

Example Request

curl -X POST https://api.sgivu.com/v1/ml/predict \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "vehicle_type": "CAR",
    "brand": "CHEVROLET",
    "model": "ONIX",
    "line": "LTZ 1.4",
    "horizon_months": 12,
    "confidence": 0.90
  }'

Predict with History

/v1/ml/predict-with-history
POST
Generate forecast and return historical sales data for visualization.
Required Permissions: sgivu.ml.predict or internal service key
This endpoint is ideal for building charts that show both historical trends and future predictions.

Request Schema

Identical to /predict endpoint (see above).

Response Schema

{
  "predictions": [
    {
      "month": "2026-04-01",
      "demand": 45.3,
      "lower_ci": 38.1,
      "upper_ci": 52.5
    }
  ],
  "history": [
    {
      "month": "2025-01-01",
      "sales_count": 42.0
    },
    {
      "month": "2025-02-01",
      "sales_count": 38.0
    },
    {
      "month": "2025-03-01",
      "sales_count": 44.0
    }
  ],
  "segment": {
    "vehicle_type": "CAR",
    "brand": "CHEVROLET",
    "model": "ONIX",
    "line": "LTZ 1.4"
  },
  "model_version": "20260306_143022",
  "trained_at": "2026-03-06T14:30:22.123456+00:00",
  "metrics": {
    "rmse": 3.24,
    "mae": 2.15,
    "mape": 0.087,
    "r2": 0.89,
    "residual_std": 2.8
  }
}

Additional Response Fields

history
array
Array of historical monthly sales data
segment
object
Normalized segment identifiers used for the prediction
  • vehicle_type: Canonicalized vehicle type
  • brand: Canonicalized brand name
  • model: Canonicalized model name
  • line: Canonicalized line/trim
trained_at
string
ISO 8601 timestamp when the model was trained

Example Request

curl -X POST https://api.sgivu.com/v1/ml/predict-with-history \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "vehicle_type": "MOTORCYCLE",
    "brand": "HONDA",
    "model": "CG 160",
    "line": "START",
    "horizon_months": 6,
    "confidence": 0.95
  }'

Retrain Model

/v1/ml/retrain
POST
Trigger model retraining with fresh data from the database.
Required Permissions: sgivu.ml.retrain or internal service key
Retraining is a resource-intensive operation. Use with caution in production environments.

Request Schema

{
  "start_date": "2024-01-01",
  "end_date": "2026-03-06"
}

Request Parameters

start_date
string
Start date for training data (ISO 8601 format: YYYY-MM-DD)If omitted, uses all available historical data.
end_date
string
End date for training data (ISO 8601 format: YYYY-MM-DD)If omitted, uses data up to the current date.

Response Schema

{
  "version": "20260306_150845",
  "metrics": {
    "rmse": 2.89,
    "mae": 1.92,
    "mape": 0.072,
    "r2": 0.91,
    "residual_std": 2.45
  },
  "trained_at": "2026-03-06T15:08:45.678901+00:00",
  "samples": {
    "train": 1847,
    "test": 462,
    "total": 2309
  }
}

Response Fields

version
string
Unique version identifier for the new model (timestamp-based)
metrics
object
Performance metrics from model evaluation
  • rmse: Lower is better (same units as target variable)
  • mae: Mean absolute error
  • mape: Percentage error (0.072 = 7.2%)
  • r2: Closer to 1.0 is better
  • residual_std: Used for confidence interval calculations
trained_at
string
ISO 8601 timestamp when training completed
samples
object
Dataset split information
  • train: Number of samples used for training
  • test: Number of samples used for evaluation
  • total: Total samples in dataset

Example Requests

# Retrain with all available data
curl -X POST https://api.sgivu.com/v1/ml/retrain \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}'

Get Latest Model

/v1/ml/models/latest
GET
Retrieve metadata for the currently active model.
Required Permissions: sgivu.ml.models or internal service key

Request

GET /v1/ml/models/latest

Response Schema

{
  "version": "20260306_143022",
  "trained_at": "2026-03-06T14:30:22.123456+00:00",
  "target": "sales_count",
  "features": [
    "vehicle_type",
    "brand",
    "model",
    "line",
    "purchases_count",
    "avg_margin",
    "avg_sale_price",
    "avg_purchase_price",
    "avg_days_inventory",
    "inventory_rotation",
    "lag_1",
    "lag_3",
    "lag_6",
    "rolling_mean_3",
    "rolling_mean_6",
    "month",
    "year",
    "month_sin",
    "month_cos"
  ],
  "metrics": {
    "rmse": 3.24,
    "mae": 2.15,
    "mape": 0.087,
    "r2": 0.89,
    "residual_std": 2.8
  },
  "candidates": [
    {
      "model": "linear_regression",
      "rmse": 4.12,
      "mae": 3.05,
      "mape": 0.124,
      "r2": 0.76,
      "samples": 462
    },
    {
      "model": "random_forest",
      "rmse": 3.45,
      "mae": 2.31,
      "mape": 0.095,
      "r2": 0.85,
      "samples": 462
    },
    {
      "model": "xgboost",
      "rmse": 3.24,
      "mae": 2.15,
      "mape": 0.087,
      "r2": 0.89,
      "samples": 462
    }
  ],
  "train_samples": 1847,
  "test_samples": 462,
  "total_samples": 2309
}

Response Fields

version
string
Model version identifier
trained_at
string
Training completion timestamp
target
string
Target variable name (typically sales_count)
features
array
List of feature names used by the model
metrics
object
Performance metrics of the selected best model
candidates
array
Comparison of all evaluated models during trainingShows which algorithm performed best and by how much.
train_samples
integer
Number of samples in training set
test_samples
integer
Number of samples in test set
total_samples
integer
Total dataset size

Example

curl https://api.sgivu.com/v1/ml/models/latest \
  -H "Authorization: Bearer YOUR_TOKEN"

Error Responses

All endpoints follow consistent error response format:
{
  "detail": "Error message describing what went wrong"
}

Common Error Codes

400 Bad Request
Invalid input parameters or missing required fields
{"detail": "Falta la línea del vehículo. Incluye brand/model/line completos para predecir."}
401 Unauthorized
Missing or invalid authentication token
{"detail": "Invalid token or authentication required"}
403 Forbidden
Insufficient permissions for the requested operation
{"detail": "Missing required permission: sgivu.ml.retrain"}
404 Not Found
Requested resource doesn’t exist
{"detail": "No se encontró historial para la combinación solicitada."}
422 Unprocessable Entity
Validation error in request payload
{
  "detail": [
    {
      "loc": ["body", "horizon_months"],
      "msg": "ensure this value is less than or equal to 24",
      "type": "value_error.number.not_le"
    }
  ]
}
500 Internal Server Error
Unexpected server error (check logs)
{"detail": "Aún no existe un modelo entrenado."}

Rate Limiting

Rate limiting is typically handled at the API gateway level. Check gateway documentation for specific limits.

OpenAPI Specification

The complete OpenAPI 3.0 specification is available at:
GET /openapi.json
You can import this into Postman, Insomnia, or other API clients for automatic request generation.

SDK Examples

For more comprehensive examples and client library usage, see:

Next Steps

Try the API

Test endpoints using the interactive docs at /docs

Understanding Predictions

Learn how forecasts are generated

Model Versioning

Manage and compare model versions

Authentication

Configure JWT and permissions