# AI Functions

## Install AI Functions

To install AI Functions, navigate to **AI > AI & ML Functions**, select the deployment on which to install AI Functions. In the **AI Functions** tab, select **Install**, review the **AI Functions Summary** and then select **Deploy**.

Once the AI Functions are installed, query them in the SQL Editor or SingleStore notebooks. SingleStore provides the following AI Functions:

| **Category**                                                    | **Function**               |
| --------------------------------------------------------------- | -------------------------- |
| Text Processing Functions                                       | `AI_COMPLETE(text, model)` |
| `AI_SENTIMENT(text, model)`                                     |                            |
| `AI_TRANSLATE(text, source_languages, target_languages, model)` |                            |
| `AI_SUMMARIZE(text, model, max_lengths)`                        |                            |
| `AI_CLASSIFY(text, categories, model)`                          |                            |
| `AI_EXTRACT(text, questions, model)`                            |                            |
| Embedding Function                                              |                            |
| `EMBED_TEXT(text, model)`                                       |                            |

## Edit AI Functions

To edit AI Functions, navigate to **Settings** in the right navigation of the **AI Functions** tab and select **Edit**. Alternatively, select the ellipsis (vertical three dots) in the right and select **Edit AI Functions**. On the **Edit AI Functions** page, view or select the following:

| **WorkspaceGroup**  | Theworkspacegroup in which the AI Function is installed and running.                                                                                                                                                                                                                                                                            |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Models**          | Default models used by AI Functions for inference and embedding.<ul> <li><strong>LLM Model</strong>: Uses Anthropic’s Claude model family for inference.</li> <li><strong>Embedding Model</strong>: Uses an optimized embedding model for text vectorization. Supported models include the Qwen and Amazon Titan embedding families.</li> </ul> |
| **Settings**        | <ul> <li><strong>Container Region</strong>: Select the region of your container.</li> <li><strong>Scaling</strong>: Select the minimum and maximum active replica. <blockquote> <p><strong>📝 Note</strong>: <p>Auto-scale depends upon the container load.</p></p> </blockquote> </li> </ul>                                                   |
| **Cost Estimation** | View the cost estimation of LLM Model, Embedding Model, and Compute. In Compute, runtime cost scales with the replica count.                                                                                                                                                                                                                    |
| **Region**          | View the region of the following:<ul> <li>Workspace Group</li> <li>Container</li> <li>LLM Model</li> <li>Embedding Model</li> </ul>                                                                                                                                                                                                             |

Select **Next**, review the changes, and select **Save** to save your settings.

## Uninstall AI Functions

To uninstall AI Functions, select the ellipsis (vertical three dots) in the right and then select **Uninstall AI Functions**. Confirm the uninstallation and select **Uninstall**.

## Text Processing Functions

## AI\_COMPLETE

Provides batched LLM powered completion of every input text. Used for general purpose text generation, completion, and complex reasoning.

## Syntax

```sql
AI_COMPLETE(text, model)
```

## Arguments

* `text`: A prompt.
* `model`: An LLM model.

## Return Type

`string`

## Usage

| Basic usage with the default model | `SELECT cluster.AI_COMPLETE('Life is like a box of') AS completion;`                                        |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Basic usage with a specific model  | `SELECT cluster.AI_COMPLETE('Life is like a box of', model => 'anthropic-claude-3-5-haiku') as completion;` |
| Input example on database          | `SELECT cluster.AI_COMPLETE(column_1) FROM table;`                                                          |

## AI\_SENTIMENT

Provides sentiment classification and score for all user-defined inputs.

## Syntax

```sql
AI_SENTIMENT(text, model)
```

## Arguments

* `text`: A prompt.
* `model`: An LLM model.

## Return Type

`string`

## Usage

| Basic usage with default model  | `SELECT cluster.AI_SENTIMENT('The migration tool saved us hours, but the error messages were completely cryptic      and we had to open three support tickets just to get past the setup.') AS sentiment;`                               |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected model | `SELECT cluster.AI_SENTIMENT('The migration tool saved us hours, but the error messages were completely cryptic      and we had to open three support tickets just to get past the setup.', 'anthropic-claude-3-5-haiku') as sentiment;` |
| Input example on database       | `SELECT cluster.AI_SENTIMENT(column_1) FROM table;`                                                                                                                                                                                      |

## AI\_TRANSLATE

Provides translation of user-provided documents from source language to target language. Supports multi-language translation.

## Syntax

```sql
AI_TRANSLATE(text, source_languages, target_languages, model)
```

## Arguments

* `text`: A prompt.
* `source_languages`: The language in which the prompt is written.
* `target_languages`: The language to which the prompt gets translated.
* `model`: An LLM model.

## Return Type

`string`

## Usage

| Basic usage with default model  | `SELECT cluster.AI_TRANSLATE(   '平素より大変お世話になっております。株式会社テクノソリューションズの田中と申します。先日よりご利用いただいておりますデータ移行サービスについて、    重大な問題が発生しておりますため、緊急のご連絡を差し上げております。昨日の午後3時頃より、移行ジョブが途中で停止し、エラーログには「接続タイムアウト」    と記録されております。弊社のシステム管理者が調査いたしましたが、原因の特定には至っておりません。本件は弊社の本番環境に影響を及ぼしており、    業務に支障をきたしております。至急、担当エンジニアよりご連絡いただけますようお願い申し上げます。何卒よろしくお願いいたします。','Japanese','English') AS translated_escalation;`                          |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected model | `SELECT cluster.AI_TRANSLATE('平素より大変お世話になっております。株式会社テクノソリューションズの田中と申します。     先日よりご利用いただいておりますデータ移行サービスについて、重大な問題が発生しておりますため、緊急のご連絡を差し上げております。     昨日の午後3時頃より、移行ジョブが途中で停止し、エラーログには「接続タイムアウト」と記録されております。弊社のシステム管理者が調査いたしましたが、     原因の特定には至っておりません。本件は弊社の本番環境に影響を及ぼしており、業務に支障をきたしております。至急、     担当エンジニアよりご連絡いただけますようお願い申し上げます。何卒よろしくお願いいたします。','Japanese','English', 'anthropic-claude-3-5-haiku') as translation;` |
| Input example on database       | `SELECT cluster.AI_TRANSLATE(column_1, "source_language", "target_language") FROM table;`                                                                                                                                                                                                                                                                                                                       |

## AI\_SUMMARIZE

Provides summary of user-provided documents within the specified length.

## Syntax

```sql
AI_SUMMARIZE(text, model, max_lengths)
```

## Arguments

* `text`: A prompt.
* `model`: An LLM model.
* `max_lengths`: Maximum length of the summary.

## Return Type

`string`

## Usage

| Basic usage with default model and length | `SELECT cluster.AI_SUMMARIZE(     'At 14:32 UTC, our monitoring system detected elevated error rates on the primary ingestion pipeline.      The on-call engineer was paged at 14:35. Initial investigation pointed to a misconfigured rate limit      introduced during the 14:00 deployment. A rollback was initiated at 14:50 and completed at 15:02.      Error rates returned to baseline by 15:05. Total customer-facing impact: approximately 33 minutes of degraded write throughput.') AS incident_one_liner;`                                 |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected model           | `SELECT cluster.AI_SUMMARIZE(     'At 14:32 UTC, our monitoring system detected elevated error rates on the primary ingestion pipeline.      The on-call engineer was paged at 14:35. Initial investigation pointed to a misconfigured rate limit      introduced during the 14:00 deployment. A rollback was initiated at 14:50 and completed at 15:02.      Error rates returned to baseline by 15:05. Total customer-facing impact: approximately 33 minutes of degraded write throughput.','anthropic-claude-3-5-haiku',15) AS incident_one_liner;` |
| Input example on database                 | `SELECT cluster.AI_SUMMARIZE(column_1) FROM table;`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

## AI\_CLASSIFY

Provides classification of each input text into one of the given categories or labels.

## Syntax

```sql
AI_CLASSIFY(text, categories, model)
```

## Arguments

* `text`: A prompt.
* `categories`: Categories for classification.
* `model`: An LLM model.

## Return Type

`string`

## Usage

| Basic usage with default model  | `SELECT cluster.AI_CLASSIFY(   'Hi, I was charged twice for my subscription this month. I have already checked my payment history and both transactions are showing as completed.',   '["billing", "technical_issue", "account_access", "feature_request", "abuse_report"]') AS assigned_queue;`                            |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected model | `SELECT cluster.AI_CLASSIFY(  'Hi, I was charged twice for my subscription this month. I have already checked my payment history and both transactions are showing as completed.',  '["billing", "technical_issue", "account_access", "feature_request", "abuse_report"]','anthropic-claude-3-5-haiku') AS assigned_queue;` |
| Input example on database       | `SELECT cluster.AI_CLASSIFY(column_1, categories) FROM table;`                                                                                                                                                                                                                                                              |

## AI\_EXTRACT

Extracts information from a block or text based on the specified natural language question.

## Syntax

```sql
AI_EXTRACT(text, questions, model)
```

## Arguments

* `text`: A prompt.
* `questions`: Input natural language question on which the LLM model extracts information.
* `model`: An LLM model.

## Return Type

`string`

## Usage

| Basic usage with default model  | `SELECT   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'What is the contract expiration date?'   ) AS expiration_date,   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'What is the total contract value?'   ) AS contract_value,   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'How many days notice is required for termination?'   ) AS termination_notice;`                               |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected model | `SELECT   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'What is the contract expiration date?'   ) AS expiration_date,   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'What is the total contract value?'   ) AS contract_value,   cluster.AI_EXTRACT(     'This Service Agreement is entered into on March 1, 2025 between Acme Corp and DataStream Inc. The total contract value is $240,000 USD, payable in quarterly installments. The agreement expires on February 28, 2027, with a 60-day written notice required for termination.',     'How many days notice is required for termination?', 'anthropic-claude-3-5-haiku'   ) AS termination_notice;` |
| Input example on database       | `SELECT cluster.AI_EXTRACT(column_1, question) FROM table;`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

## Embedding Function

## EMBED\_TEXT

Provides batched embeddings of all input text. Converts text into high-dimensional vector embeddings for semantic search and RAG applications.

## Syntax

```sql
EMBED_TEXT(text, model)
```

## Arguments

* `text`: A prompt.
* `model`: An embedding model.

## Return Type

`bytes`

## Usage

| Basic usage with default model            | `SELECT cluster.EMBED_TEXT('Lightweight running shoes with breathable mesh fabric, cushioned soles,      and flexible support designed for daily workouts and long-distance comfort.') AS embedding;`                            |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic usage with selected embedding model | `SELECT cluster.EMBED_TEXT('Lightweight running shoes with breathable mesh fabric, cushioned soles,      and flexible support designed for daily workouts and long-distance comfort.', 'shared-qwen3-embed-0-6b') as embedding;` |
| Input example on database                 | `SELECT cluster.EMBED_TEXT(column_1) FROM table;`                                                                                                                                                                                |

## Examples

The following examples demonstrate how to use AI functions with the following `customer_reviews` table.

```sql
CREATE DATABASE reviews;

USE reviews;

CREATE TABLE customer_reviews (
   review_id INT PRIMARY KEY,
   product_id VARCHAR(50),
   product_name VARCHAR(255),
   customer_name VARCHAR(100),
   review_text TEXT,
   rating INT,
   review_date DATETIME,
   language VARCHAR(20) DEFAULT 'English',
   response_text TEXT,
   review_embedding BLOB
);

-- Insert data
INSERT INTO customer_reviews (
   review_id,
   product_id,
   product_name,
   customer_name,
   review_text,
   rating,
   review_date,
   language
) VALUES
(1, 'PROD-101', 'Wireless Headphones', 'John Smith',
'These headphones are amazing! The sound quality is crystal clear and the battery lasts for days. Highly recommend for anyone looking for quality audio.',
5, '2026-05-01', 'English'),

(2, 'PROD-101', 'Wireless Headphones', 'Maria Garcia',
'Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful.',
1, '2026-05-02', 'English'),

(3, 'PROD-102', 'Smart Watch', 'David Lee',
'Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.',
4, '2026-05-03', 'English'),

(4, 'PROD-101', 'Wireless Headphones', 'Sophie Martin',
'Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.',
5, '2026-05-04', 'French'),

(5, 'PROD-103', 'Laptop Stand', 'Ahmed Hassan',
'Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.',
5, '2026-05-05', 'English');
```

## Generate Follow-up Questions for Negative Reviews

The following example uses the `AI_COMPLETE` function to generate follow-up questions for negative reviews:

```sql
SELECT
    review_id,
    customer_name,
    product_name,
    review_text,
    cluster.AI_COMPLETE(
        CONCAT(
            'Based on this negative review: "',
            review_text,
            '", generate three specific follow-up questions to better understand the issue.'
        )
    ) AS follow_up_questions
FROM customer_reviews
WHERE rating <= 2;

```

```output

+-----------+----------------+----------------------+--------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| review_id | customer_name  | product_name         | review_text                                                  | follow_up_questions                                                                                                                                                                               |
+-----------+----------------+----------------------+--------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 2         | Maria Garcia   | Wireless Headphones  | Disappointed with the build quality. They broke after just   | 1. Can you describe exactly how the product broke and in what specific way?                                                                                                                       |
|           |                |                      | two weeks of normal use. Customer service was unhelpful.     | 2. Did you contact customer service through phone, email, or another method, and what precisely did they say that made you feel they were unhelpful?                                              |
|           |                |                      |                                                              | 3. What type of normal use were you subjecting the product to when it broke?                                                                                                                      |
+-----------+----------------+----------------------+--------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
```

## Compare Customer Ratings with AI Sentiment

The following example uses the `AI_SENTIMENT` function to compare customer ratings with AI-generated sentiment analysis:

```sql
SELECT
    review_id,
    customer_name,
    product_name,
    rating AS star_rating,
    review_text,
    cluster.AI_SENTIMENT(review_text) AS ai_sentiment
FROM customer_reviews
ORDER BY review_date DESC;

```

```output

+-----------+----------------+----------------------+-------------+---------------------------------------------------------------------------------------------------------------------+----------------------------------------------+
| review_id | customer_name  | product_name         | star_rating | review_text                                                                                                         | ai_sentiment                                 |
+-----------+----------------+----------------------+-------------+---------------------------------------------------------------------------------------------------------------------+----------------------------------------------+
| 3         | David Lee      | Smart Watch          | 4           | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.          | {'sentiment': 'neutral', 'score': '0.5'}     |
| 1         | John Smith     | Wireless Headphones  | 5           | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days.                    | {'sentiment': 'positive', 'score': '0.9'}    |
| 5         | Ahmed Hassan   | Laptop Stand         | 5           | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.        | {'sentiment': 'positive', 'score': '0.95'}   |
| 4         | Sophie Martin  | Wireless Headphones  | 5           | Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.                            | {'sentiment': 'positive', 'score': '0.90'}   |
| 2         | Maria Garcia   | Wireless Headphones  | 1           | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful. | {'sentiment': 'negative', 'score': '0.85'}   |
+-----------+----------------+----------------------+-------------+---------------------------------------------------------------------------------------------------------------------+----------------------------------------------+
```

## Standardize Reviews in English

The following example uses the `AI_TRANSLATE` function to standardize the reviews in English language:

```sql
SELECT
    review_id,
    customer_name,
    product_name,
    language AS original_language,
    review_text AS original_review,
    CASE
        WHEN language = 'English' THEN review_text
        ELSE cluster.AI_TRANSLATE(
            review_text,
            language,
            'English'
        )
    END AS standardized_review_english
FROM customer_reviews
ORDER BY review_date DESC;

```

```output

+-----------+----------------+----------------------+-------------------+---------------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+
| review_id | customer_name  | product_name         | original_language | original_review                                                                                                     | standardized_review_english                                                                                         |
+-----------+----------------+----------------------+-------------------+---------------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+
| 3         | David Lee      | Smart Watch          | English           | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.          | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.          |
| 1         | John Smith     | Wireless Headphones  | English           | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days.                    | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days.                    |
| 5         | Ahmed Hassan   | Laptop Stand         | English           | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.        | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.        |
| 4         | Sophie Martin  | Wireless Headphones  | French            | Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.                            | Excellent sound quality! I use them every day for work and leisure.                                                 |
| 2         | Maria Garcia   | Wireless Headphones  | English           | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful. | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful. |
+-----------+----------------+----------------------+-------------------+---------------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+
```

## Generate Product-Level Summaries

The following example uses the `AI_SUMMARIZE` function to generate product-level summaries from customer reviews:

```sql
SELECT
    product_id,
    product_name,
    COUNT(*) AS review_count,
    AVG(rating) AS avg_rating,
    cluster.AI_SUMMARIZE(
        GROUP_CONCAT(review_text SEPARATOR '. ')
    ) AS product_summary
FROM customer_reviews
GROUP BY product_id, product_name;

```

```output

+------------+----------------------+--------------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| product_id | product_name         | review_count | avg_rating | product_summary                                                                                                                                                   |
+------------+----------------------+--------------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| PROD-103   | Laptop Stand         | 1            | 5.0000     | Excellent ergonomic home office solution with sturdy construction and adjustable height, providing good value.                                                    |
| PROD-101   | Wireless Headphones  | 3            | 3.6667     | Mixed reviews for headphones: praised for excellent sound quality and long battery life, but criticized for poor durability and potential customer service issues.|
| PROD-102   | Smart Watch          | 1            | 4.0000     | Fitness tracker offers good value, though battery life is shorter than expected.                                                                                  |
+------------+----------------------+--------------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
```

## Classify Review Intent

The following example uses the `AI_CLASSIFY` function to classify the review intent:

```sql
SELECT
    review_id,
    customer_name,
    product_name,
    rating,
    review_text,
    cluster.AI_CLASSIFY(
        review_text,
        '[praise, complaint, suggestion, question, comparison]'
    ) AS review_intent
FROM customer_reviews
ORDER BY review_date DESC;

```

```output

+-----------+----------------+----------------------+--------+---------------------------------------------------------------------------------------------------------------------+---------------+
| review_id | customer_name  | product_name         | rating | review_text                                                                                                         | review_intent |
+-----------+----------------+----------------------+--------+---------------------------------------------------------------------------------------------------------------------+---------------+
| 3         | David Lee      | Smart Watch          | 4      | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.          | complaint     |
| 1         | John Smith     | Wireless Headphones  | 5      | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days.                    | praise        |
| 5         | Ahmed Hassan   | Laptop Stand         | 5      | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.        | praise        |
| 4         | Sophie Martin  | Wireless Headphones  | 5      | Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.                            | praise        |
| 2         | Maria Garcia   | Wireless Headphones  | 1      | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful. | complaint     |               
+-----------+----------------+----------------------+--------+---------------------------------------------------------------------------------------------------------------------+---------------+

```

## Extract Multiple Insights

The following example uses the `AI_EXTRACT` function to extract multiple insights from customer reviews:

```sql
SELECT
    review_id,
    product_name,
    review_text,
    cluster.AI_EXTRACT(
        review_text,
        'What product features are mentioned?'
    ) AS features_mentioned,
    cluster.AI_EXTRACT(
        review_text,
        'How long has the customer used this product?'
    ) AS usage_duration
FROM customer_reviews;

```

```output

+-----------+----------------------+--------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------+-----------------------------+
| review_id | product_name         | review_text                                                                                                  | features_mentioned                                            | usage_duration              |
+-----------+----------------------+--------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------+-----------------------------+
| 5         | Laptop Stand         | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny. | Sturdy construction, adjustable height                        | Not specified in the review |
| 2         | Wireless Headphones  | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service         | Build quality issues, broke after two weeks was unhelpful.    | Two weeks                   |                                                                                         
| 4         | Wireless Headphones  | Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.                     | Sound quality                                                 | Daily (ongoing)             |
| 3         | Smart Watch          | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.   | Battery life (shorter than advertised), good value for price. | Not specified in the review |
| 1         | Wireless Headphones  | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days.             | Sound quality (crystal clear), long battery life              | Not specified in the review |
+-----------+----------------------+--------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------+-----------------------------+

```

## Perform Semantic Search

The following example uses the `EMBED_TEXT` function to perform semantic search on customer reviews.

```sql
SET batch_external_functions = AUTO;

SELECT
   review_id,
   product_name,
   review_text,
   cluster.EMBED_TEXT(review_text) AS review_embedding
FROM customer_reviews;

UPDATE customer_reviews
SET review_embedding = cluster.EMBED_TEXT(review_text)
WHERE review_embedding IS NULL;

WITH search_query AS (
   SELECT cluster.EMBED_TEXT(
       'battery problems and short lifespan'
   ) AS query_embedding
)
SELECT
   cr.review_id,
   cr.product_name,
   cr.review_text,
   cr.rating,
   DOT_PRODUCT(
       cr.review_embedding,
       sq.query_embedding
   ) AS relevance_score
FROM customer_reviews cr,
    search_query sq
WHERE cr.review_embedding IS NOT NULL
ORDER BY relevance_score DESC;

```

```output

+-----------+---------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+--------+-----------------+
| review_id | product_name        | review_text                                                                                                                                            | rating | relevance_score |
+-----------+---------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+--------+-----------------+
| 3         | Smart Watch         | Great fitness tracker, but the battery life is shorter than advertised. Overall, good value for the price.                                             | 4      | NULL            |
| 1         | Wireless Headphones | These headphones are amazing! The sound quality is crystal clear and the battery lasts for days. Highly recommend for anyone looking for quality audio.| 5      | NULL            |
| 2         | Wireless Headphones | Disappointed with the build quality. They broke after just two weeks of normal use. Customer service was unhelpful.                                    | 1      | NULL            |
| 4         | Wireless Headphones | Excellente qualité sonore! Je les utilise tous les jours pour le travail et les loisirs.                                                               | 5      | NULL            |
| 5         | Laptop Stand        | Perfect ergonomic solution for my home office. Sturdy construction and adjustable height. Worth every penny.                                           | 5      | NULL            |
+-----------+---------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+--------+-----------------+

```

## Complete Customer Insights

The following example uses the `AI_SUMMARIZE` and `AI_EXTRACT` functions to generate complete customer insights for each product:

```sql
SELECT
    product_id,
    product_name,
    COUNT(*) AS total_reviews,
    AVG(rating) AS avg_rating,
    cluster.AI_SUMMARIZE(
        GROUP_CONCAT(review_text SEPARATOR '. ')
    ) AS overview,
    cluster.AI_EXTRACT(
        GROUP_CONCAT(review_text SEPARATOR '. '),
        'What are the top three issues customers mention?'
    ) AS top_issues,
    cluster.AI_EXTRACT(
        GROUP_CONCAT(review_text SEPARATOR '. '),
        'What do customers love most about this product?'
    ) AS top_strengths
FROM customer_reviews
GROUP BY product_id, product_name;

```

```output

+------------+----------------------+---------------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------+---------------------------------------------+
| product_id | product_name         | total_reviews | avg_rating | overview                                                                                                                                                            | top_issues                                                               | top_strengths                               |
+------------+----------------------+---------------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------+---------------------------------------------+
| PROD-103   | Laptop Stand         | 1             | 5.0000     | Excellent ergonomic home office solution with sturdy construction and adjustable height, providing good value.                                                      | 1. Sturdy construction 2. Adjustable height 3. Good value for money      | Sturdy construction and adjustable height   |
| PROD-101   | Wireless Headphones  | 3             | 3.6667     | Mixed reviews for headphones: praised for excellent sound quality and long battery life, but criticized for poor durability and potential customer service issues.  | 1. Sound quality 2. Battery life 3. Build quality (durability)           | Sound quality and battery life              |                                                                         |                                             |
| PROD-102   | Smart Watch          | 1             | 4.0000     | Fitness tracker offers good value, though battery life is shorter than expected.                                                                                    | 1. Battery life 2. Price 3. Functionality                                | Good value for the price                    |
+------------+----------------------+---------------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------+---------------------------------------------+

```

## Example Notebook

The following notebook demonstrates AI Functions:

## Usage Recommendations for AI Functions

To optimize performance and control costs when using AI Functions, SingleStore recommends the following:

* Use Common Table Expressions (CTEs) to filter rows before making calls to large language models (LLMs). The query engine currently sends data to the LLM before applying LLM or `WHERE` filters.
* LLM calls are expensive. Begin with a small dataset to evaluate response quality and verify the results meet the requirements before scaling up.
* Enterprise plans support three model providers; Aura, Amazon Bedrock, and Azure AI Services. Data is processed according to each provider’s policies. If a row violates provider rules, the system fails the batch that includes the row and returns errors for these rows.
* Strict usage quotas apply per model and per organization. These quotas are not configurable by end users. For higher usage limits, contact [SingleStore Support](https://support.singlestore.com/). Self-service quota configuration will be available in the future.

***

Modified at: May 22, 2026

Source: [/cloud/ai/ai-ml-functions/ai-functions/](https://docs.singlestore.com/cloud/ai/ai-ml-functions/ai-functions/)

(An index of the documentation is available at /llms.txt)
