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
embeddingProvider. - ai_complete and the other text helper functions use a
chatProvider. - SQL AI functions support the
openaicompatible protocol and the nativedashscopeprotocol. For images and videos, choose an endpoint and model that accept the input. See FILE input support.
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.
Getting started
The examples use Alibaba Cloud Model Studio (Bailian) in the Beijing region. Enable the models you plan to use, replaceYOUR_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 theqwen-plus model, then call ai_complete:
Embedding Provider: generate text embeddings
Create an embedding Provider using thetext-embedding-v4 model with 256 output dimensions, then call ai_embed:
Describe an image with a vision model
Thevision_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
Createvision_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.
Common calling rules
Passing arguments
Functions support positional arguments and named arguments in the formargument_name => value. Named arguments can appear in any order and allow you to specify optional arguments without supplying defaults for earlier arguments.
chat_provider refers to an existing chat AI Provider.
Provider and model
All functions have optionalprovider and model arguments. Both must be constant VARCHAR expressions. The cluster maintains separate default Providers for chat and embedding.
JSON options
Onlyai_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.
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
VARBINARYcolumnimage_bytes, useto_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. Seeai_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.
offsetmust be NULL or 0, andsizedoes not restrict the byte range available to the service. - A nonempty
content_typesets 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 explicitcontent_typesupported 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 useai_function_rate_limit_qps_embedding. The entire BE process shares one limit on concurrent requests, set byai_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_retriesandai_function_max_retries_on_throttleaccording 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_byteslimits 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.
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, orCASEconditional 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.
PREPAREis supported, but statements containing AI functions are fully replanned on everyEXECUTE; execution plans are not reused.- In a correlated subquery block, AI expressions in the
SELECTlist,WHERE,HAVING,ORDER BY, andJOIN ONare rejected even if the AI expression references only columns in that block. AI expressions in join conditions are supported only forINNER JOINandCROSS 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 anORDER 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:
Nat or below the threshold (default1000): a global candidate TopN limits input to the rewritten AI projection to at mostNrows.Nabove the threshold: a local candidate TopN limits input to that AI projection to at mostNrows per fragment instance, not per BE or pipeline driver.
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 supportsSET, 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.