AI Function

更新时间:
复制 MD 格式

PolarDB-X AI functions provide a suite of built-in SQL functions for large language model (LLM) text generation, embedding, semantic similarity, cross-encoder reranking, zero-shot classification, structured extraction, document parsing, and multimodal embedding. You can perform enterprise-grade knowledge retrieval, text comprehension, and inference directly through standard SQL, without any AI SDK or external inference service.

Prerequisites

  • A PolarDB-X instance is created, and the instance version is 2.6.0_5.4.21-20260610 or later.

    Note
  • Only Enterprise Edition is supported.

  • Enable instance AI capability: On the instance details page, in the upper-right corner, click Enable AI to enable the instance AI capability. After the AI capability is enabled, an AI gateway is created for the instance so that you can use AI functions.

AI function summary

The following table lists all AI functions currently supported by PolarDB-X.

  • The AI gateway automatically binds an optimal default model to each AI function. If you do not explicitly specify a model name when calling a function, the system automatically uses the corresponding default model.

  • To switch to another available model, pass the model name as the second parameter of the function.

Important

In this topic, names in the form AI_GATEWAY_XXX_MODEL are model names registered by the AI gateway. The actual underlying model is determined by the AI gateway. To view the registered model names, see View registered models.

Function

Description

Default model

AI_PROMPT

Calls a large language model (LLM) with a prompt for text inference and generation. Supports system prompts, temperature control, and chain-of-thought reasoning.

AI_GATEWAY_LLM_MODEL (default). Other LLM models are also available.

AI_EMBEDDING

Converts input text into a fixed-dimensional continuous vector.

AI_GATEWAY_EMBEDDING_MODEL (default).

AI_SIMILARITY

Computes the semantic similarity between a query and a candidate text or a pre-stored vector. When the second parameter is a stored vector, no API call is made, resulting in very high performance.

AI_GATEWAY_EMBEDDING_MODEL (same as AI_EMBEDDING).

AI_RANK

Scores query-document relevance with a cross-encoder reranking model.

AI_GATEWAY_RERANK_MODEL (default).

AI_CLASSIFY

Performs zero-shot classification of input text against a set of candidate labels. Supports single-label and multi-label modes.

AI_GATEWAY_LLM_MODEL (default).

AI_EXTRACT

Extracts structured fields from input text based on a specified JSON Schema.

AI_GATEWAY_LLM_MODEL (default).

AI_SUMMARIZE

Generates a summary of input text. Supports word count limits, output language, and summary style options.

AI_GATEWAY_LLM_MODEL (default).

AI_PARSE_DOCUMENT

Parses unstructured files such as PDFs and images from public URLs into plain text.

AI_GATEWAY_DOCUMENT_PARSE_MODEL (default).

AI_VL_EMBEDDING

Generates multimodal vectors from image URLs, video URLs, or plain text. Supports cross-modal image-text retrieval.

AI_GATEWAY_VL_EMBEDDING_MODEL (default).

AI_TEXT2SQL

Converts a natural language description into a SQL statement. Automatically reads the table schema of the current database to generate an executable SQL.

AI_GATEWAY_LLM_MODEL (default).

AI function usage

AI_PROMPT

Calls a large language model with a prompt to perform text inference and return the result. This function supports advanced capabilities such as setting an AI role with a system prompt, controlling output diversity with temperature, and enabling chain-of-thought reasoning (Qwen3 series).

Syntax

--Basic call using the default LLM model
SELECT AI_PROMPT(prompt)

--Specify a model
SELECT AI_PROMPT(prompt, model)

--Specify a model and generation parameters
SELECT AI_PROMPT(prompt, model, options)

Parameters

  • prompt: Required. The input prompt text. Supports character types (CHAR, VARCHAR, TEXT).

  • model: Optional. The name of the model to use. Defaults to the built-in LLM model AI_GATEWAY_LLM_MODEL.

  • options: Optional. A JSON string that controls LLM generation behavior. The following fields are supported:

    Field

    Type

    Description

    temperature

    DOUBLE

    Temperature parameter (0 to 2). Higher values produce more random output.

    max_tokens

    INT

    Maximum number of tokens to generate.

    top_p

    DOUBLE

    Nucleus sampling parameter.

    stop

    STRING / ARRAY

    Stop token(s) to terminate generation.

    system_prompt

    STRING

    System prompt that defines the AI role.

    enable_thinking

    BOOLEAN

    Enables chain-of-thought reasoning mode (Qwen3 series). Default: false.

Return values

  • Returns the model response as TEXT.

  • Returns an error when the parameter is NULL or an empty string (""). For example, NULL returns AI_PROMPT requires at least 1 argument: prompt, and an empty string returns AI_PROMPT: prompt cannot be empty.

Examples

  • Basic inference (out of the box)

    SELECT AI_PROMPT('What is PolarDB-X? Answer in one sentence.');

    Sample output:

    AI_PROMPT
    ---------
    PolarDB-X is a cloud-native distributed database developed by Alibaba, compatible with the MySQL protocol, designed for high-concurrency real-time processing and analytics on massive datasets.
  • Specify a model

    --Use the faster Turbo model
    SELECT AI_PROMPT('Explain distributed databases in one sentence', 'AI_GATEWAY_LLM_MODEL');
    
    --Use the most powerful Max model
    SELECT AI_PROMPT('Explain distributed databases in one sentence', 'AI_GATEWAY_LLM_MODEL');
  • Set an AI role

    SELECT AI_PROMPT(
        'Please optimize this SQL: SELECT * FROM orders WHERE status = 1',
        'AI_GATEWAY_LLM_MODEL',
        '{"system_prompt": "You are a senior DBA specializing in SQL performance optimization."}'
    );
  • Enable chain-of-thought reasoning

    SELECT AI_PROMPT(
        'Analyze the time complexity and suggest optimizations: for(int i=0;i<n;i++) for(int j=i;j<n;j++) sum+=a[j];',
        'AI_GATEWAY_LLM_MODEL',
        '{"enable_thinking": true}'
    );
  • Generate descriptions for each row of table data

    SELECT
        name,
        AI_PROMPT(CONCAT('Describe this city in one sentence: ', name)) AS description
    FROM city
    LIMIT 3;

AI_EMBEDDING

Converts input text into a fixed-dimensional continuous vector (JSON array) for use in semantic search, clustering, recommendations, and similar scenarios.

Syntax

--Basic call using the default EMBEDDING model
SELECT AI_EMBEDDING(text)

--Specify a model
SELECT AI_EMBEDDING(text, model)

--Specify a model and vector dimensions
SELECT AI_EMBEDDING(text, model, options)

Parameters

  • text: Required. The input text. Supports character types (CHAR, VARCHAR, TEXT).

  • model: Optional. The name of the model to use. Defaults to the built-in EMBEDDING model AI_GATEWAY_EMBEDDING_MODEL.

  • options: Optional. A JSON string that specifies vector dimensions.

    Field

    Type

    Description

    dimension

    INT

    Vector dimension (determined by the model by default).

Return values

  • Returns a JSON array of floating-point numbers. The array length is determined by the model or the dimension parameter.

  • When the text parameter is NULL or an empty string (""), an error is returned, for example AI_EMBEDDING requires at least 1 argument: text.

Examples

  • Basic embedding

    SELECT AI_EMBEDDING('PolarDB-X is a distributed database');

    The result is a JSON array. Example:

    AI_EMBEDDING
    ------------
    [0.123, -0.456, 0.789, ...]
  • Specify vector dimensions

    SELECT AI_EMBEDDING(
        'PolarDB-X is a distributed database',
        'AI_GATEWAY_EMBEDDING_MODEL',
        '{"dimension": 512}'
    );
  • Persist vectors for reuse (compute once, reuse indefinitely)

    --Create a table with a vector column
    CREATE TABLE documents (
        id BIGINT PRIMARY KEY AUTO_INCREMENT,
        content TEXT,
        embedding JSON
    );
    
    --Batch generate and store vectors
    UPDATE documents
    SET embedding = AI_EMBEDDING(content)
    WHERE embedding IS NULL;

AI_SIMILARITY

Computes the semantic similarity between a query text and a candidate text (or a pre-stored vector), returning a score between 0 and 1. When the second parameter is a JSON array vector, the function computes similarity directly without making any API call, which significantly improves performance and is ideal for large-scale online retrieval.

Syntax

SELECT AI_SIMILARITY(query, text_or_vector [, similarity_type [, model]])

Parameters

Parameter

Type

Required

Description

query

STRING

Yes

The query text.

text_or_vector

STRING / JSON

Yes

Candidate text or a pre-stored vector (JSON array).

similarity_type

STRING

No

Similarity algorithm: cosine (cosine similarity, default), euclidean (Euclidean distance), dot (dot product).

model

STRING

No

The EMBEDDING model name. Uses the default model if not specified.

Return values

  • Returns a DOUBLE similarity score in the range [0, 1]. A higher value indicates greater similarity.

  • Returns an error when any parameter is NULL, for example AI_SIMILARITY requires at least 2 arguments: input1, input2.

Examples

  • Text-to-text similarity

    SELECT AI_SIMILARITY('cloud-native database', 'PolarDB-X is a distributed cloud-native database') AS score;

    Sample output:

    score
    -----
    0.87
  • Semantic search with pre-stored vectors (recommended)

    --Read vectors directly from the embedding column, with zero additional API calls
    SELECT id, name,
        AI_SIMILARITY('distributed transaction expert', embedding) AS score
    FROM resumes
    WHERE status = 'processed' AND embedding IS NOT NULL
    ORDER BY score DESC
    LIMIT 10;

AI_RANK

Uses a cross-encoder reranking model to perform deep semantic matching between a query and a candidate document. This function produces higher accuracy than vector cosine similarity, and is commonly used to rerank recalled results.

Syntax

SELECT AI_RANK(query, candidate [, model [, options]])

Parameters

  • query: Required. The query text. Supports character types (CHAR, VARCHAR, TEXT).

  • candidate: Required. The candidate text to compare against the query. Supports character types (CHAR, VARCHAR, TEXT).

  • model: Optional. The name of the model to use. Defaults to the built-in RERANK model AI_GATEWAY_RERANK_MODEL.

  • options: Optional. A JSON string that controls reranking parameters.

Return values

  • Returns a DOUBLE relevance score in the range [0, 1]. A higher value indicates greater relevance.

  • Returns an error when any parameter is empty or NULL, for example AI_RANK requires at least 2 arguments: query, candidate.

Note

Performance tip: AI_RANK calls a cross-encoder model, which has relatively high latency per call. Apply reranking only to recalled results (top 20 or fewer), and avoid using it directly on full-table scans.

Examples

  • Basic scoring

    SELECT AI_RANK(
        'How to optimize database query performance',
        'Top 10 best practices for database index design and query optimization'
    ) AS score;

    Sample output:

    score
    -----
    0.91
  • Rerank a list of documents

    SELECT id, title,
        AI_RANK('PolarDB-X distributed transactions', content) AS relevance
    FROM articles
    WHERE category = 'database'
    ORDER BY relevance DESC
    LIMIT 10;
  • Recommended: Two-stage retrieval (vector recall + reranking)

    SELECT id, name, summary, similarity_score,
        AI_RANK('Senior Java backend engineer', summary) AS rank_score
    FROM (
        SELECT id, name, summary,
            AI_SIMILARITY('Senior Java backend engineer', embedding) AS similarity_score
        FROM resumes
        WHERE embedding IS NOT NULL AND summary IS NOT NULL
        ORDER BY similarity_score DESC
        LIMIT 20
    ) recalled
    ORDER BY rank_score DESC;

AI_CLASSIFY

Classifies text into user-specified candidate labels through zero-shot classification. No training is required. Simply provide a list of candidate labels. Supports both single-label (default) and multi-label modes.

Syntax

SELECT AI_CLASSIFY(text, labels_json [, model [, options]])

Parameters

  • text: Required. The text to classify. Supports character types (CHAR, VARCHAR, TEXT).

  • labels_json: Required. A JSON array of candidate labels. The recommended number of labels is between 2 and 20.

  • model: Optional. The name of the model to use. Defaults to the built-in LLM model.

  • options: Optional. A JSON string.

    Field

    Type

    Description

    multi_label

    BOOLEAN

    Enables multi-label classification mode, returning a JSON array of matching labels. Default: false (single-label).

Return values

  • In single-label mode, returns the matched label as a string.

  • In multi-label mode, returns a JSON array of multiple labels.

  • Returns an error when the parameter is NULL or an empty string (""). For example, NULL returns AI_CLASSIFY requires at least 2 arguments, and an empty string returns AI_CLASSIFY: text cannot be empty.

Examples

  • Single-label classification (sentiment analysis)

    SELECT AI_CLASSIFY(
        'I have been using this product for a week. The quality is great and I highly recommend it!',
        '["positive", "negative", "neutral"]'
    ) AS sentiment;

    Sample output:

    sentiment
    ---------
    positive
  • Multi-label classification

    SELECT AI_CLASSIFY(
        'This article covers best practices for deploying distributed databases on Kubernetes',
        '["database", "cloud-native", "operations", "development"]',
        '',
        '{"multi_label": true}'
    ) AS tags;

    Sample output:

    tags
    ----
    ["database", "cloud-native", "operations"]
  • Batch classification with write-back

    UPDATE resumes
    SET category = AI_CLASSIFY(
        raw_text,
        '["frontend", "backend", "algorithm", "data", "operations", "other"]'
    )
    WHERE category IS NULL AND status = 'processed';

AI_EXTRACT

Extracts structured fields from unstructured text based on a specified JSON Schema and returns a JSON object. You can use functions such as JSON_EXTRACT to expand the result into columns.

Syntax

SELECT AI_EXTRACT(text, schema_json [, model])

Parameters

  • text: Required. The input text. Supports character types (CHAR, VARCHAR, TEXT).

  • schema_json: Required. A JSON string describing the fields to extract and their meanings.

  • model: Optional. The name of the model to use. Defaults to the built-in LLM model.

Return values

  • Returns a JSON object containing the extracted result for each field defined in the schema.

  • Returns an error when the parameter is NULL or an empty string ("").

Examples

  • Extract resume information

    SELECT AI_EXTRACT(
        'John Smith, 8 years of Java development experience, graduated from Stanford University CS department, previously worked at Google, proficient in Spring Boot, Kafka, and MySQL.',
        '{"name": "Full name", "experience_years": "Years of experience", "university": "University", "skills": "Skill list", "company": "Previous employer"}'
    ) AS info;

    Sample output:

    {
      "name": "John Smith",
      "experience_years": "8 years",
      "university": "Stanford University",
      "skills": "Java, Spring Boot, Kafka, MySQL",
      "company": "Google"
    }
  • Extract and expand into columns

    SELECT
        id,
        JSON_UNQUOTE(JSON_EXTRACT(info, '$.name'))       AS name,
        JSON_UNQUOTE(JSON_EXTRACT(info, '$.university')) AS university,
        JSON_UNQUOTE(JSON_EXTRACT(info, '$.skills'))     AS skills
    FROM (
        SELECT id,
            AI_EXTRACT(raw_text,
                '{"name":"Full name","university":"University","skills":"Skills"}') AS info
        FROM resumes
    ) t;

AI_SUMMARIZE

Compresses long text into a summary within a specified word count, preserving the key information. Supports specifying the output language and summary style.

Syntax

SELECT AI_SUMMARIZE(text, max_words [, model [, options]])

Parameters

  • text: Required. The input text. Supports character types (CHAR, VARCHAR, TEXT).

  • max_words: Required. The maximum word count for the summary. The model attempts to stay close to this limit. Set to 0 for no length restriction.

  • model: Optional. The name of the model to use. Defaults to the built-in LLM model.

  • options: Optional. A JSON string.

    Field

    Type

    Description

    language

    STRING

    Specifies the output language of the summary, such as "Chinese" or "English".

    style

    STRING

    Summary style. Set to "bullet_points" for a bullet-point list. Default: coherent paragraph.

Return values

  • Returns the summary content as TEXT.

  • Returns an error when the parameter is NULL or an empty string ("").

  • When max_words is negative, behavior is undefined; the model may return a brief summary. Use a meaningful positive integer.

Examples

  • Basic summary

    SELECT AI_SUMMARIZE(raw_text, 200) AS summary
    FROM resumes
    WHERE id = 1;
  • Specify the output language

    SELECT AI_SUMMARIZE(raw_text, 200, '', '{"language": "English"}') AS summary
    FROM resumes
    WHERE id = 1;
  • Bullet-point style

    SELECT AI_SUMMARIZE(raw_text, 300, '', '{"style": "bullet_points"}') AS summary
    FROM resumes
    WHERE id = 1;
  • Batch generate and store summaries

    UPDATE resumes
    SET summary = AI_SUMMARIZE(raw_text, 200)
    WHERE summary IS NULL AND status = 'processed';

AI_PARSE_DOCUMENT

Parses unstructured files such as PDFs and images from public URLs and converts them to plain text. The file type is automatically detected.

Syntax

SELECT AI_PARSE_DOCUMENT(url [, input_format [, model [, options]]])

Parameters

Parameter

Type

Required

Description

url

STRING

Yes

The public URL of the file.

input_format

STRING

No

File format hint. Default: auto (automatic detection). Supported values include pdf and image.

model

STRING

No

The DOCUMENT_PARSE model name. Defaults to AI_GATEWAY_DOCUMENT_PARSE_MODEL.

options

STRING

No

Additional options (JSON format).

Return values

  • Returns the parsed plain text content as TEXT.

  • When parsing fails, the function returns an error description text instead of throwing an exception.

Examples

  • Parse a public PDF

    SELECT AI_PARSE_DOCUMENT('https://example.com/report.pdf') AS content;
  • Specify the file format

    SELECT AI_PARSE_DOCUMENT('https://example.com/report.pdf', 'pdf') AS content;
  • Parse an image

    SELECT AI_PARSE_DOCUMENT('https://example.com/scan.jpg') AS content;
  • Chain into a processing pipeline (parse, extract, and summarize)

    SELECT
        AI_PARSE_DOCUMENT('https://example.com/cv.pdf') AS raw_text,
        AI_EXTRACT(
            AI_PARSE_DOCUMENT('https://example.com/cv.pdf'),
            '{"name":"Full name","skills":"Skills"}'
        ) AS structured,
        AI_SUMMARIZE(
            AI_PARSE_DOCUMENT('https://example.com/cv.pdf'), 200
        ) AS summary;
Note

Optimization tip: The example above calls AI_PARSE_DOCUMENT multiple times for each function. We recommend caching the parsed result in a temporary table or subquery to avoid redundant API calls.

AI_VL_EMBEDDING

Generates multimodal vectors from image URLs, video URLs, or plain text, enabling cross-modal image-text retrieval. The function automatically detects the input type: inputs starting with http:// or https:// are treated as images or videos, while other inputs are treated as text. You can also explicitly specify the type through the options parameter.

Supported content types

  • Text: Any non-URL string. Automatically recognized as text.

  • Image: jpg, jpeg, png, webp, bmp, tiff, tif, ico, dib, icns, sgi.

  • Video: mp4, avi, mov.

  • Base64 Data URI: data:image/... or data:video/....

Syntax

SELECT AI_VL_EMBEDDING(content [, model [, options]])

Parameters

  • content: Required. A text string, image/video URL, or Base64 Data URI.

  • model: Optional. The name of the model to use. Defaults to the built-in VL_EMBEDDING model AI_GATEWAY_VL_EMBEDDING_MODEL.

  • options: Optional. A JSON string.

    Field

    Type

    Description

    content_type

    STRING

    Explicitly specifies the content type: "text", "image", or "video". If not specified, the type is detected automatically.

    dimension

    INT

    Vector dimension (determined by the model by default).

    fps

    DOUBLE

    Video frame sampling rate (applicable to videos only).

Return values

  • Returns a JSON array of floating-point numbers.

Note

Text vectors and image/video vectors generated by AI_VL_EMBEDDING share the same multimodal semantic space, so you can directly compute similarity between them. This is different from the text-only vector space of AI_EMBEDDING. Do not mix vectors from the two functions.

Examples

  • Generate an image vector

    SELECT AI_VL_EMBEDDING('https://example.com/product.jpg') AS vec;
  • Generate a text vector (multimodal space)

    SELECT AI_VL_EMBEDDING('red dress') AS vec;
  • Generate a video vector with explicit parameters

    SELECT AI_VL_EMBEDDING(
        'https://example.com/clip.mp4',
        '',
        '{"content_type": "video", "dimension": 1024, "fps": 2.0}'
    ) AS vec;
  • Image-to-image search

    SELECT id, product_name,
        AI_SIMILARITY(
            AI_VL_EMBEDDING('https://example.com/query.jpg'),
            image_embedding
        ) AS similarity
    FROM products
    WHERE image_embedding IS NOT NULL
    ORDER BY similarity DESC
    LIMIT 10;
  • Cross-modal image-text retrieval

    --Combine text similarity and image similarity with weighted scoring
    SELECT id, product_name,
        (AI_SIMILARITY('red dress', text_embedding) * 0.4 +
         AI_SIMILARITY(AI_VL_EMBEDDING('https://example.com/red_dress.jpg'), image_embedding) * 0.6
        ) AS combined_score
    FROM products
    ORDER BY combined_score DESC
    LIMIT 20;

AI_TEXT2SQL

Converts a natural language query into an executable SQL statement. The function automatically discovers the table schema of the current database (selected by USE database) and sends it together with the natural language description to the LLM to generate the SQL. When the database contains many tables, the model first selects the relevant tables before generating the final SQL.

Syntax

--Basic call
SELECT AI_TEXT2SQL(prompt);

--Specify a model
SELECT AI_TEXT2SQL(prompt, model);

--Specify a model and generation parameters
SELECT AI_TEXT2SQL(prompt, model, options);

Parameters

  • prompt: Required. The natural language query description. Supports CHAR, VARCHAR, and TEXT types.

  • model: Optional. The name of the model to use. Defaults to the AI gateway LLM model AI_GATEWAY_LLM_MODEL.

  • options: Optional. A JSON string that controls LLM generation behavior (temperature, max_tokens, etc., same as AI_PROMPT).

Return value

  • Returns a TEXT value containing the SQL statement generated by the model.

  • Returns an error when prompt is NULL or an empty string ("").

Examples

  • Basic query generation

    --Switch to the target database before calling
    USE my_database;
    
    SELECT AI_TEXT2SQL('Find all users older than 30');

    Example output:

    AI_TEXT2SQL
    -----------
    SELECT * FROM users WHERE age > 30;
  • Cross-table aggregation

    SELECT AI_TEXT2SQL('Count the number of employees and average salary for each department');
  • Mixed Chinese and English input

    SELECT AI_TEXT2SQL('Find the top 10 best-selling products in the last 7 days');
  • Specify a model and temperature

    SELECT AI_TEXT2SQL(
        'Find the top 5 products by sales',
        'AI_GATEWAY_LLM_MODEL',
        '{"temperature": 0.1, "max_tokens": 500}'
    );
Note
  • AI_TEXT2SQL only generates the SQL string. It does not execute the SQL automatically. The generated SQL should be reviewed by the user or application before execution.

  • The function depends on the table schema of the current database. Before calling it, make sure you have switched to the target database with USE <database>.

  • When the database contains more than 10 tables, the model first identifies relevant tables before generating the SQL, which may result in two model invocations.

AI function and models

Built-in model overview

After the AI gateway starts, it automatically registers models of the following types and configures the optimal default model for each AI function:

Model type

Default model name

Applicable functions

Description

LLM

AI_GATEWAY_LLM_MODEL

AI_PROMPT, AI_CLASSIFY, AI_EXTRACT, AI_SUMMARIZE, AI_TEXT2SQL

Large language model for text generation, classification, extraction, and similar tasks.

EMBEDDING

AI_GATEWAY_EMBEDDING_MODEL

AI_EMBEDDING, AI_SIMILARITY

Text embedding model.

RERANK

AI_GATEWAY_RERANK_MODEL

AI_RANK

Cross-attention reranking model.

DOCUMENT_PARSE

AI_GATEWAY_DOCUMENT_PARSE_MODEL

AI_PARSE_DOCUMENT

Document parsing model.

VL_EMBEDDING

AI_GATEWAY_VL_EMBEDDING_MODEL

AI_VL_EMBEDDING

Multimodal embedding model.

Note

Model registration, updates, and management are handled automatically by the AI gateway, with no manual operation required. The AI gateway automatically selects the best model version based on the latest model capabilities. To view the actual registered model names and underlying mappings, use SHOW AI MODEL (Enterprise Edition).

View registered models

Enterprise Edition (SHOW AI MODEL / AI_DESCRIBE_MODEL)

  • Use the SHOW AI MODEL statement to view all registered AI model configurations, including built-in and user-defined models. To view the basic information of a specific model, use SHOW AI MODEL FROM <model_name>.

    --View all registered models
    SHOW AI MODEL;
    
    --View details of a specific model
    SHOW AI MODEL FROM AI_GATEWAY_LLM_MODEL;

    Output fields

    Column

    Description

    NAME

    The model configuration name (unique identifier).

    MODEL

    The underlying model identifier used in actual API calls.

    PROVIDER

    The model provider: dashscope, openai, or custom.

    ENDPOINT

    The API endpoint URL.

    STATUS

    The model status: ACTIVE (available) or INACTIVE (disabled).

    DESCRIPTION

    The model description.

    mysql> SHOW AI MODEL;
    +---------------------------------+--------------------+-----------+------------------+--------+-------------------------------+
    | NAME                            | MODEL              | PROVIDER  | ENDPOINT         | STATUS | DESCRIPTION                   |
    +---------------------------------+--------------------+-----------+------------------+--------+-------------------------------+
    | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | dashscope | (managed by AI gateway) | ACTIVE | Default LLM model (balanced)  |
    | AI_GATEWAY_LLM_MODEL_MAX        | qwen-max           | dashscope | (managed by AI gateway) | ACTIVE | LLM model (strongest)         |
    | AI_GATEWAY_LLM_MODEL_TURBO      | qwen-turbo         | dashscope | (managed by AI gateway) | ACTIVE | LLM model (fast and cheap)    |
    | AI_GATEWAY_EMBEDDING_MODEL      | text-embedding-v4  | dashscope | (managed by AI gateway) | ACTIVE | Default text embedding model  |
    | AI_GATEWAY_RERANK_MODEL         | qwen3-vl-rerank    | dashscope | (managed by AI gateway) | ACTIVE | Default reranking model       |
    | AI_GATEWAY_DOCUMENT_PARSE_MODEL | qwen-doc-turbo     | dashscope | (managed by AI gateway) | ACTIVE | Default document parse model  |
    | AI_GATEWAY_VL_EMBEDDING_MODEL   | qwen3-vl-embedding | dashscope | (managed by AI gateway) | ACTIVE | Default multimodal embedding  |
    +---------------------------------+--------------------+-----------+------------------+--------+-------------------------------+
  • Use SELECT AI_DESCRIBE_MODEL(model_name) to view the full details of a specific model — including the endpoint, provider, underlying model, API key (masked), creation and modification time, and status. The function returns a JSON string.

    SELECT AI_DESCRIBE_MODEL('AI_GATEWAY_LLM_MODEL');

    Output fields

    Field

    Description

    name

    The model configuration name (unique identifier).

    provider

    The model provider.

    endpoint

    The API endpoint URL.

    model

    The underlying model identifier.

    api_key

    The model-level API key. The value is masked when displayed (for example, sk-f****8jTh).

    description

    The model description.

    gmt_created

    The time when the model was registered.

    gmt_modified

    The time when the model was last modified.

    status

    The model status: ACTIVE (available) or INACTIVE (disabled).

View AI function configurations

Enterprise Edition (SHOW AI FUNCTION)

Use the SHOW AI FUNCTION statement to view all AI functions and their currently configured default models.

--View all AI functions
SHOW AI FUNCTION;

--View a specific function
SHOW AI FUNCTION FROM AI_PROMPT;

Output columns

Column

Description

FUNCTION

The AI function name.

DEFAULT_MODEL

The currently configured default model name.

ACTUAL_MODEL

The actual underlying model identifier corresponding to the default model.

DESCRIPTION

The function description.

mysql> SHOW AI FUNCTION;
+-------------------+---------------------------------+--------------------+----------------------------+
| FUNCTION          | DEFAULT_MODEL                   | ACTUAL_MODEL       | DESCRIPTION                |
+-------------------+---------------------------------+--------------------+----------------------------+
| AI_PROMPT         | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | AI prompt function         |
| AI_EMBEDDING      | AI_GATEWAY_EMBEDDING_MODEL      | text-embedding-v4  | AI embedding function      |
| AI_CLASSIFY       | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | AI classify function       |
| AI_RANK           | AI_GATEWAY_RERANK_MODEL         | qwen3-vl-rerank    | AI rank function           |
| AI_SIMILARITY     | AI_GATEWAY_EMBEDDING_MODEL      | text-embedding-v4  | AI similarity function     |
| AI_EXTRACT        | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | AI extract function        |
| AI_SUMMARIZE      | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | AI summarize function      |
| AI_PARSE_DOCUMENT | AI_GATEWAY_DOCUMENT_PARSE_MODEL | qwen-doc-turbo     | AI parse document function |
| AI_VL_EMBEDDING   | AI_GATEWAY_VL_EMBEDDING_MODEL   | qwen3-vl-embedding | AI vl embedding function   |
| AI_TEXT2SQL       | AI_GATEWAY_LLM_MODEL            | qwen3.5-plus       | AI text2sql function       |
+-------------------+---------------------------------+--------------------+----------------------------+

Change the default model of an AI function

Note

Make sure the model type matches the function when changing the default model. For example, AI_EMBEDDING requires an EMBEDDING-type model. If you assign a mismatched model type as the default, subsequent calls to the function may return errors.

Enterprise Edition (AI_UPDATE_FUNCTION)

Use the AI_UPDATE_FUNCTION function to dynamically change the default model of a specified AI function. The change takes effect immediately across all CN nodes in the cluster without a restart.

Syntax

SELECT AI_UPDATE_FUNCTION(function_name, model_name);

Parameters

Parameter

Type

Required

Description

function_name

STRING

Yes

The AI function name (case-insensitive), such as AI_PROMPT or AI_EMBEDDING.

model_name

STRING

Yes

A registered model name (must exist in SHOW AI MODEL).

Return values

  • Returns the string "OK" on success.

  • Returns the error Unknown AI function if the function name is invalid.

  • Returns the error Model not found if the model name does not exist.

Examples

  • Change the default model of AI_PROMPT to AI_GATEWAY_LLM_MODEL.

    SELECT AI_UPDATE_FUNCTION('AI_PROMPT', 'AI_GATEWAY_LLM_MODEL');
    -- Returns: OK
  • Verify the change

    SHOW AI FUNCTION FROM AI_PROMPT;
    -- The DEFAULT_MODEL column shows: AI_GATEWAY_LLM_MODEL
  • Use a custom model as the default

    --Register a custom model first
    SELECT AI_REGISTER_MODEL('my_gpt4', 'openai', 'https://api.openai.com/v1/chat/completions', 'gpt-4', '{"api_key":"sk-xxxx"}');
    
    --Set the custom model as the default for AI_PROMPT
    SELECT AI_UPDATE_FUNCTION('AI_PROMPT', 'my_gpt4');

Specify a model for AI function calls

Each AI function is bound by default to a recommended model. If you do not specify a model name when calling a function, the system automatically uses the default model for the corresponding type. To switch to another built-in model, simply pass the model name as the second parameter when calling the function.

Note

Different AI functions require specific model types. For example, AI_EMBEDDING requires an EMBEDDING-type model, AI_RANK requires a RERANK-type model, and AI_PARSE_DOCUMENT requires a DOCUMENT_PARSE-type model. Do not pass a mismatched model type to any function.

--Default call using AI_GATEWAY_LLM_MODEL
SELECT AI_PROMPT('Explain distributed databases in one sentence');

--Switch to the faster Turbo model
SELECT AI_PROMPT('Explain distributed databases in one sentence', 'AI_GATEWAY_LLM_MODEL');

--Switch to the most powerful Max model
SELECT AI_PROMPT('Explain distributed databases in one sentence', 'AI_GATEWAY_LLM_MODEL');

Best practices

Now that you are familiar with the basics of each AI function, the following scenarios demonstrate how to combine them to solve complex business problems.

Two-stage semantic retrieval (vector recall + cross-encoder reranking)

For enterprise-grade semantic retrieval, vector similarity alone may not provide sufficient recall precision. A recommended approach is two-stage retrieval: first use AI_SIMILARITY with pre-stored vectors for millisecond-level recall, then apply AI_RANK to the top-N candidates for high-precision scoring to produce the most relevant results.

--1. Offline: Batch compute and store vectors
UPDATE resumes
SET embedding = AI_EMBEDDING(raw_text)
WHERE embedding IS NULL;

--2. Online: Two-stage retrieval in a single SQL statement
SELECT id, name, summary, similarity_score,
    AI_RANK('Senior Java backend engineer', summary) AS rank_score
FROM (
    SELECT id, name, summary,
        AI_SIMILARITY('Senior Java backend engineer', embedding) AS similarity_score
    FROM resumes
    WHERE embedding IS NOT NULL AND summary IS NOT NULL
    ORDER BY similarity_score DESC
    LIMIT 20
) recalled
ORDER BY rank_score DESC;

Key points:

  • Compute vectors offline once and store them. During online retrieval, read them directly to avoid repeated Embedding API calls.

  • The inner query performs vector computation only (no API calls). The outer AI_RANK reranks only the top 20 candidates, keeping overall latency under control.

Unstructured-to-structured data pipeline

By chaining AI functions such as parsing, extraction, summarization, classification, and embedding, you can transform PDFs, images, and other unstructured data into analyzable structured data and persist it in a single SQL statement.

INSERT INTO resumes (raw_text, structured_info, summary, category, embedding)
SELECT
    AI_PARSE_DOCUMENT(file_url) AS raw_text,
    AI_EXTRACT(
        AI_PARSE_DOCUMENT(file_url),
        '{"name":"Full name","skills":"Skills","experience_years":"Years of experience"}'
    ) AS structured_info,
    AI_SUMMARIZE(AI_PARSE_DOCUMENT(file_url), 200) AS summary,
    AI_CLASSIFY(
        AI_PARSE_DOCUMENT(file_url),
        '["frontend", "backend", "algorithm", "data", "operations", "other"]'
    ) AS category,
    AI_EMBEDDING(AI_PARSE_DOCUMENT(file_url)) AS embedding
FROM file_inbox
WHERE status = 'pending';
Note

Optimization tip: The example above calls AI_PARSE_DOCUMENT multiple times for each function. We recommend caching the parsed result in a temporary table or subquery to avoid redundant API calls.

Multimodal product retrieval (image-to-image + cross-modal search)

With AI_VL_EMBEDDING, you can represent both images and text in a unified multimodal semantic space, enabling an integrated cross-modal product retrieval system.

--1. Product ingestion: Store both multimodal and text-only vectors
INSERT INTO products (name, image_url, text_embedding, image_embedding)
VALUES (
    ?,
    ?,
    AI_EMBEDDING(?),
    AI_VL_EMBEDDING(?)
);
--3. Cross-modal retrieval (weighted combination of text and image similarity)
SELECT id, product_name,
    (AI_SIMILARITY('red dress', text_embedding) * 0.4 +
     AI_SIMILARITY(AI_VL_EMBEDDING('https://example.com/red_dress.jpg'), image_embedding) * 0.6
    ) AS combined_score
FROM products
ORDER BY combined_score DESC
LIMIT 20;

Key points:

  • Vectors generated by AI_VL_EMBEDDING and AI_EMBEDDING reside in different semantic spaces. Do not mix vectors across these two functions. We recommend storing text_embedding and image_embedding separately in your table.

  • Adjust the weighting coefficients based on your business needs. For image-heavy scenarios, set the image weight to 0.7 or higher. For text-heavy scenarios, set the text weight to 0.7 or higher.

Batch data governance (classification, anonymization, cleaning)

With the batch processing capability of AI functions, you can perform semantic-level data governance directly in SQL without writing additional ETL programs.

--Batch classification
UPDATE feedback
SET sentiment = AI_CLASSIFY(content, '["positive", "negative", "neutral"]')
WHERE sentiment IS NULL;
--Batch structured extraction
UPDATE orders
SET parsed_info = AI_EXTRACT(
    order_notes,
    '{"customer_name":"Customer name","delivery_address":"Delivery address","special_requirements":"Special requirements"}'
)
WHERE order_notes IS NOT NULL AND parsed_info IS NULL;
--Batch summarization
UPDATE articles
SET summary = AI_SUMMARIZE(content, 200)
WHERE summary IS NULL;

Key points:

  • We recommend processing updates in batches (for example, by primary key range) to avoid long-running SQL statements that tie up resources on very large tables.

  • For latency-sensitive online scenarios, pre-compute and store results such as vectors and summaries, then read them directly at query time.