[ Web Proxy ]
URL:
Viewing: https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-classify [Back]  [Original]

The AI.CLASSIFY function  |  BigQuery  |  Google Cloud Documentation Skip to main content
Google Cloud Documentation [Google Cloud Documentation]
Send feedback Stay organized with collections Save and categorize content based on your preferences.

The AI.CLASSIFY function

This document describes the AI.CLASSIFY function, which uses a Gemini Enterprise Agent Platform Gemini model to classify inputs into categories that you provide. BigQuery automatically structures your input to improve the quality of the classification.

The following are common use cases:

Input

AI.CLASSIFY accepts the following types of input:

This function passes your input to a Gemini model and incurs charges in Gemini Enterprise Agent Platform each time it's called. For information about how to view these charges, see Track costs.

Syntax

AI.CLASSIFY(
  [ input => ] INPUT,
  [ categories => ] CATEGORIES
  [, examples => EXAMPLES ]
  [, connection_id => 'CONNECTION' ]
  [, endpoint => 'ENDPOINT' ]
  [, output_mode => 'OUTPUT_MODE' ]
  [, embeddings => EMBEDDINGS ]
  [, optimization_mode => 'OPTIMIZATION_MODE' ]
  [, max_error_ratio => MAX_ERROR_RATIO ]
)

Arguments

AI.CLASSIFY takes the following arguments.

Output

If you don't specify an OUTPUT_MODE, then AI.CLASSIFY returns a STRING value containing the category that best fits the input.

If you specify an OUTPUT_MODE, then AI.CLASSIFY returns an ARRAY<STRING> value that contains all categories that the input is classified into. If OUTPUT_MODE is single then the array always has length 1. If OUTPUT_MODE is multi then the array length is between 0 and the number of categories.

If the call to Gemini Enterprise Agent Platform is unsuccessful for any reason, such as exceeding quota or model unavailability, then the function returns NULL for that row. However, if the ratio of unsuccessful rows exceeds the value of max_error_ratio, then the entire query fails.

Examples

The following examples show how to use the AI.CLASSIFY function to classify text and images into predefined categories.

Classify text by topic

The following query categorizes BBC news articles into high-level categories:

SELECT
  title,
  body,
  AI.CLASSIFY(
    body,
    endpoint => 'gemini-2.5-pro',
    categories => ['tech', 'sport', 'business', 'politics', 'entertainment', 'other']) AS category
FROM
  `bigquery-public-data.bbc_news.fulltext`
LIMIT 100;

The result is similar to the following:

+-------------------------------+------------------------------------+----------+
| title                         | body                               | category |
+-------------------------------+------------------------------------+----------+
| Anti-spam screensave scrapped | A contentious campaign to bump up  | tech     |
|                               | the bandwidth bills of spammers... |          |
| ...                           | ...                                | ...      |
+-------------------------------+------------------------------------+----------+

To extract your categories from a table instead of using an array of string literals directly in your query, you can use variables. Suppose you have a table called mydataset.categories with a string column called category that contains each of the categories from the previous example. You can rewrite the previous query using a variable in the following way:

DECLARE article_types ARRAY<STRING>
  DEFAULT (SELECT ARRAY_AGG(category) FROM mydataset.categories);

SELECT
  title,
  body,
  AI.CLASSIFY(
    body,
    endpoint => 'gemini-2.5-pro',
    categories => article_types) AS category
FROM
  `bigquery-public-data.bbc_news.fulltext`
LIMIT 100;

Classify text into multiple topics

The following query categorizes each news article into one or more high-level categories and provides two examples of categorization to the function:

WITH NewsArticles AS (
  SELECT
    'A major streaming platform announced a high-tech virtual reality broadcast for the upcoming championship game.' AS article_text
  UNION ALL
  SELECT
    'New legislation has been proposed to regulate the use of facial recognition technology in government buildings.' AS article_text
  UNION ALL
  SELECT
    'The superstar athlete announced a multi-million dollar movie deal and a new sports apparel venture.' AS article_text
)
SELECT
  article_text,
  AI.CLASSIFY(
    ('Main topics of this news article: ', article_text),
    endpoint => 'gemini-2.5-pro',
    categories => ['Politics', 'Finance', 'Technology', 'Sports', 'Entertainment'],
    output_mode => 'multi',
    examples => [
      ('The new stock market app is a hit with investors.', ['Finance', 'Technology']),
      ('The senator\'s speech on the economy was widely criticized.', ['Politics', 'Finance'])
    ]
  ) AS topics
FROM NewsArticles;

The result is similar to the following:

+----------------------+-------------------------------------+
| article_text         | topics                              |
+----------------------+-------------------------------------+
| New legislation...   | [Politics, Technology]              |
| The superstar...     | [Sports, Entertainment, Finance]    |
| A major streaming... | [Technology, Sports, Entertainment] |
+----------------------+-------------------------------------+

Classify text with optimized mode

The following query categorizes BBC news articles using optimized mode (Preview):

SELECT
  title,
  body,
  AI.CLASSIFY(
    body,
    categories => ['tech', 'sport', 'business', 'other'],
    embeddings => AI.EMBED(body, endpoint => 'text-embedding-005', task_type => 'CLASSIFICATION').result,
    optimization_mode => 'MINIMIZE_COST'
   ) AS category
FROM
  `bigquery-public-data.bbc_news.fulltext`;

For this example, embeddings are generated on-the-fly. In practice, we recommend that you materialize embeddings so that they can be reused. For more information, see Optimize AI function costs.

Classify reviews by sentiment

The following query classifies movie reviews of The English Patient by sentiment according to a custom color scheme. For example, a review that is very positive is classified as 'green'.

SELECT
  AI.CLASSIFY(
    ('Classify the review by sentiment: ', review),
    endpoint => 'gemini-2.5-pro',
    categories =>
         [('green', 'The review is positive.'),
          ('yellow', 'The review is neutral.'),
          ('red', 'The review is negative.')]) AS ai_review_rating,
  reviewer_rating AS human_provided_rating,
  review,
FROM
  `bigquery-public-data.imdb.reviews`
WHERE
  title = 'The English Patient'

Classify images by type

The following query creates an external table from images of pet products stored in a publicly available Cloud Storage bucket. Then, it classifies each image as a box, ball, bottle, stand, or other type of item.

-- Create a dataset
CREATE SCHEMA IF NOT EXISTS cymbal_pets;

-- Create an object table
CREATE OR REPLACE EXTERNAL TABLE cymbal_pets.product_images
WITH CONNECTION us.example_connection
OPTIONS (
 object_metadata = 'SIMPLE',
 uris = ['gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png']
);

-- Classify images in the object table
SELECT
  OBJ.GET_READ_URL(ref).url AS signed_url,
  AI.CLASSIFY(
    images.ref,
    ['box', 'ball', 'bottle', 'stand', 'other'],
    endpoint => 'gemini-2.5-pro') AS category
FROM
  `cymbal_pets.product_images` AS images
LIMIT 10;

Handle inference errors

The following query classifies news articles but sets max_error_ratio to 0.05, meaning the query fails if more than 5% of rows return an error during inference:

SELECT
  title,
  body,
  AI.CLASSIFY(
    body,
    categories => ['tech', 'sport', 'business', 'politics', 'entertainment', 'other'],
    endpoint => 'gemini-2.5-pro',
    max_error_ratio => 0.05) AS category
FROM
  `bigquery-public-data.bbc_news.fulltext`
LIMIT 100;

If the query exceeds the 0.05 error ratio, it fails and returns an error message similar to the following: Query failed because AI functions exceeded their allowed error ratio

Locations

You can run AI.CLASSIFY in all of the regions that support Gemini models, and also in the US and EU multi-regions.

Quotas and limits

For quota and limit information, see Generative AI functions in the BigQuery quotas and limits reference.

What's next

Send feedback

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-08-11 UTC.

Need to tell us more? [[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-08-11 UTC."],[],[]]

Web Proxy Viewer  |  New URL  |  Original Page