5.8.1 Running Retrieval-Augmented Generation

The ML_RAG routine runs retrieval-augmented generation which aims to generate more accurate responses for your queries.

For context retrieval, the ML_RAG routine uses the name of the embedding model used to embed the input query to find relevant vector store tables that contain vector embeddings from the same embedding model.

This topic contains the following sections:

Before You Begin

Retrieving Context and Generating Relevant Content

To enter a natural-language query, retrieve the context, and generate results using RAG, perform the following steps:

  1. Optionally, to speed up vector processing, load the vector store table in MySQL AI Engine (AI engine):

    mysql> ALTER TABLE VectorStoreTableName SECONDARY_LOAD;

    Replace VectorStoreTableName with the name of the vector store table.

    For example:

    mysql> ALTER TABLE demo_db.demo_embeddings SECONDARY_LOAD;

    This accelerates processing of vector distance function used to compare vector embeddings and generate relevant output later in this section.

  2. To specify the table for retrieving the vector embeddings to use as context, set the @options variable:

    mysql> SET @options = JSON_OBJECT(
      "vector_store", JSON_ARRAY("DBName.VectorStoreTableName"), 
      "model_options", JSON_OBJECT("language", "Language")
    );

    Replace the following:

    • DBName: the name of the database that contains the vector store table.

    • VectorStoreTableName: the name of the vector store table.

    • Language: the two-letter ISO 639-1 code for the language you want to use. Default language is en, which is English. To view the list of supported languages, see Languages.

    For example:

    mysql> SET @options = JSON_OBJECT(
      "vector_store", JSON_ARRAY("demo_db.demo_embeddings"), 
      "model_options", JSON_OBJECT("language", "en")
    );

    To learn more about the available routine options, see ML_RAG Syntax.

  3. To define your natural-language query, set the @query variable:

    mysql> SET @query="AddYourQuery";

    Replace AddYourQuery with your natural-language query.

    For example:

    mysql> SET @query="What is AutoML?";
  4. To retrieve the augmented prompt, use the ML_RAG routine:

    mysql> CALL sys.ML_RAG(@query,@output,@options);
  5. Print the output:

    mysql> SELECT JSON_PRETTY(@output);

    Text-based content that is generated by the LLM in response to your query is printed as output. The output generated by RAG is comprised of two parts:

    • The text section contains the text-based content generated by the LLM as a response for your query.

    • The citations section shows the segments and documents it referred to as context.

    The output looks similar to the following:

    | {
      "text": "\nAutoML (Automated Machine Learning) is a machine learning technique that automates the process of selecting, training, and evaluating machine learning models. It involves using algorithms and techniques to automatically identify the best model for a given dataset and optimize its hyperparameters without requiring manual intervention from data analysts or ML practitioners.",
      "license": "Your use of this llama model is subject to your Oracle agreements and this llama license agreement: https://downloads.mysql.com/docs/LLAMA_32_3B_INSTRUCT-license.pdf",
      "citations": [
        {
          "segment": "\"segment\": \"| {   \\\"text\\\": \\\" AutoML is a subfield of machine learning that focuses on automating the process of building and training machine learning models. It involves using algorithms and techniques to automatically select features, tune hyperparameters, and evaluate model performance, without requiring human intervention. AutoML can be used for a variety of tasks, including classification, regression, clustering, and anomaly detection.\\\",   \\\"citations\\\": [     {\",",
          "distance": 0.0732,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
          "segment": "}, {   \"segment\": \"| {   \\\"text\\\": \\\" AutoML is a subfield of machine learning that focuses on automating the process of building and training machine learning models. It involves using algorithms and techniques to automatically select features, tune hyperparameters, and evaluate model performance, without requiring human intervention. AutoML can be used for a variety of tasks, including classification, regression, clustering, and anomaly detection.\\\",   \\\"citations\\\": [     {\",   \"distance\":",
          "distance": 0.0738,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
          "segment": "| {   \"text\": \" AutoML is a machine learning technique that automates the process of selecting, training, and evaluating machine learning models. It involves using algorithms and techniques to automatically identify the best model for a given dataset and optimize its hyperparameters without requiring manual intervention from data analysts or ML practitioners. AutoML can be used in various stages of the machine learning pipeline, including data preprocessing, feature engineering, model",
          "distance": 0.0743,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        }
      ],
      "vector_store": [
        "`demo_db`.`demo_embeddings`"
      ],
      "retrieval_info": {
        "method": "n_citations",
        "threshold": 0.0743
      }
    } |

    To continue running more queries in the same session, repeat steps 3 to 5.

Retrieving Context Without Generating Content

To enter a natural-language query and retrieve the context without generating a response for the query, perform the following steps:

  1. Optionally, to speed up vector processing, load the vector store table in the AI engine:

    mysql> ALTER TABLE VectorStoreTableName SECONDARY_LOAD;

    Replace VectorStoreTableName with the name of the vector store table.

    For example:

    mysql> ALTER TABLE demo_db.demo_embeddings SECONDARY_LOAD;

    This accelerates processing of vector distance function used to compare vector embeddings and generate relevant output later in this section.

  2. To specify the table for retrieving the vector embeddings and to skip generation of content, set the @options variable:

    mysql> SET @options = JSON_OBJECT("vector_store", JSON_ARRAY("DBName.VectorStoreTableName"), "skip_generate", true);

    Replace the following:

    • DBName: the name of the database that contains the vector store table.

    • VectorStoreTableName: the name of the vector store table.

    For example:

    mysql> SET @options = JSON_OBJECT("vector_store", JSON_ARRAY("demo_db.demo_embeddings"), "skip_generate", true);
  3. To define your natural-language query, set the @query variable:

    mysql> SET @query="AddYourQuery";

    Replace AddYourQuery with your natural-language query.

    For example:

    mysql> SET @query="What is AutoML?";
  4. To retrieve the augmented prompt, use the ML_RAG routine:

    mysql> CALL sys.ML_RAG(@query,@output,@options);
  5. Print the output:

    mysql> SELECT JSON_PRETTY(@output);

    Semantically similar text segments used as content for the query and the name of the documents they were found in are printed as output.

    The output looks similar to the following:

    | {
      "citations": [
        {
          "segment": "\"segment\": \"| {   \\\"text\\\": \\\" AutoML is a subfield of machine learning that focuses on automating the process of building and training machine learning models. It involves using algorithms and techniques to automatically select features, tune hyperparameters, and evaluate model performance, without requiring human intervention. AutoML can be used for a variety of tasks, including classification, regression, clustering, and anomaly detection.\\\",   \\\"citations\\\": [     {\",",
          "distance": 0.0732,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
          "segment": "}, {   \"segment\": \"| {   \\\"text\\\": \\\" AutoML is a subfield of machine learning that focuses on automating the process of building and training machine learning models. It involves using algorithms and techniques to automatically select features, tune hyperparameters, and evaluate model performance, without requiring human intervention. AutoML can be used for a variety of tasks, including classification, regression, clustering, and anomaly detection.\\\",   \\\"citations\\\": [     {\",   \"distance\":",
          "distance": 0.0738,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
          "segment": "| {   \"text\": \" AutoML is a machine learning technique that automates the process of selecting, training, and evaluating machine learning models. It involves using algorithms and techniques to automatically identify the best model for a given dataset and optimize its hyperparameters without requiring manual intervention from data analysts or ML practitioners. AutoML can be used in various stages of the machine learning pipeline, including data preprocessing, feature engineering, model",
          "distance": 0.0743,
          "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        }
      ],
      "vector_store": [
        "`demo_db`.`demo_embeddings`"
      ],
      "retrieval_info": {
        "method": "n_citations",
        "threshold": 0.0743
      }
    } |

    To continue running more queries in the same session, repeat steps 3 to 5.

Running Batch Queries

To run multiple RAG queries in parallel, use the ML_RAG_TABLE routine. This method is faster than running the ML_RAG routine multiple times.

To run the steps in this section, create a new table input_table in demo_db:

mysql> USE demo_db;
mysql> CREATE TABLE input_table (id INT AUTO_INCREMENT, Input TEXT, primary key (id));
mysql> INSERT INTO input_table (Input) VALUES('What is HeatWave Lakehouse?');
mysql> INSERT INTO input_table (Input) VALUES('What is HeatWave AutoML?');
mysql> INSERT INTO input_table (Input) VALUES('What is HeatWave GenAI?');

To run batch queries using ML_RAG_TABLE, perform the following steps:

  1. To specify the table for retrieving the vector embeddings to use as context, set the @options variable:

    mysql> SET @options = JSON_OBJECT(
      "vector_store", JSON_ARRAY("DBName.VectorStoreTableName"), 
      "model_options", JSON_OBJECT("language", "Language")
    );

    Replace the following:

    • DBName: the name of the database that contains the vector store table.

    • VectorStoreTableName: the name of the vector store table.

    • Language: the two-letter ISO 639-1 code for the language you want to use. Default language is en, which is English. To view the list of supported languages, see Languages.

    For example:

    mysql> SET @options = JSON_OBJECT(
      "vector_store", JSON_ARRAY("demo_db.demo_embeddings"), 
      "model_options", JSON_OBJECT("language", "en")
    );

    To learn more about the available routine options, see ML_RAG_TABLE Syntax.

  2. In the ML_RAG_TABLE routine, specify the table columns containing the input queries and for storing the generated outputs:

    mysql> CALL sys.ML_RAG_TABLE("InputDBName.InputTableName.InputColumn", "OutputDBName.OutputTableName.OutputColumn", @options);

    Replace the following:

    • InputDBName: the name of the database that contains the table column where your input queries are stored.

    • InputTableName: the name of the table that contains the column where your input queries are stored.

    • InputColumn: the name of the column that contains input queries.

    • OutputDBName: the name of the database that contains the table where you want to store the generated outputs. This can be the same as the input database.

    • OutputTableName: the name of the table where you want to create a new column to store the generated outputs. This can be the same as the input table. If the specified table doesn't exist, a new table is created.

    • OutputColumn: the name for the new column where you want to store the output generated for the input queries.

    For example:

    mysql> CALL sys.ML_RAG_TABLE("demo_db.input_table.Input", "demo_db.output_table.Output", @options);
  3. View the contents of the output table:

    mysql> SELECT * FROM output_table\G
    *************************** 1. row ***************************
        id: 1
    Output: {"text": "\nHeatWave Lakehouse is a feature of the HeatWave platform that enables query processing on data resident in Object Storage.", 
    "error": null, 
    "license": "Your use of this llama model is subject to your Oracle agreements and this llama license agreement: https://downloads.mysql.com/docs/LLAMA_32_3B_INSTRUCT-license.pdf", 
    "citations": [
        {
            "segment": "-----------------------+ |  1 | {\"text\": \" HeatWave Lakehouse is a feature of the HeatWave platform that enables query processing on data resident in Object Storage. The source data is read from Object Storage, transformed to the memory optimized HeatWave format, stored in the HeatWave persistence storage layer in Object Storage, and then loaded to HeatWave cluster memory for in-memory query processing. It allows you to create tables which point to external data sources and provides rapid and lakehouse as the primary",
            "distance": 0.0828,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "------------------------------------------+ |  1 | {\"text\": \" HeatWave Lakehouse is a feature of the HeatWave platform that enables query processing on data resident in Object Storage. The source data is read from Object Storage, transformed to the memory optimized HeatWave format, stored in the HeatWave persistence storage layer in Object Storage, and then loaded to HeatWave cluster memory for in-memory query processing. It allows you to create tables which point to external data sources and provides rapid and lakehouse as the primary",
            "distance": 0.0863,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "The Lakehouse feature of HeatWave enables query processing on data in Object Storage. HeatWave Lakehouse reads the source data from Object Storage, transforms it to the memory optimized HeatWave format, saves it in the HeatWave persistence storage layer in Object Storage, and then loads the data to HeatWave Cluster memory. While Lakehouse provides in-memory query processing on data in Object Storage, it does not load data into a DB System table.",
            "distance": 0.1028,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        }
    ], 
    "vector_store": ["`demo_db`.`demo_embeddings`"], 
    "retrieval_info": {"method": "n_citations", "threshold": 0.1028}}
    *************************** 2. row ***************************
        id: 2
    Output: {"text": "\nHeatWave AutoML is a feature of MySQL HeatWave that makes it easy to use machine learning, allowing users to create optimized machine learning models for predictions and explanations without having to leave the database.", 
    "error": null, 
    "citations": [
        {
            "segment": "|  HeatWave AutoML is a feature of MySQL HeatWave that makes it easy to use machine learning, whether you are a novice user or an experienced ML practitioner. It analyzes the characteristics of the data and creates an optimized machine learning model that can be used to generate predictions and explanations. The data and models never leave MySQL HeatWave, saving time and effort while keeping the data and models secure. HeatWave AutoML is optimized for HeatWave shapes and scaling, and all",
            "distance": 0.0561,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "HeatWave shapes and scaling, and all HeatWave AutoML makes it easy to use machine learning, whether you are a novice user or an experienced ML practitioner. You provide the data, and HeatWave AutoML analyzes the characteristics of the data and creates an optimized machine learning model that you can use to generate predictions and explanations. An ML model makes predictions by identifying patterns in your data and applying those patterns to unseen data. HeatWave AutoML explanations help you",
            "distance": 0.0573,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "HeatWave AutoML makes it easy to use machine learning, whether you are a novice user or an experienced ML practitioner. You provide the data, and HeatWave AutoML analyzes the characteristics of the data and creates an optimized machine learning model that you can use to generate predictions and explanations. An ML model makes predictions by identifying patterns in your data and applying those patterns to unseen data. HeatWave AutoML explanations help you understand how predictions are made,",
            "distance": 0.0598,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        }
    ], 
    "vector_store": ["`demo_db`.`demo_embeddings`"], 
    "retrieval_info": {"method": "n_citations", "threshold": 0.0598}}
    *************************** 3. row ***************************
        id: 3
    Output: {"text": "\nHeatWave GenAI is a feature of HeatWave that enables natural language communication with unstructured data using large language models (LLMs) and provides an inbuilt vector store for enterprise-specific proprietary content, along with a chatbot called HeatWave Chat.", 
    "error": null, 
    "citations": [
        {
            "segment": "4.1 HeatWave GenAI Overview HeatWave GenAI is a feature of HeatWave that lets you communicate with unstructured data in HeatWave using natural-language queries. It uses a familiar SQL interface which makes it is easy to use for content generation, summarization, and retrieval-augmented generation (RAG).",
            "distance": 0.0521,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "Chapter 3, HeatWave AutoML. 1.4 HeatWave GenAI The HeatWave GenAI feature of HeatWave lets you communicate with unstructured data in HeatWave using natural language queries. It uses large language models (LLMs) to enable natural language communication and provides an inbuilt vector store that you can use to store enterprise-specific proprietary content to perform vector searches. HeatWave GenAI also includes HeatWave Chat which is a chatbot that extends the generative AI and vector search functionalities to let you ask multiple follow-up",
            "distance": 0.0735,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        },
        {
            "segment": "HeatWave Chat also provides a graphical interface integrated with the Visual Studio Code plugin for MySQL Shell.\nBenefits\nHeatWave GenAI lets you integrate generative AI into the applications, providing an integrated end-to-end pipeline including vector store generation, vector search with RAG, and an inbuilt chatbot.\nSome key benefits of using HeatWave GenAI are described below:",
            "distance": 0.0781,
            "document_name": "/var/lib/mysql-files/demo-directory/heatwave-en.pdf"
        }
    ], 
    "vector_store": ["`demo_db`.`demo_embeddings`"], 
    "retrieval_info": {"method": "n_citations", "threshold": 0.0781}}

    The output table generated using the ML_RAG_TABLE routine contains an additional details for error reporting. In case the routine fails to generate output for specific rows, details of the errors encountered and default values used are added for the rows in the output column.

Cleaning Up

If you created a new database for testing the steps in this topic, delete the database to free up space:

mysql> DROP DATABASE demo_db;