> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# AI functions

> Learn how AI Providers, AI functions, and usage privileges work together to process text with model services in SQL.

**Experimental feature**

[Advice on use of experimental features](/documents/4.2/maturity/features.md)

AI functions let you call model services from SQL. `ai_complete` generates text from a prompt and can answer questions about an image or video. `ai_embed` generates embeddings for text, images, or videos.

## Function index

| Function | Purpose | Return type |
| - | - | - |
| [ai\_complete](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_complete.md) | Generate text from a prompt and an optional image or video | VARCHAR |
| [ai\_embed](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_embed.md) | Generate an embedding for text, an image, or a video | `ARRAY<FLOAT>` |
| [ai\_sentiment](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_sentiment.md) | Analyze text sentiment | VARCHAR |
| [ai\_classify](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_classify.md) | Classify text into given categories | JSON |
| [ai\_extract](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_extract.md) | Extract specified information | JSON |
| [ai\_fix\_grammar](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_fix_grammar.md) | Correct grammar and spelling | VARCHAR |
| [ai\_redact](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_redact.md) | Redact sensitive information by category | VARCHAR |
| [ai\_translate](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_translate.md) | Translate text | VARCHAR |
| [ai\_similarity](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_similarity.md) | Evaluate the semantic similarity of two texts | FLOAT |
| [ai\_summarize](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_summarize.md) | Generate a summary | VARCHAR |
| [ai\_filter](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_filter.md) | Determine whether text meets a condition | BOOLEAN |

## AI Providers and AI functions

An AI Provider is a centrally managed model service configuration in the cluster. It stores an endpoint, protocol, default model, and optional credentials. AI functions obtain these settings from the Provider, so you do not need to repeat endpoints and credentials in SQL.

* [ai\_embed](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_embed.md) uses an `embedding` Provider.
* [ai\_complete](/documents/4.2/sql-reference/sql-functions/ai-functions/ai_complete.md) and the other text helper functions use a `chat` Provider.
* SQL AI functions support the `openai` compatible protocol and the native `dashscope` protocol. For images and videos, choose an endpoint and model that accept the input. See [FILE input support](#file-input).

Provider endpoints support HTTP and HTTPS. Each execution plan captures the selected Provider configuration. Changes to that configuration or to the default Provider apply when a query is replanned.

For Provider creation, configuration properties, and management syntax, see [CREATE AI PROVIDER](/documents/4.2/sql-reference/sql-statements/cluster-management/ai_provider/CREATE_AI_PROVIDER.md). For default settings, see [SET DEFAULT AI PROVIDER](/documents/4.2/sql-reference/sql-statements/cluster-management/ai_provider/SET_DEFAULT_AI_PROVIDER.md).

## AI function privileges

Calling an AI function requires both types of usage privileges:

* **Function privilege**: Allows use of the corresponding AI function.
* **Provider privilege**: Allows access to the Provider selected for this call. This privilege is also checked when using a default Provider.

Neither privilege replaces the other. Managing Providers requires SYSTEM OPERATE. Provider management privileges do not mean that ordinary users have usage privileges on functions and Providers. Privileges on the tables, columns, and views involved in the query still apply.

For details, see [AI privilege items](/documents/4.2/administration/user_privs/authorization/privilege_item.md#ai-function-privileges). For the syntax to grant, revoke, and view privileges, see [GRANT](/documents/4.2/sql-reference/sql-statements/account-management/GRANT.md#ai-functions-and-providers), [REVOKE](/documents/4.2/sql-reference/sql-statements/account-management/REVOKE.md#ai-functions-and-providers), and [SHOW GRANTS](/documents/4.2/sql-reference/sql-statements/account-management/SHOW_GRANTS.md), respectively.

## Getting started

The examples use Alibaba Cloud Model Studio (Bailian) in the Beijing region. Enable the models you plan to use, replace `YOUR_DASHSCOPE_API_KEY` with an API key for that region, and use an account with Provider management privileges and usage privileges on the corresponding functions and Providers.

### Chat Provider: generate text

Create a chat Provider using the `qwen-plus` model, then call `ai_complete`:

```sql theme={null}
CREATE AI PROVIDER bailian_chat TYPE chat
PROPERTIES (
    "endpoint" = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
    "protocol" = "openai",
    "model" = "qwen-plus",
    "api_key" = "YOUR_DASHSCOPE_API_KEY"
);

-- Explicitly specify the Provider and use its default model.
SELECT ai_complete(
    prompt => 'Explain what columnar storage is in one sentence.',
    provider => 'bailian_chat',
    options => json_object('enable_thinking', false)
);

-- After setting the default chat Provider, you can omit provider in calls.
SET bailian_chat AS DEFAULT AI PROVIDER;

SELECT ai_complete(
    prompt => 'Explain what columnar storage is in one sentence.',
    options => json_object('enable_thinking', false)
);
```

### Embedding Provider: generate text embeddings

Create an embedding Provider using the `text-embedding-v4` model with 256 output dimensions, then call `ai_embed`:

```sql theme={null}
CREATE AI PROVIDER bailian_embedding TYPE embedding
PROPERTIES (
    "endpoint" = "https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings",
    "protocol" = "openai",
    "model" = "text-embedding-v4",
    "dimensions" = "256",
    "api_key" = "YOUR_DASHSCOPE_API_KEY"
);

-- Explicitly specify the Provider to generate a text embedding.
SELECT ai_embed(
    input => 'Columnar storage is suitable for analytical queries.',
    provider => 'bailian_embedding'
);

-- Set the default embedding Provider without affecting the default chat Provider.
SET bailian_embedding AS DEFAULT AI PROVIDER;

SELECT ai_embed('Columnar storage is suitable for analytical queries.');
```

### Describe an image with a vision model

The `vision_chat` Provider uses the OpenAI-compatible Chat endpoint in Model Studio and a vision model. Wrap the image URL in a FILE and pass it with the prompt using the `file` argument.

```sql theme={null}
CREATE AI PROVIDER vision_chat TYPE chat
PROPERTIES (
    "protocol" = "openai",
    "endpoint" = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
    "model" = "qwen3-vl-plus",
    "api_key" = "YOUR_DASHSCOPE_API_KEY"
);

SELECT ai_complete(
    prompt => 'Describe this image.',
    file => to_file(named_struct(
        'uri', 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg'
    )),
    provider => 'vision_chat'
);
```

### Embed a video from object storage

Create `vision_embedding` with the native DashScope multimodal embedding endpoint. This example uses an S3 storage volume named `media_volume`. You need USAGE on the volume to call [get\_presigned\_file](/documents/4.2/sql-reference/sql-functions/file-functions/presigned_functions.md#get_presigned_file). Replace the object URI with an MP4 video the volume can read. The model service must be able to reach the signed URL.

```sql theme={null}
CREATE AI PROVIDER vision_embedding TYPE embedding
PROPERTIES (
    "protocol" = "dashscope",
    "endpoint" = "https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding",
    "model" = "tongyi-embedding-vision-plus",
    "api_key" = "YOUR_DASHSCOPE_API_KEY"
);

SELECT ai_embed(
    input => get_presigned_file(
        'media_volume',
        to_file(named_struct('uri', 's3://my-bucket/videos/clip.mp4'))
    ),
    provider => 'vision_embedding'
);
```

The database sends input text, inline media, or the full media URL (including any signature parameters) to the Provider endpoint. Choose a service that meets your data egress requirements.

## Common calling rules

### Passing arguments

Functions support positional arguments and named arguments in the form `argument_name => value`. Named arguments can appear in any order and allow you to specify optional arguments without supplying defaults for earlier arguments.

```sql theme={null}
-- Use the default chat AI Provider and its default model.
SELECT ai_complete('Explain columnar storage.');

-- Positional arguments: override the default model of chat_provider with chat-model.
SELECT ai_complete('Explain columnar storage.', 'chat_provider', 'chat-model');

-- Named arguments: override the default model of the default chat AI Provider.
SELECT ai_complete(prompt => 'Explain columnar storage.', model => 'chat-model');
```

In these examples, `chat_provider` refers to an existing chat AI Provider.

### Provider and model

All functions have optional `provider` and `model` arguments. Both must be constant VARCHAR expressions. The cluster maintains separate default Providers for chat and embedding.

| Argument | When omitted, an empty string, or SQL NULL | When explicitly specified |
| - | - | - |
| `provider` | Use the cluster default Provider of the corresponding type | Use the named Provider; no cluster default is required |
| `model` | Use the selected Provider's default model | Use the specified model offered by the selected service |

### JSON options

Only `ai_complete` and `ai_embed` accept `options`. It must be a constant JSON expression that evaluates to a JSON object or SQL NULL. The default is an empty object. Passing `json_object()` or SQL NULL also sends no extra parameters to the model service.

```sql theme={null}
SELECT ai_complete(
    prompt => 'Explain columnar storage in one sentence.',
    options => json_object('temperature', 0.2)
);
```

Use options to pass additional request parameters supported by the model service.

## FILE input support

Each call accepts at most one [FILE](/documents/4.2/sql-reference/data-types/other-data-types/FILE.md). The table shows what the database can send. The model must also support the format you supply.

| Function | Protocol and endpoint | Text | Image FILE | Video FILE |
| - | - | - | - | - |
| `ai_complete` | `openai` compatible Chat | Yes | Inline or URL | No |
| `ai_complete` | `dashscope` native text generation | Yes | No | No |
| `ai_complete` | `dashscope` native multimodal generation | Yes | Inline or URL | Inline or URL |
| `ai_embed` | `openai` compatible Embeddings | Yes | No | No |
| `ai_embed` | `dashscope` native text embedding | Yes | No | No |
| `ai_embed` | `dashscope` native multimodal embedding | Yes | Inline or URL | URL only |

For video input, use a native `dashscope` multimodal endpoint. The FILE overloads do not support audio or PDF files.

* To supply **inline bytes** from a `VARBINARY` column `image_bytes`, use `to_file(named_struct('inline', image_bytes))`. The bytes must be nonempty. The database encodes them as a data URI. The default limit is 10 MiB per FILE before Base64 encoding. See [`ai_function_max_input_file_bytes`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_max_input_file_bytes).
* For a **URL reference**, supply an HTTP(S) URL the model service can access. For private objects, use [get\_presigned\_file](/documents/4.2/sql-reference/sql-functions/file-functions/presigned_functions.md#get_presigned_file). The database forwards the full URL. `offset` must be NULL or 0, and `size` does not restrict the byte range available to the service.
* A nonempty `content_type` sets the **media type**. If it is NULL or empty, the database infers JPEG, PNG, WebP, or MP4 from the inline file header or the extension on the last segment of the URL path (`.jpg`, `.jpeg`, `.png`, `.webp`, `.mp4`). Extension matching ignores case, query parameters, and fragments. An unknown type requires an explicit `content_type` supported by the model.
* A FILE that evaluates to **SQL NULL** returns NULL without a model request. Invalid media follows [`ai_function_on_error`](#error-handling).

## Error handling

`ai_function_on_error` controls row-level failures. The default, `ignore`, returns NULL for a failed row and continues the query; `fail` aborts the query. Analysis or configuration errors, query cancellation, and deadline expiration are not ignored. A NULL result therefore does not necessarily mean the input was NULL; it can also indicate a failed model call or response validation.

## Runtime limits and retries

* Each BE limits requests per second for each combination of endpoint, credential, and capability. Text generation and helper functions use [`ai_function_rate_limit_qps_chat`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_rate_limit_qps_chat). Embedding functions use [`ai_function_rate_limit_qps_embedding`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_rate_limit_qps_embedding). The entire BE process shares one limit on concurrent requests, set by [`ai_function_max_inflight`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_max_inflight). The BE schedules queued requests fairly across resource groups and queries. Both limits apply to the first attempt and every retry.
* A request may reach the model service even if it times out or returns an error. If the database retries, the service may process the same request again and charge for it a second time. Set [`ai_function_max_retries`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_max_retries) and [`ai_function_max_retries_on_throttle`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_max_retries_on_throttle) according to how the service handles and bills for duplicate requests.
* Request and response bodies count toward the query's memory usage. The execution pipeline applies backpressure while requests are outstanding. [`ai_function_max_response_bytes`](/documents/4.2/administration/configuration/BE_parameters/query_loading#ai_function_max_response_bytes) limits the size of each HTTP response body.
* Each task gets a fixed timeout at creation. Retries do not restart the timer. While a task runs asynchronously, it still responds to query cancellation and changes to the query deadline. For timeout, worker thread, and scheduling granularity settings, see [BE AI function configuration](/documents/4.2/administration/configuration/BE_parameters/query_loading.md#ai_function_request_timeout_ms).

For request, retry, and timeout metrics, see [AI HTTP metrics](/documents/4.2/administration/management/monitoring/metric_details/a-c.md#ai_http_requests_total).

## SQL usage restrictions

* AI functions cannot be used in `GROUP BY`, `SELECT DISTINCT`, aggregate function arguments, or window function expressions.
* They cannot be used in `IF`, `IFNULL`, `NULLIF`, `COALESCE`, or `CASE` conditional expressions, or as table function arguments.
* They cannot be used in synchronous materialized view definitions, LOAD expressions, or generated column expressions.
* They cannot be used in Lambda expression bodies or SQL UDF bodies.
* SQL Plan Baselines cannot be created or bound for statements containing AI functions. Other queries containing AI functions do not use SPM rewrites either.
* `PREPARE` is supported, but statements containing AI functions are fully replanned on every `EXECUTE`; execution plans are not reused.
* In a correlated subquery block, AI expressions in the `SELECT` list, `WHERE`, `HAVING`, `ORDER BY`, and `JOIN ON`
  are rejected even if the AI expression references only columns in that block. AI expressions in join conditions are supported only for `INNER JOIN` and `CROSS JOIN`.
* Each non-NULL input row can trigger a remote request. For large queries, use the expected request count to estimate cost. Check the service quota and network latency when deciding whether the query can finish before its deadline.

## Reducing AI input rows

For an `ORDER BY ... LIMIT` query with a positive `LIMIT` and no `OFFSET`, the database can select candidate rows before
evaluating an AI projection when the ordering columns pass through that projection and any intervening ordinary
Project unchanged.

[`ai_topn_pushdown_max_global_limit`](/documents/4.2/sql-reference/System_variable#ai_topn_pushdown_max_global_limit) selects the
strategy for SQL `LIMIT N`:

* `N` at or below the threshold (default `1000`): a global candidate TopN limits input to the rewritten AI projection
  to at most `N` rows.
* `N` above the threshold: a local candidate TopN limits input to that AI projection to at most `N` rows per fragment
  instance, not per BE or pipeline driver.

The global strategy can trade cross-instance AI parallelism for a global row bound. The local strategy avoids an
additional global gather before AI execution, although local merging can reduce parallelism within an instance.
Both retain the original TopN above the AI projection to preserve output order and limit. Use `EXPLAIN` to inspect
the resulting plan.

These bounds apply to the rewritten AI projection, not all AI work in a query: an inner nested AI call may still
process more rows. They are not HTTP request or token limits. Pruned rows do not execute AI calls.

The optimization does not move TopN below AI calls needed for ordering or filtering, cross existing limits or unsafe
projection and predicate barriers, or apply to partitioned TopN, `RANK`, or `DENSE_RANK`.

### Selecting the strategy

The threshold supports `SET`, `SET GLOBAL` for future sessions, and statement-level `SET_VAR` hints without restarting.
It does not affect queries without an AI projection. Setting it to `0` selects local-only pruning, not disabled pruning.

```sql theme={null}
-- Use global pruning for LIMIT <= 1000, and local pruning for larger limits.
SET ai_topn_pushdown_max_global_limit = 1000;
-- Use local-only pruning.
SET ai_topn_pushdown_max_global_limit = 0;
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.