> This page is for version v1 API.
> For other versions, use one of these documentation indexes:
> - v2 API (default): https://docs.cohere.com/v2/llms.txt
> - v1 API: https://docs.cohere.com/v1/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.cohere.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.cohere.com/_mcp/server.

# Classify

POST https://api.cohere.com/v1/classify
Content-Type: application/json

This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided `examples` of text + label pairs as a reference.
Note: [Fine-tuned models](https://docs.cohere.com/docs/classify-fine-tuning) trained on classification examples don't require the `examples` parameter to be passed in explicitly.

Reference: https://docs.cohere.com/reference/classify

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication of the form `Bearer <token>`, where token is your auth token.

## Request

### Headers

- `X-Client-Name` (string, optional) — The name of the project that is making the request.

### Body (application/json)

This endpoint expects an object.

- `inputs` (list of string, required) — A list of up to 96 texts to be classified. Each one must be a non-empty string. There is, however, no consistent, universal limit to the length a particular input can be. We perform classification on the first `x` tokens of each input, and `x` varies depending on which underlying model is powering classification. The maximum token length for each model is listed in the "max tokens" column [here](https://docs.cohere.com/docs/models). Note: by default the `truncate` parameter is set to `END`, so tokens exceeding the limit will be automatically dropped. This behavior can be disabled by setting `truncate` to `NONE`, which will result in validation errors for longer texts.
- `examples` (list of ClassifyExample, optional) — An array of examples to provide context to the model. Each example is a text string and its associated label/class. Each unique label requires at least 2 examples associated with it; the maximum number of examples is 2500, and each example has a maximum length of 512 tokens. The values should be structured as `{text: "...",label: "..."}`. Note: [Fine-tuned Models](https://docs.cohere.com/docs/classify-fine-tuning) trained on classification examples don't require the `examples` parameter to be passed in explicitly.
- `model` (string, optional) — ID of a [Fine-tuned](https://docs.cohere.com/v2/docs/classify-starting-the-training) Classify model
- `truncate` (enum, optional, default: END) — One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned.
  - Allowed values: `NONE`, `START`, `END`
- `preset` (string, optional, deprecated) — The ID of a custom playground preset. You can create presets in the [playground](https://dashboard.cohere.com/playground). If you use a preset, all other parameters become optional, and any included parameters will override the preset's parameters.

## Response

### 200

OK

- `id` (string, required)
- `classifications` (list of V1ClassifyPostResponsesContentApplicationJsonSchemaClassificationsItems, required)
- `meta` (ApiMeta, optional)

## Errors

### 400 Bad Request Error

This error is returned when the request is not well formed. This could be because: - JSON is invalid - The request is missing required fields - The request contains an invalid combination of fields

- `message` (string, optional)
- `id` (string, optional)

### 401 Unauthorized Error

This error indicates that the operation attempted to be performed is not allowed. This could be because: - The api token is invalid - The user does not have the necessary permissions

- `message` (string, optional)
- `id` (string, optional)

### 403 Forbidden Error

This error indicates that the operation attempted to be performed is not allowed. This could be because: - The api token is invalid - The user does not have the necessary permissions

- `message` (string, optional)
- `id` (string, optional)

### 404 Not Found Error

This error is returned when a resource is not found. This could be because: - The endpoint does not exist - The resource does not exist eg model id, dataset id

- `message` (string, optional)
- `id` (string, optional)

### 422 Unprocessable Entity Error

This error is returned when the request is not well formed. This could be because: - JSON is invalid - The request is missing required fields - The request contains an invalid combination of fields

- `message` (string, optional)
- `id` (string, optional)

### 429 Too Many Requests Error

Too many requests

- `message` (string, optional)
- `id` (string, optional)

### 498 Invalid Token Error

This error is returned when a request or response contains a deny-listed token.

- `message` (string, optional)
- `id` (string, optional)

### 499 Client Closed Request Error

This error is returned when a request is cancelled by the user.

- `message` (string, optional)
- `id` (string, optional)

### 500 Internal Server Error

This error is returned when an uncategorised internal server error occurs.

- `message` (string, optional)
- `id` (string, optional)

### 501 Not Implemented Error

This error is returned when the requested feature is not implemented.

- `message` (string, optional)
- `id` (string, optional)

### 503 Service Unavailable Error

This error is returned when the service is unavailable. This could be due to: - Too many users trying to access the service at the same time

- `message` (string, optional)
- `id` (string, optional)

### 504 Gateway Timeout Error

This error is returned when a request to the server times out. This could be due to: - An internal services taking too long to respond

- `message` (string, optional)
- `id` (string, optional)

## Types

### ClassifyExample

- `text` (string, optional)
- `label` (string, optional)

### V1ClassifyPostResponsesContentApplicationJsonSchemaClassificationsItems

- `id` (string, required)
- `predictions` (list of string, required) — An array containing the predicted labels for the associated query (only filled for single-label classification)
- `confidences` (list of double, required) — An array containing the confidence scores of all the predictions in the same order
- `labels` (map from string to V1ClassifyPostResponsesContentApplicationJsonSchemaClassificationsItemsLabels, required) — A map containing each label and its confidence score according to the classifier. All the confidence scores add up to 1 for single-label classification. For multi-label classification the label confidences are independent of each other, so they don't have to sum up to 1.
- `classification_type` (enum, required) — The type of classification performed
  - Allowed values: `single-label`, `multi-label`
- `input` (string, optional) — The input text that was classified
- `prediction` (string, optional, deprecated) — The predicted label for the associated query (only filled for single-label models)
- `confidence` (double, optional, deprecated) — The confidence score for the top predicted class (only filled for single-label classification)

### ApiMeta

- `api_version` (ApiMetaApiVersion, optional)
- `billed_units` (ApiMetaBilledUnits, optional)
- `tokens` (ApiMetaTokens, optional)
- `cached_tokens` (double, optional) — The number of prompt tokens that hit the inference cache.
- `warnings` (list of string, optional)

### V1ClassifyPostResponsesContentApplicationJsonSchemaClassificationsItemsLabels

- `confidence` (double, optional)

### ApiMetaApiVersion

- `version` (string, required)
- `is_deprecated` (boolean, optional)
- `is_experimental` (boolean, optional)

### ApiMetaBilledUnits

- `images` (double, optional) — The number of billed images.
- `input_tokens` (double, optional) — The number of billed input tokens.
- `image_tokens` (double, optional) — The number of billed image tokens.
- `output_tokens` (double, optional) — The number of billed output tokens.
- `search_units` (double, optional) — The number of billed search units.
- `classifications` (double, optional) — The number of billed classifications units.
- `pages` (double, optional) — The number of billed pages parsed.

### ApiMetaTokens

- `input_tokens` (double, optional) — The number of tokens used as input to the model.
- `output_tokens` (double, optional) — The number of tokens produced by the model.

## Examples

**Request**

```json
{
  "inputs": [
    "Confirm your email address",
    "hey i need u to send some $"
  ],
  "examples": [
    {
      "text": "Dermatologists don't like her!",
      "label": "Spam"
    },
    {
      "text": "'Hello, open to this?'",
      "label": "Spam"
    },
    {
      "text": "I need help please wire me $1000 right now",
      "label": "Spam"
    },
    {
      "text": "Nice to know you ;)",
      "label": "Spam"
    },
    {
      "text": "Please help me?",
      "label": "Spam"
    },
    {
      "text": "Your parcel will be delivered today",
      "label": "Not spam"
    },
    {
      "text": "Review changes to our Terms and Conditions",
      "label": "Not spam"
    },
    {
      "text": "Weekly sync notes",
      "label": "Not spam"
    },
    {
      "text": "'Re: Follow up from today's meeting'",
      "label": "Not spam"
    },
    {
      "text": "Pre-read for tomorrow",
      "label": "Not spam"
    }
  ],
  "model": "YOUR-FINE-TUNED-MODEL-ID"
}
```

**Response**

```json
{
  "id": "86886163-b3f3-4e36-8554-60eca7696216",
  "classifications": [
    {
      "id": "842d12fe-934b-4b71-82c2-c581eca00718",
      "predictions": [
        "Not spam"
      ],
      "confidences": [
        0.5661598
      ],
      "labels": {
        "Not spam": {
          "confidence": 0.5661598
        },
        "Spam": {
          "confidence": 0.43384025
        }
      },
      "classification_type": "single-label",
      "input": "Confirm your email address",
      "prediction": "Not spam",
      "confidence": 0.5661598
    },
    {
      "id": "e1a39b3e-1ecd-41d2-be75-90ed726f7b9e",
      "predictions": [
        "Spam"
      ],
      "confidences": [
        0.9909811
      ],
      "labels": {
        "Not spam": {
          "confidence": 0.009018883
        },
        "Spam": {
          "confidence": 0.9909811
        }
      },
      "classification_type": "single-label",
      "input": "hey i need u to send some $",
      "prediction": "Spam",
      "confidence": 0.9909811
    }
  ],
  "meta": {
    "api_version": {
      "version": "1"
    },
    "billed_units": {
      "classifications": 2
    }
  }
}
```

**SDK Code**

```go Cohere Go SDK
package main

import (
	"context"
	"log"
	"os"

	cohere "github.com/cohere-ai/cohere-go/v2"
	client "github.com/cohere-ai/cohere-go/v2/client"
)

func main() {
	co := client.NewClient(client.WithToken(os.Getenv("CO_API_KEY")))
	model := "<YOUR-FINE-TUNED-MODEL-ID>"

	resp, err := co.Classify(
		context.TODO(),
		&cohere.ClassifyRequest{
			Model: &model,
			Examples: []*cohere.ClassifyExample{
				{
					Text:  cohere.String("orange"),
					Label: cohere.String("fruit"),
				},
				{
					Text:  cohere.String("pear"),
					Label: cohere.String("fruit"),
				},
				{
					Text:  cohere.String("lettuce"),
					Label: cohere.String("vegetable"),
				},
				{
					Text:  cohere.String("cauliflower"),
					Label: cohere.String("vegetable"),
				},
			},
			Inputs: []string{"peach"},
		},
	)

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("%+v", resp)
}

```

```typescript Cohere TypeScript SDK
import { CohereClient } from 'cohere-ai';

const cohere = new CohereClient({});

(async () => {
  const classify = await cohere.classify({
    model: '<YOUR-FINE-TUNED-MODEL-ID>',
    examples: [
      { text: "Dermatologists don't like her!", label: 'Spam' },
      { text: "'Hello, open to this?'", label: 'Spam' },
      { text: 'I need help please wire me $1000 right now', label: 'Spam' },
      { text: 'Nice to know you ;)', label: 'Spam' },
      { text: 'Please help me?', label: 'Spam' },
      { text: 'Your parcel will be delivered today', label: 'Not spam' },
      { text: 'Review changes to our Terms and Conditions', label: 'Not spam' },
      { text: 'Weekly sync notes', label: 'Not spam' },
      { text: "'Re: Follow up from today's meeting'", label: 'Not spam' },
      { text: 'Pre-read for tomorrow', label: 'Not spam' },
    ],
    inputs: ['Confirm your email address', 'hey i need u to send some $'],
  });

  console.log(classify);
})();

```

```python Sync
import cohere
from cohere import ClassifyExample

co = cohere.Client()
examples = [
    ClassifyExample(text="Dermatologists don't like her!", label="Spam"),
    ClassifyExample(text="'Hello, open to this?'", label="Spam"),
    ClassifyExample(text="I need help please wire me $1000 right now", label="Spam"),
    ClassifyExample(text="Nice to know you ;)", label="Spam"),
    ClassifyExample(text="Please help me?", label="Spam"),
    ClassifyExample(text="Your parcel will be delivered today", label="Not spam"),
    ClassifyExample(
        text="Review changes to our Terms and Conditions", label="Not spam"
    ),
    ClassifyExample(text="Weekly sync notes", label="Not spam"),
    ClassifyExample(text="'Re: Follow up from today's meeting'", label="Not spam"),
    ClassifyExample(text="Pre-read for tomorrow", label="Not spam"),
]
inputs = [
    "Confirm your email address",
    "hey i need u to send some $",
]
response = co.classify(
    model="<YOUR-FINE-TUNED-MODEL-ID>",
    inputs=inputs,
    examples=examples,
)
print(response)

```

```python Async
import cohere
import asyncio
from cohere import ClassifyExample

co = cohere.AsyncClient()
examples = [
    ClassifyExample(text="Dermatologists don't like her!", label="Spam"),
    ClassifyExample(text="'Hello, open to this?'", label="Spam"),
    ClassifyExample(text="I need help please wire me $1000 right now", label="Spam"),
    ClassifyExample(text="Nice to know you ;)", label="Spam"),
    ClassifyExample(text="Please help me?", label="Spam"),
    ClassifyExample(text="Your parcel will be delivered today", label="Not spam"),
    ClassifyExample(
        text="Review changes to our Terms and Conditions", label="Not spam"
    ),
    ClassifyExample(text="Weekly sync notes", label="Not spam"),
    ClassifyExample(text="'Re: Follow up from today's meeting'", label="Not spam"),
    ClassifyExample(text="Pre-read for tomorrow", label="Not spam"),
]
inputs = [
    "Confirm your email address",
    "hey i need u to send some $",
]


async def main():
    response = await co.classify(
        model="<YOUR-FINE-TUNED-MODEL-ID>",
        inputs=inputs,
        examples=examples,
    )
    print(response)


asyncio.run(main())

```

```java Cohere java SDK
/* (C)2024 */
import com.cohere.api.Cohere;
import com.cohere.api.requests.ClassifyRequest;
import com.cohere.api.types.ClassifyExample;
import com.cohere.api.types.ClassifyResponse;
import java.util.List;

public class ClassifyPost {
  public static void main(String[] args) {
    Cohere cohere = Cohere.builder().clientName("snippet").build();

    ClassifyResponse response =
        cohere.classify(
            ClassifyRequest.builder()
                .addAllInputs(List.of("Confirm your email address", "hey i need u to send some $"))
                .examples(
                    List.of(
                        ClassifyExample.builder()
                            .text("Dermatologists don't like her!")
                            .label("Spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("'Hello, open to this?'")
                            .label("Spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("I need help please wire me $1000" + " right now")
                            .label("Spam")
                            .build(),
                        ClassifyExample.builder().text("Nice to know you ;)").label("Spam").build(),
                        ClassifyExample.builder().text("Please help me?").label("Spam").build(),
                        ClassifyExample.builder()
                            .text("Your parcel will be delivered today")
                            .label("Not spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("Review changes to our Terms and" + " Conditions")
                            .label("Not spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("Weekly sync notes")
                            .label("Not spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("'Re: Follow up from today's" + " meeting'")
                            .label("Not spam")
                            .build(),
                        ClassifyExample.builder()
                            .text("Pre-read for tomorrow")
                            .label("Not spam")
                            .build()))
                .build());

    System.out.println(response);
  }
}

```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.cohere.com/v1/classify")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"inputs\": [\n    \"Confirm your email address\",\n    \"hey i need u to send some $\"\n  ],\n  \"examples\": [\n    {\n      \"text\": \"Dermatologists don't like her!\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"'Hello, open to this?'\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"I need help please wire me $1000 right now\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Nice to know you ;)\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Please help me?\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Your parcel will be delivered today\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Review changes to our Terms and Conditions\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Weekly sync notes\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"'Re: Follow up from today's meeting'\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Pre-read for tomorrow\",\n      \"label\": \"Not spam\"\n    }\n  ],\n  \"model\": \"YOUR-FINE-TUNED-MODEL-ID\"\n}"

response = http.request(request)
puts response.read_body
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.cohere.com/v1/classify', [
  'body' => '{
  "inputs": [
    "Confirm your email address",
    "hey i need u to send some $"
  ],
  "examples": [
    {
      "text": "Dermatologists don\'t like her!",
      "label": "Spam"
    },
    {
      "text": "\'Hello, open to this?\'",
      "label": "Spam"
    },
    {
      "text": "I need help please wire me $1000 right now",
      "label": "Spam"
    },
    {
      "text": "Nice to know you ;)",
      "label": "Spam"
    },
    {
      "text": "Please help me?",
      "label": "Spam"
    },
    {
      "text": "Your parcel will be delivered today",
      "label": "Not spam"
    },
    {
      "text": "Review changes to our Terms and Conditions",
      "label": "Not spam"
    },
    {
      "text": "Weekly sync notes",
      "label": "Not spam"
    },
    {
      "text": "\'Re: Follow up from today\'s meeting\'",
      "label": "Not spam"
    },
    {
      "text": "Pre-read for tomorrow",
      "label": "Not spam"
    }
  ],
  "model": "YOUR-FINE-TUNED-MODEL-ID"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.cohere.com/v1/classify");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"inputs\": [\n    \"Confirm your email address\",\n    \"hey i need u to send some $\"\n  ],\n  \"examples\": [\n    {\n      \"text\": \"Dermatologists don't like her!\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"'Hello, open to this?'\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"I need help please wire me $1000 right now\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Nice to know you ;)\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Please help me?\",\n      \"label\": \"Spam\"\n    },\n    {\n      \"text\": \"Your parcel will be delivered today\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Review changes to our Terms and Conditions\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Weekly sync notes\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"'Re: Follow up from today's meeting'\",\n      \"label\": \"Not spam\"\n    },\n    {\n      \"text\": \"Pre-read for tomorrow\",\n      \"label\": \"Not spam\"\n    }\n  ],\n  \"model\": \"YOUR-FINE-TUNED-MODEL-ID\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "inputs": ["Confirm your email address", "hey i need u to send some $"],
  "examples": [
    [
      "text": "Dermatologists don't like her!",
      "label": "Spam"
    ],
    [
      "text": "'Hello, open to this?'",
      "label": "Spam"
    ],
    [
      "text": "I need help please wire me $1000 right now",
      "label": "Spam"
    ],
    [
      "text": "Nice to know you ;)",
      "label": "Spam"
    ],
    [
      "text": "Please help me?",
      "label": "Spam"
    ],
    [
      "text": "Your parcel will be delivered today",
      "label": "Not spam"
    ],
    [
      "text": "Review changes to our Terms and Conditions",
      "label": "Not spam"
    ],
    [
      "text": "Weekly sync notes",
      "label": "Not spam"
    ],
    [
      "text": "'Re: Follow up from today's meeting'",
      "label": "Not spam"
    ],
    [
      "text": "Pre-read for tomorrow",
      "label": "Not spam"
    ]
  ],
  "model": "YOUR-FINE-TUNED-MODEL-ID"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.cohere.com/v1/classify")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```