TrainLab AI API Documentation
Overview​
The TrainLab AI API provides access to machine learning models across various tasks including text processing, computer vision, and tabular data analysis. This documentation covers all supported endpoints and integration methods.
Base URL​
https://api.trainlab.ai/v1
Authentication​
All API requests require authentication using an API key in the header:
X-API-Key: your_api_key_here
Getting Your API Key​
- Deploy a model in the TrainLab AI platform
- Navigate to the API Access tab for your deployment
- Copy the generated API key
- Use the key in all API requests
Common Response Format​
All endpoints return responses in the following format:
{
"success": true,
"result": {
// Task-specific results
},
"request_id": "req_12345",
"model_id": "deployment_id",
"usage": {
"tokens_used": 150
}
}
Supported Tasks​
1. Chat Assistant Training (llm:sft)​
OpenAI-compatible chat completions endpoint for conversational AI models.
Endpoint​
POST /api/v1/chat/completions
Headers​
X-API-Key: your_api_key_here
Content-Type: application/json
Request Body​
{
"deployment": "your_deployment_id",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is artificial intelligence?"
}
],
"session": "session-12345-abcdef",
"max_tokens": 512,
"temperature": 0.7,
"top_p": 1.0,
"stream": false
}
Response​
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677652288,
"model": "sft-27",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 45,
"total_tokens": 60
}
}
Parameters​
deployment(string, required): Your deployment IDmessages(array, required): Conversation messagessession(string, optional): Session ID for conversation continuitymax_tokens(integer, optional): Maximum response tokens (default: 512)temperature(float, optional): Sampling temperature 0-1 (default: 0.7)top_p(float, optional): Nucleus sampling parameter (default: 1.0)stream(boolean, optional): Enable streaming responses (default: false)
2. Text Classification​
Classify text into predefined categories.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"text": "I love this product! It works perfectly and exceeded my expectations.",
"return_probabilities": true
}
}
Response​
{
"success": true,
"result": {
"predicted_class": 1,
"predicted_label": "positive",
"confidence": 0.89,
"probabilities": {
"positive": 0.89,
"negative": 0.11
}
}
}
Parameters​
text(string, required): Text to classifyreturn_probabilities(boolean, optional): Include class probabilities
3. Text Similarity Matching (st:pair)​
Compare semantic similarity between two texts.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"anchor": "The weather is sunny today",
"positive": "It's a bright and sunny day",
"similarity_threshold": 0.7
}
}
Response​
{
"success": true,
"result": {
"similarity_score": 0.85,
"is_similar": true,
"confidence": 0.92
}
}
4. Image Classification​
Classify images into predefined categories.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA...",
"return_probabilities": true
}
}
Response​
{
"success": true,
"result": {
"predicted_class": "cat",
"confidence": 0.94,
"probabilities": {
"cat": 0.94,
"dog": 0.06
}
}
}
Parameters​
image_base64(string, required): Base64 encoded image with data URI prefixreturn_probabilities(boolean, optional): Include class probabilities
5. Image Description Generator (vlm:captioning)​
Generate natural language descriptions of images.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA...",
"max_length": 100,
"temperature": 0.7
}
}
Response​
{
"success": true,
"result": {
"caption": "A brown dog sitting in a green park with trees in the background",
"confidence": 0.87
}
}
6. Visual Question Answering (vlm:vqa)​
Answer questions about image content.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA...",
"question": "What color is the car in the image?",
"max_length": 50
}
}
Response​
{
"success": true,
"result": {
"answer": "The car is red",
"confidence": 0.91
}
}
7. Document Question Answering (extractive-qa)​
Extract answers from document text based on questions.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"context": "TrainLab AI is a machine learning platform that enables users to train and deploy custom AI models without requiring extensive technical expertise.",
"question": "What is TrainLab AI?",
"max_answer_length": 100
}
}
Response​
{
"success": true,
"result": {
"answer": "a machine learning platform",
"confidence": 0.95,
"start_position": 12,
"end_position": 40
}
}
8. Structured Data Classification (tabular:classification)​
Classify structured/tabular data.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"Currency": "USD",
"Event": "Manufacturing PMI",
"Value": 52.5,
"Previous": 51.2,
"Forecast": 52.0,
"return_probabilities": true
}
}
Response​
{
"success": true,
"result": {
"predicted_class": "positive_impact",
"confidence": 0.78,
"probabilities": {
"positive_impact": 0.78,
"negative_impact": 0.15,
"neutral": 0.07
}
}
}
9. Structured Data Prediction (tabular:regression)​
Predict numerical values from structured data.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"Currency": "EUR",
"Event": "GDP Growth",
"Previous": 2.1,
"Forecast": 2.3,
"return_confidence": true,
"confidence_level": 0.95
}
}
Response​
{
"success": true,
"result": {
"predicted_value": 2.45,
"confidence_interval": [2.12, 2.78],
"confidence_level": 0.95
}
}
10. Named Entity Recognition (token-classification)​
Extract named entities from text.
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"text": "Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976.",
"return_confidence": true
}
}
Response​
{
"success": true,
"result": {
"entities": [
{
"text": "Apple Inc.",
"label": "ORG",
"start": 0,
"end": 10,
"confidence": 0.99
},
{
"text": "Steve Jobs",
"label": "PERSON",
"start": 25,
"end": 35,
"confidence": 0.97
},
{
"text": "Cupertino",
"label": "LOCATION",
"start": 39,
"end": 48,
"confidence": 0.95
}
]
}
}
12. Text Transformation​
Transform text (translation, summarization, etc.).
Endpoint​
POST /api/v1/inference
Request Body​
{
"deployment": "your_deployment_id",
"inputs": {
"text": "Translate this text to French: Hello, how are you today?",
"max_length": 100,
"temperature": 0.3
}
}
Response​
{
"success": true,
"result": {
"transformed_text": "Bonjour, comment allez-vous aujourd'hui?",
"confidence": 0.92
}
}
Batch Processing​
Process multiple inputs in a single request for better efficiency.
Endpoint​
POST /api/v1/inference/batch
Request Body​
{
"deployment": "your_deployment_id",
"batch_inputs": [
{
"text": "First text to classify"
},
{
"text": "Second text to classify"
},
{
"text": "Third text to classify"
}
]
}
Response​
{
"success": true,
"results": [
{
"predicted_class": 1,
"predicted_label": "positive",
"confidence": 0.89
},
{
"predicted_class": 0,
"predicted_label": "negative",
"confidence": 0.76
},
{
"predicted_class": 1,
"predicted_label": "positive",
"confidence": 0.93
}
],
"batch_size": 3
}
Code Examples​
Python​
import requests
import json
import base64
from PIL import Image
import io
# API Configuration
api_key = "your_api_key_here"
deployment_id = "your_deployment_id"
# Text Classification Example
def classify_text(text):
url = "https://api.trainlab.ai/v1/inference"
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
data = {
"deployment": deployment_id,
"inputs": {
"text": text,
"return_probabilities": True
}
}
response = requests.post(url, headers=headers, json=data)
return response.json()
# Image Classification Example
def classify_image(image_path):
# Convert image to base64
with Image.open(image_path) as img:
if img.mode != 'RGB':
img = img.convert('RGB')
buffer = io.BytesIO()
img.save(buffer, format='JPEG')
img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
image_data = f"data:image/jpeg;base64,{img_base64}"
url = "https://api.trainlab.ai/v1/inference"
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
data = {
"deployment": deployment_id,
"inputs": {
"image_base64": image_data,
"return_probabilities": True
}
}
response = requests.post(url, headers=headers, json=data)
return response.json()
# Chat API Example
def chat_completion(messages):
url = "https://api.trainlab.ai/v1/chat/completions"
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
data = {
"deployment": deployment_id,
"messages": messages,
"max_tokens": 512,
"temperature": 0.7
}
response = requests.post(url, headers=headers, json=data)
return response.json()
# Usage examples
result = classify_text("This product is amazing!")
print(result)
# Chat example
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain machine learning in simple terms."}
]
chat_result = chat_completion(messages)
print(chat_result)
JavaScript​
const apiKey = 'your_api_key_here';
const deploymentId = 'your_deployment_id';
// Text Classification
async function classifyText(text) {
const response = await fetch('https://api.trainlab.ai/v1/inference', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
deployment: deploymentId,
inputs: {
text: text,
return_probabilities: true
}
})
});
return await response.json();
}
// Image Classification with File Upload
async function classifyImage(imageFile) {
// Convert image to base64
const base64 = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(imageFile);
});
const response = await fetch('https://api.trainlab.ai/v1/inference', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
deployment: deploymentId,
inputs: {
image_base64: base64,
return_probabilities: true
}
})
});
return await response.json();
}
// Chat Completion
async function chatCompletion(messages) {
const response = await fetch('https://api.trainlab.ai/v1/chat/completions', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
deployment: deploymentId,
messages: messages,
max_tokens: 512,
temperature: 0.7
})
});
return await response.json();
}
// Usage
classifyText('This is a great product!').then(console.log);
cURL​
# Text Classification
curl -X POST "https://api.trainlab.ai/v1/inference" \
-H "X-API-Key: your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"deployment": "your_deployment_id",
"inputs": {
"text": "This product is amazing!",
"return_probabilities": true
}
}'
# Chat Completion
curl -X POST "https://api.trainlab.ai/v1/chat/completions" \
-H "X-API-Key: your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"deployment": "your_deployment_id",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is machine learning?"}
],
"max_tokens": 512,
"temperature": 0.7
}'
# Batch Processing
curl -X POST "https://api.trainlab.ai/v1/inference/batch" \
-H "X-API-Key: your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"deployment": "your_deployment_id",
"batch_inputs": [
{"text": "First text"},
{"text": "Second text"},
{"text": "Third text"}
]
}'
Error Handling​
The API returns standard HTTP status codes with detailed error messages:
Error Response Format​
{
"success": false,
"error": {
"code": "INVALID_INPUT",
"message": "The input text is too long. Maximum length is 10,000 characters.",
"details": {
"field": "text",
"max_length": 10000,
"provided_length": 15000
}
}
}
Common Error Codes​
400 Bad Request- Invalid input parameters401 Unauthorized- Invalid or missing API key403 Forbidden- Deployment not accessible404 Not Found- Deployment not found429 Too Many Requests- Rate limit exceeded500 Internal Server Error- Server error
Rate Limits​
Rate limits are enforced per API key:
- Default: 1000 requests per hour
- Enterprise: Custom limits available
Rate limit headers are included in responses:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642694400
Best Practices​
-
Handle Images Efficiently: For image inputs, ensure images are reasonably sized (< 10MB) and in supported formats (JPEG, PNG)
-
Use Batch Processing: For multiple inputs, use the batch endpoint to reduce latency and costs
-
Implement Retry Logic: Handle temporary failures with exponential backoff
-
Cache Results: Cache prediction results when appropriate to reduce API calls
-
Monitor Usage: Track your API usage to stay within rate limits
-
Validate Inputs: Always validate input data before sending to the API
Support​
- Documentation: docs.trainlab.ai
- Support Email: [email protected]