Skip to content

Classify

Automatically classify text using a custom Text Classifier ML model trained on your data.

Perfect for applying consistent labels to text (articles, video/audio transcripts, tickets, emails, reviews, comments, etc.) based on historical patterns in your data plus the semantic meaning of your text.

Example Use Cases
  • Assign labels to video/audio transcripts
  • Assign categories to product descriptions
  • Classify user reviews/comments by sentiment
  • Categorize customer feedback by topic or product
  • Flag urgent vs non-urgent customer inquiries
  • Detect spam in emails or user posts
  • Route support tickets to the right team (technical, billing, sales)
  • Assign topic to documents or articles
Categorize vs. Classify vs. Predict

See this page for details on selecting the right endpoint for your classification task.

Endpoint

POST /v20241104/classify

API Request

  • Required Parameters


    input object

    JSON object specifying a document_id or a text string to classify.

    Info
    • Example (document ID):

      "input": {
        "type": "document_id",
        "value": "4nD1gZIB7caKVIeL2MgL"
      }
      

    • Example (text string):

      "input": {
        "type": "text",
        "value": "Server is down, customers cannot access the service"
      }
      

    • For document ID:

      MinLength: 1   MaxLength: 128

    • For text string:

      MinLength: 1   MaxLength: 5000

    • Text strings have a max length (characters) specified above. To classify longer texts, first add them as a document and then classify them using their document_id.


    model_id string required

    ID of your custom ML model to use for classification.

    Info
    • You can find the model ID in your Gainly Dashboard under Settings > Custom Models.

    MinLength: 1   MaxLength: 128


    Optional Parameters


    max_labels integer

    Maximum number of labels (classifications) to assign.

    Default is 3.

    Min: 1   Max: 10


    version string required

    Version of your custom ML model to use for classification. Default is default.

    Info
    • You can find the version number in your Gainly Dashboard under Settings > Custom Models.
    • You can also mark a version as default in your Gainly Dashboard.

    • Examples:

      "version": "2"
      
      "version": "default"
      

    MinLength: 1   MaxLength: 10

  • POST /v20241104/classify


    curl -X POST "https://api.gainly.ai/v20241104/classify" \
      -H "Content-Type: application/json" \
      -H "X-API-Key: YOUR_API_KEY_HERE" \  # (1)!
      -d '{
        "input": {
          "type": "text",
          "value": "I love my original Listerine. This came properly packaged so it didn\'t leak. What more can I say. Kills germs by the millions. Great for use with my waterpick and I feel so clean."
        },
        "model_id": "support_priority_v1"
      }'
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    # Prompt for AI coding assistants/IDEs (e.g., ChatGPT, Claude, GitHub Copilot, Cursor, Windsurf)
    
    Using the Gainly API:
    1. Write code to call the classify operation (see OpenAPI spec: https://api.gainly.ai/v20241104/openapi.json)
    2. Implement authentication using the header "X-API-Key" as described in the docs: https://docs.gainly.ai/latest/api-reference/authentication/
    3. Implement rate limit handling as described in the docs: https://docs.gainly.ai/latest/api-reference/rate-limits/
    4. Implement error handling
    5. Handle the response according to the ClassifyResults schema in the OpenAPI spec
    
    using System.Net.Http;
    using System.Text.Json;
    using System.Text;
    
    var client = new HttpClient();
    
    var url = "https://api.gainly.ai/v20241104/classify";
    
    var payload = new {
        input = new {
            type = "text",
            value = "Server is down, customers cannot access the service"
        },
        model_id = "support_priority_v1"
    };
    
    var content = new StringContent(
        JsonSerializer.Serialize(payload),
        Encoding.UTF8,
        "application/json"
    );
    
    client.DefaultRequestHeaders.Add("X-API-Key", "YOUR_API_KEY_HERE"); // (1)!
    
    var response = await client.PostAsync(url, content);
    var result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "net/http"
    )
    
    func main() {
        url := "https://api.gainly.ai/v20241104/classify"
    
        payload := map[string]interface{}{
            "input": map[string]interface{}{
                "type": "text",
                "value": "Server is down, customers cannot access the service",
            },
            "model_id": "support_priority_v1",
        }
    
        jsonData, _ := json.Marshal(payload)
    
        req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("X-API-Key", "YOUR_API_KEY_HERE") // (1)!
    
        resp, _ := http.DefaultClient.Do(req)
        defer resp.Body.Close()
    
        var result map[string]interface{}
        json.NewDecoder(resp.Body).Decode(&result)
        fmt.Println(result)
    }
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.net.URI;
    
    var client = HttpClient.newHttpClient();
    
    var url = "https://api.gainly.ai/v20241104/classify";
    
    var payload = """
        {
            "input": {
                "type": "text",
                "value": "Server is down, customers cannot access the service"
            },
            "model_id": "support_priority_v1"
        }
        """;
    
    var request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .header("Content-Type", "application/json")
        .header("X-API-Key", "YOUR_API_KEY_HERE") // (1)!
        .POST(HttpRequest.BodyPublishers.ofString(payload))
        .build();
    
    var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    const axios = require('axios');  // or: import axios from 'axios';
    
    const url = 'https://api.gainly.ai/v20241104/classify';
    
    const payload = {
        input: {
            type: "text",
            value: "Server is down, customers cannot access the service"
        },
        model_id: "support_priority_v1"
    };
    
    const headers = {
        'Content-Type': 'application/json',
        'X-API-Key': 'YOUR_API_KEY_HERE' // (1)!
    };
    
    axios.post(url, payload, { headers })
        .then(response => console.log(response.data))
        .catch(error => console.error('Error:', error.message));
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    <?php
    
    $client = new \GuzzleHttp\Client();
    
    $url = 'https://api.gainly.ai/v20241104/classify';
    
    $payload = [
        'input' => [
            'type' => 'text',
            'value' => 'I love my original Listerine. This came properly packaged so it didn\'t leak. What more can I say. Kills germs by the millions. Great for use with my waterpick and I feel so clean.',
        ],
        'model_id' => 'support_priority_v1',
    ];
    
    $response = $client->request('POST', $url, [
        'json' => $payload,
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => 'YOUR_API_KEY_HERE' # (1)!
        ],
    ]);
    
    echo $response->getBody();
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    import requests
    
    url = "https://api.gainly.ai/v20241104/classify"
    
    payload = {
        "input": {
            "type": "text",
            "value": "Server is down, customers cannot access the service"
        },
        "model_id": "support_priority_v1"
    }
    
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": "YOUR_API_KEY_HERE" # (1)!
    }
    
    response = requests.post(url, json=payload, headers=headers)
    data = response.json()
    print(data)
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    require 'json'
    require 'uri'
    require 'net/http'
    require 'openssl'
    
    url = URI('https://api.gainly.ai/v20241104/classify')
    
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    
    request = Net::HTTP::Post.new(url)
    request['Content-Type'] = 'application/json'
    request['X-API-Key'] = 'YOUR_API_KEY_HERE' # (1)!
    request.body = {
        input: {
            type: "text",
            value: "Server is down, customers cannot access the service"
        },
        model_id: "support_priority_v1"
    }.to_json
    
    response = http.request(request)
    puts response.read_body
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.

API Response

{
    "object": "classify_result",
    "url": "/v20241104/classify",
    "data": [
      {
        "label": "urgent",
        "confidence_score": 0.89,
        "alternatives": [
            {
                "label": "normal",
                "confidence_score": 0.08
            },
            {
                "label": "low",
                "confidence_score": 0.03
            }
        ]
      }
    ],
    "input": {
        "type": "text",
        "value": "Server is down, customers cannot access the service"
    },
    "model_id": "support_priority_v1",
    "version": "default",
    "max_labels": 3,
    "token_usage": {
        "semantic_tokens": 69,
        "llm_tokens": {
            "llm_output_tokens": 0,
            "llm_input_tokens": 0,
            "model": null
        }
    },
    "livemode": true
}

Label

label indicates the classification assigned by the custom model to the input text. confidence_score is the probability score (0-1) assigned by the custom model to the predicted label. alternatives is a list of other possible labels along with their corresponding probability scores.

"data": [
    {
        "label": "urgent",          // The predicted label
        "confidence_score": 0.89,   // Confidence score (0-1)
        "alternatives": [           // Optional: other possible labels
            {
                "label": "normal",
                "confidence_score": 0.08
            },
            {
                "label": "low",
                "confidence_score": 0.03
            }
        ]
    }
],

This example is from a model that was trained to assign a priority to support tickets based on the ticket text, and assigns a label of urgent, normal or low.