---
title: ai_classify function
description: Learn the syntax of the ai\_classify function of the SQL language in Databricks SQL.
canonical_url: https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_classify
---

# `ai_classify` function

**Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime

The `ai_classify()` function classifies text content according to custom labels you provide. You can use simple label names for basic classification, or add label descriptions and instructions to improve accuracy for use cases like customer support routing, document categorization, and content analysis.

The function accepts text or `VARIANT` output from other AI functions like `ai_parse_document`, enabling composable workflows.

For a UI version to iterate on `ai_classify`, see [Classification](https://docs.databricks.com/aws/en/agents/agent-bricks/classification.md).

## Data security

Your document data is processed within the Databricks security perimeter. Databricks does not store the parameters that are passed into the AI function calls, but does retain metadata run details, such as the Databricks Runtime version used.

## Requirements

**Apache 2.0 license**

The underlying models that might be used at this time are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0), Copyright © The Apache Software Foundation. Customers are responsible for ensuring compliance with applicable model licenses.

Databricks recommends reviewing these licenses to ensure compliance with any applicable terms. If models emerge in the future that perform better according to Databricks's internal benchmarks, Databricks might change the model (and the list of applicable licenses provided on this page).

The model powering this function is made available using Model Serving Foundation Model APIs. See [Applicable model terms](https://docs.databricks.com/aws/en/machine-learning/model-serving/acceptable-use-models.md) for information about which models are available on Databricks and the licenses and policies that govern the use of those models.

If models emerge that perform better according to Databricks's internal benchmarks, Databricks might change the models and update the documentation.

* This function is only available in some regions, see [AI function availability](https://docs.databricks.com/aws/en/resources/feature-region-support.md#ai-functions-aws).
* For workspaces with the [Enhanced Security and Compliance add-on](https://docs.databricks.com/aws/en/security/privacy/enhanced-security-compliance.md),
  * See regional support for `ai_classify` for the appropriate [compliance standard](https://docs.databricks.com/aws/en/security/privacy/security-profile.md).
  * See [Manage Databricks previews](https://docs.databricks.com/aws/en/admin/workspace-settings/manage-previews.md) for how to enable it on your workspace.
* This function is not available on Databricks SQL Classic.
* Databricks Runtime 15.4 LTS or above is required. For an upcoming change to this requirement, see [AI Functions require Databricks Runtime 17.3 LTS or above](https://docs.databricks.com/aws/en/release-notes/whats-coming.md#ai-functions-runtime-support). Databricks Runtime 18.2 or above is recommended for the best performance and access to the latest features.
* Check the [Databricks SQL pricing page](https://www.databricks.com/product/pricing/databricks-sql).

> [!TIP]
>
> Databricks recommends using **version 2.1** for `ai_classify`. Version 1.0 is a legacy interface that does not support these capabilities and is not recommended for new or production workloads.
>
> Version 2.0 supports:
>
> * Label descriptions for improved accuracy
> * Multi-label classification
> * Global instructions
> * Up to 500 labels, compared to 20 in version 1.0
> * `VARIANT` input from upstream AI functions like `ai_parse_document`
> * Returns a structured `VARIANT` with error information
>
> Version 2.1 also supports:
>
> * Confidence scores for each returned label, enabled with `enableConfidenceScores`
> * Rationales explaining each returned label, enabled with `enableRationales`
>
> In version 2.1, each classification in `response` is a per-label object with a `value` key instead of a plain label string. This output shape change applies to all version 2.1 calls, even when the new options are disabled. Moving from version 2.0 to 2.1 is not output-compatible. Update your queries and downstream code to read the label from the `value` key instead of reading it directly.
>
> To pin a version explicitly, pass `options => map('version', '2.1')`.

## Syntax

### Version 2.1 (recommended)

```
ai_classify(content, labels [, options])
```

### Version 2

```
ai_classify(content, labels [, options])
```

### Version 1 (Legacy)

```
ai_classify(content, labels [, options])
```

## Arguments

### Version 2.1 (recommended)

* `content`: A `VARIANT` or `STRING` expression. Accepts either:
  * Raw text as a `STRING`
  * A `VARIANT` produced by another AI function (such as [`ai_parse_document`](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_parse_document.md) or [`ai_extract`](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_extract.md))

* `labels`: A `STRING` expression defining the classification labels. This can be a string literal or any SQL expression that evaluates to a `STRING`, including a Delta table column. The labels can be:

  * Simple labels: A JSON array of label names.
    ```json
    ["urgent", "not_urgent"]
    ```
  * Labels with descriptions: A JSON object mapping label names to descriptions. Label descriptions must be 0-1000 characters.
    ```json
    {
      "billing_error": "Payment, invoice, or refund issues",
      "product_defect": "Any malfunction, bug, or breakage",
      "account_issue": "Login failures, password resets"
    }
    ```

  Each label must be 1-100 characters. `labels` must contain at least 2 labels, and no more than 500 labels. For taxonomies larger than 500 labels, see the [ Classification with 500+ labels](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_classify.md#classify-500-labels).

* `options`: An optional `MAP<STRING, STRING>` containing configuration options:
  * `version`: Version switch to support migration (`"1.0"`, `"2.0"`, or `"2.1"`). Default is based on input types, but falls back to `"1.0"`.
  * `instructions`: Global description of the task and domain to improve classification quality. Must be less than 20,000 characters.
  * `multilabel`: Set to `"true"` to return multiple labels when multiple categories apply. Default is `"false"` (single-label classification).
  * `enableConfidenceScores`: Set to `"true"` to include a `confidence_score` (0–1) for each returned label. Requires version `"2.1"`. Default is `"false"`.
  * `enableRationales`: Set to `"true"` to include a short rationale explaining each returned label, grounded in the input text. Requires version `"2.1"`. Default is `"false"`.

### Version 2

* `content`: A `VARIANT` or `STRING` expression. Accepts either:
  * Raw text as a `STRING`
  * A `VARIANT` produced by another AI function (such as [`ai_parse_document`](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_parse_document.md) or [`ai_extract`](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_extract.md))

* `labels`: A `STRING` expression defining the classification labels. This can be a string literal or any SQL expression that evaluates to a `STRING`, including a Delta table column. The labels can be:

  * Simple labels: A JSON array of label names.
    ```json
    ["urgent", "not_urgent"]
    ```
  * Labels with descriptions: A JSON object mapping label names to descriptions. Label descriptions must be 0-1000 characters.
    ```json
    {
      "billing_error": "Payment, invoice, or refund issues",
      "product_defect": "Any malfunction, bug, or breakage",
      "account_issue": "Login failures, password resets"
    }
    ```

  Each label must be 1-100 characters. `labels` must contain at least 2 labels, and no more than 500 labels. For taxonomies larger than 500 labels, see the [ Classification with 500+ labels](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_classify.md#classify-500-labels).

* `options`: An optional `MAP<STRING, STRING>` containing configuration options:
  * `version`: Version switch to support migration (`"1.0"` for v1 behavior, `"2.0"` for v2 behavior). Default is based on input types, but falls back to `"1.0"`.
  * `instructions`: Global description of the task and domain to improve classification quality. Must be less than 20,000 characters.
  * `multilabel`: Set to `"true"` to return multiple labels when multiple categories apply. Default is `"false"` (single-label classification).

### Version 1 (Legacy)

* `content`: A `STRING` expression containing the text to be classified.

* `labels`: An `ARRAY<STRING>` literal with the expected output classification labels. Must contain at least 2 elements, and no more than 20 elements. Each label must be 1-50 characters.

* `options`: An optional `MAP<STRING, STRING>` containing configuration options:
  * `version`: Version switch to support migration (`"1.0"` for v1 behavior, `"2.0"` for v2 behavior). Default is based on input types, but falls back to `"1.0"`.

## <a id="returns" />Returns

### Version 2.1 (recommended)

Returns a `VARIANT` containing:

```json
{
  "response": [{ "value": "label_name", "confidence_score": 0.97, "rationale": "Short justification for the label." }],
  "metadata": {
    "version": "2.1"
  },
  "error_message": null // null on success, or error message on failure
}
```

Each element in `response` is a per-label object with a `value` key rather than a plain label string. When `enableConfidenceScores` is `"true"`, each object also includes a `confidence_score` (0–1). When `enableRationales` is `"true"`, each object also includes a `rationale`. When both options are enabled, the key order in each object is `value`, `confidence_score`, then `rationale`.

The `response` field contains:

* **Single-label mode** (default): An array with one element containing the best matching label
* **Multi-label mode** (`multilabel: "true"`): An array with multiple labels when multiple categories apply
* Label names exactly match those provided in the `labels` parameter

Returns `NULL` if `content` is `NULL` or if the content cannot be classified.

### Version 2

Returns a `VARIANT` containing:

```json
{
  "response": ["label_name"], // Array with single label (or multiple if multilabel=true)
  "metadata": {
    "version": "2.0"
  },
  "error_message": null // null on success, or error message on failure
}
```

The `response` field contains:

* **Single-label mode** (default): An array with one element containing the best matching label
* **Multi-label mode** (`multilabel: "true"`): An array with multiple labels when multiple categories apply
* Label names exactly match those provided in the `labels` parameter

Returns `NULL` if `content` is `NULL` or if the content cannot be classified.

### Version 1 (Legacy)

Returns a `STRING`. The value matches one of the strings provided in the `labels` argument.

Returns `NULL` if `content` is `NULL` or if the content cannot be classified.

## Examples

### Version 2.1 (recommended)

### Simple labels - label names only

In version 2.1, each classification is a per-label object with a `value` key instead of a plain string, even when the new options are disabled.

```sql
> SELECT ai_classify(
    'My password is leaked.',
    '["urgent", "not_urgent"]',
    MAP('version', '2.1')
  );
 {
   "response": [{"value": "urgent"}],
   "metadata": {
     "version": "2.1"
   },
   "error_message": null
 }
```

### With confidence scores

```sql
> SELECT ai_classify(
    'My password is leaked.',
    '["urgent", "not_urgent"]',
    MAP('version', '2.1', 'enableConfidenceScores', 'true')
  );
 {
   "response": [{"value": "urgent", "confidence_score": 0.97}],
   "metadata": {
     "version": "2.1"
   },
   "error_message": null
 }
```

### With rationales

```sql
> SELECT ai_classify(
    'My password is leaked.',
    '["urgent", "not_urgent"]',
    MAP('version', '2.1', 'enableRationales', 'true')
  );
 {
   "response": [{"value": "urgent", "rationale": "A leaked password is a security incident requiring immediate action."}],
   "metadata": {
     "version": "2.1"
   },
   "error_message": null
 }
```

### With confidence scores and rationales (multi-label)

```sql
> SELECT ai_classify(
    'Customer wants refund and reports product arrived broken.',
    '{
      "billing_issue": "Payment or refund requests",
      "product_defect": "Damaged or malfunctioning items"
    }',
    MAP('version', '2.1', 'multilabel', 'true', 'enableConfidenceScores', 'true', 'enableRationales', 'true')
  );
 {
   "response": [
     {"value": "billing_issue", "confidence_score": 0.91, "rationale": "Customer explicitly requests a refund."},
     {"value": "product_defect", "confidence_score": 0.88, "rationale": "Reports the product arrived broken."}
   ],
   "metadata": {
     "version": "2.1"
   },
   "error_message": null
 }
```

### Composability with `ai_parse_document`

```sql
> WITH parsed_docs AS (
    SELECT
      path,
      ai_parse_document(
        content,
        MAP('version', '2.0')
      ) AS parsed_content
    FROM READ_FILES('/Volumes/support/tickets/', format => 'binaryFile')
  )
  SELECT
    path,
    ai_classify(
      parsed_content,
      '["billing_error", "product_defect", "account_issue", "feature_request"]',
      MAP('version', '2.1', 'instructions', 'Customer support ticket classification.')
    ) AS ticket_category
  FROM parsed_docs;
```

### Batch classification

```sql
> SELECT
    description,
    ai_classify(
      description,
      '["clothing", "shoes", "accessories", "furniture", "electronics"]',
      MAP('version', '2.1')
    ) AS category
  FROM products
  LIMIT 10;
```

### <a id="classify-500-labels" /> Classification with 500+ labels

To classify with more than 500 labels, we recommend embedding your documents and labels, retrieving the top k labels per document, and then running `ai_classify` on the smaller subset.

See [Tutorial: Classify documents with 500+ labels](https://docs.databricks.com/aws/en/large-language-models/classify-documents-labels-tutorial.md) for a step-by-step walkthrough.

### Version 2

### Simple labels - label names only

```sql
> SELECT ai_classify(
    'My password is leaked.',
    '["urgent", "not_urgent"]'
  );
 {
   "response": ["urgent"],
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }
```

### Labels with descriptions

```sql
> SELECT ai_classify(
    'Customer cannot complete checkout due to payment processing error.',
    '{
      "billing_error": "Payment, invoice, or refund issues",
      "product_defect": "Any malfunction, bug, or breakage",
      "account_issue": "Login failures, password resets",
      "feature_request": "Customer suggestions for improvements"
    }'
  );
 {
   "response": ["billing_error"],
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }
```

### Labels from Delta Table

Pass labels from a Delta table by converting them into a JSON string. For example, given a label table with schema `news_topics(topic STRING, description STRING)`, you can pass your labels to `ai_classify` as follows:

```sql
SELECT
  ai_classify(
    "Leicester City Wins Premier League Title at 5000-1 Odds",
    l.labels,
    MAP('version', '2.0')
  ) AS classification
FROM (
  SELECT to_json(map_from_entries(collect_list(struct(topic, description)))) AS labels
  FROM news_topics
) l;
```

### Using global instructions

```sql
> SELECT ai_classify(
    'User reports app crashes on startup after update.',
    '["critical", "high", "medium", "low"]',
    MAP('instructions', 'Classify bug severity based on user impact and frequency.')
  );
 {
   "response": ["critical"],
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }
```

### Multi-label classification

```sql
> SELECT ai_classify(
    'Customer wants refund and reports product arrived broken.',
    '{
      "billing_issue": "Payment or refund requests",
      "product_defect": "Damaged or malfunctioning items",
      "shipping_issue": "Delivery problems"
    }',
    MAP('version', '2.0','multilabel', 'true')
  );
 {
   "response": ["billing_issue", "product_defect"],
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }
```

### Version 1 (Legacy)

```sql
> SELECT ai_classify("My password is leaked.", ARRAY("urgent", "not urgent"));
  urgent

> SELECT
    description,
    ai_classify(description, ARRAY('clothing', 'shoes', 'accessories', 'furniture')) AS category
  FROM
    products
  LIMIT 10;
```

## <a id="limitations" />Limitations

### Version 2.1 (recommended)

Version 2.1 limitations:

* This function is not available on Databricks SQL Classic.

* This function cannot be used with [Views](https://docs.databricks.com/aws/en/views/index.md).

* Label names must be 1–100 characters each.

* The `labels` parameter must contain between 2 and 500 unique labels.

* Label descriptions must be 0–1,000 characters each.

* The maximum total context size is 1 million tokens.

### Version 2

Version 2 limitations:

* This function is not available on Databricks SQL Classic.

* This function cannot be used with [Views](https://docs.databricks.com/aws/en/views/index.md).

* Label names must be 1–100 characters each.

* The `labels` parameter must contain between 2 and 500 unique labels.

* Label descriptions must be 0–1,000 characters each.

* The maximum total context size is 1 million tokens.

### Version 1 (Legacy)

Version 1 (Legacy) limitations:

* This function is not available on Databricks SQL Classic.

* This function cannot be used with [Views](https://docs.databricks.com/aws/en/views/index.md).

* Label names must be 1–50 characters each.

* The `labels` array must contain between 2 and 20 labels.

* The `content` input must be less than 128,000 tokens (about 300,000 characters).

## Related functions

* [`ai_extract` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_extract.md)
* [`ai_parse_document` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_parse_document.md)
