Skip to main content
Experimental feature Advice on use of experimental features 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

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 uses an embedding Provider.
  • ai_complete 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.
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. For default settings, see SET DEFAULT AI PROVIDER.

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. For the syntax to grant, revoke, and view privileges, see GRANT, REVOKE, and SHOW GRANTS, 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:

Embedding Provider: generate text embeddings

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

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.

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. Replace the object URI with an MP4 video the volume can read. The model service must be able to reach the signed URL.
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.
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.

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.
Use options to pass additional request parameters supported by the model service.

FILE input support

Each call accepts at most one FILE. The table shows what the database can send. The model must also support the format you supply. 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.
  • For a URL reference, supply an HTTP(S) URL the model service can access. For private objects, use 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

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. Embedding functions use ai_function_rate_limit_qps_embedding. The entire BE process shares one limit on concurrent requests, set by 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 and 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 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.
For request, retry, and timeout metrics, see AI HTTP metrics.

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 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.