Select AI 사용 예

Oracle의 Select AI와 다양한 지원 AI 제공업체의 통합을 살펴보고, 자연어 프롬프트에서 SQL을 생성, 실행, 설명하거나, LLM과 채팅해 보세요.

예: AI 작업 선택

다음 예에서는 일반적인 Select AI 작업을 보여줍니다.

다음 예에서는 SELECT AI로 수행할 수 있는 runsql(기본값), showsql, narrate, chat, explainsql, feedbacksummarize과 같은 작업을 보여줍니다. 이러한 예에서는 sh 스키마를 DBMS_CLOUD_AI.CREATE_PROFILE 함수에 지정된 AI 제공자 및 프로파일 속성과 함께 사용합니다. 현재 세션의 DBMS_CLOUD_AI.SET_PROFILE 절차를 사용하여 AI 프로파일을 설정한 후 AI 선택 작업을 사용합니다.

텍스트 요약을 생성하려면 SELECT AI SUMMARIZE <TEXT>를 사용합니다.

SQL> select ai how many customers exist;
 
CUSTOMER_COUNT
--------------
         55500
 
SQL> select ai showsql how many customers exist;
 
RESPONSE
----------------------------------------------------
SELECT COUNT(*) AS total_customers
FROM SH.CUSTOMERS
 
 
SQL> select ai narrate how many customers exist;
 
RESPONSE
------------------------------------------------------
There are a total of 55,500 customers in the database.
 
SQL> select ai chat how many customers exist;
 
RESPONSE
--------------------------------------------------------------------------------
It is impossible to determine the exact number of customers that exist as it con
stantly changes due to various factors such as population growth, new businesses
, and customer turnover. Additionally, the term "customer" can refer to individu
als, businesses, or organizations, making it difficult to provide a specific num
ber.


SQL> select ai explainsql how many customers in San Francisco are married;
 
RESPONSE
--------------------------------------------------------------------------------
SELECT COUNT(*) AS customer_count
FROM SH.CUSTOMERS AS c
WHERE c.CUST_STATE_PROVINCE = 'San Francisco' AND c.CUST_MARITAL_STATUS = 'Married';
 
Explanation:
- We use the 'SH' table alias for the 'CUSTOMERS' table for better readability.
- The query uses the 'COUNT(*)' function to count the number of rows that match the given conditions.
- The 'WHERE' clause is used to filter the results:
  - 'c.CUST_STATE_PROVINCE = 'San Francisco'' filters customers who have 'San Francisco' as their state or province.
  - 'c.CUST_MARITAL_STATUS = 'Married'' filters customers who have 'Married' as their marital status.
The result of this query will give you the count of customers in San Francisco who are married, using the column alias 'customer_count' for the result.
 
Remember to adjust the table and column names based on your actual schema if they differ from the example.
 
Feel free to ask if you have more questions related to SQL or database in general.

-- Feedback on SQL Text
-- Negative feedback example:
SQL > select ai feedback for query "select ai showsql how many watch histories in total", please use sum instead of count;
-- Positive feedback example:
SQL > select ai feedback for query "select ai showsql how many watch histories in total", the sql query generated is correct;
 
-- Feedback on SQL ID
-- Negative feedback example:
SQL > select ai feedback please use sum instead of count for sql_id  1v1z68ra6r9zf;
-- Positive feedback example:
SQL > select ai feedback sql query result is correct for sql_id  1v1z68ra6r9zf;
 
-- If not specified, use default LASTAI SQL
-- To use default LASTAI sql, make sure that set server output off;
-- Negative feedback example:
SQL > select ai feedback please use ascending sorting for ranking;
-- Positive feedback example:
SQL > select ai feedback the result is correct;

SQL> SELECT AI SUMMARIZE
Like countless other people around the globe, I stream music, and like more
than six hundred million of them I mainly use Spotify. Streaming currently
accounts for about eighty per cent of the American recording industry’s
revenue, and in recent years Spotify’s health is often consulted as a measure
for the health of the music business over all. Last spring, the International
Federation of the Phonographic Industry reported global revenues of $28.6
billion, making for the ninth straight year of growth. All of this was
unimaginable in the two-thousands, when the major record labels appeared
poorly equipped to deal with piracy and the so-called death of physical media.
On the consumer side, the story looks even rosier. Adjusted for inflation, a
 
... (skipped 1000 rows in the middle)
 
Pelly writes of some artists, in search of viral fame, who surreptitiously use
social media to effectively beta test melodies and motifs, basically putting
together songs via crowdsourcing. Artists have always fretted about the
pressure to conform, but the data-driven, music-as-content era feels
different. “You are a Spotify employee at that point,” Daniel Lopatin, who
makes abstract electronic music as Oneohtrix Point Never, told Pelly. “If your
art practice is so ingrained in the brutal reality that Spotify has outlined
for all of us, then what is the music that you’re not making? What does the
music you’re not making sound like?” Listeners might wonder something similar.
What does the music we’re not hearing sound like?;
 
 
RESPONSE
------------------------------------------------------------------------------
The music streaming industry, led by Spotify, has revolutionized the way
people consume music, with streaming accounting for 80% of the American
recording industry's revenue. However, this shift has also complicated the
lives of artists, who struggle to survive in a hyper-abundant present where
music is often valued for its convenience rather than its artistic merit.
Spotify's algorithms prioritize popularity and profitability over artistic
diversity, leading to a homogenization of music and a devaluation of the
labor that goes into creating it. Meanwhile, the company's executives reap
enormous profits, with CEO Daniel Ek's net worth rivaling that of the
wealthiest musicians. As music critic Liz Pelly argues, the streaming economy
raises important questions about autonomy, creativity, and the value of art
in a world where everything is readily available and easily accessible.

예: RAG와 함께 Select AI 설정 및 사용

이 예에서는 인증서 설정, 네트워크 액세스 구성, Oracle Autonomous AI Database를 사용하여 OCI Generative AI 벡터 스토어 클라우드 서비스를 OpenAI과 통합하기 위한 벡터 인덱스 생성 과정을 안내합니다.

이 설정은 벡터 인덱스를 사용하여 LLM 응답을 개선하는 AI 프로파일을 생성하는 것으로 마무리됩니다. 마지막으로 이 예에서는 지정된 벡터 데이터베이스의 정보를 사용하여 향상된 응답을 반환하는 AI narrate 선택 작업을 사용합니다.

다음 예제는 Oracle Database 23ai에서 벡터 인덱스 구축 및 쿼리를 보여줍니다.

--Grants EXECUTE privilege to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_AI to ADB_USER; 

--Grants EXECUTE privilege DBMS_CLOUD_PIPELINE to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_PIPELINE to ADB_USER;

-- Create the OpenAI credential
BEGIN
      DBMS_CLOUD.CREATE_CREDENTIAL(
        credential_name => 'OPENAI_CRED',
        username => 'OPENAI_CRED',
        password => '<your_api_key>'
      );
END;
/

PL/SQL procedure successfully completed.

 -- Append the OpenAI endpoint
BEGIN
        DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
             host => 'api.openai.com',
             ace  => xs$ace_type(privilege_list => xs$name_list('http'),
                     principal_name => 'ADB_USER',
                     principal_type => xs_acl.ptype_db)
       );
END;
/

PL/SQL procedure successfully completed.

 
-- Create the object store credential
BEGIN
      DBMS_CLOUD.CREATE_CREDENTIAL(
        credential_name => 'OCI_CRED',
        username => '<your_username>',
        password => '<OCI_profile_password>'
      );
END;
/

PL/SQL procedure successfully completed.

 -- Create the profile with the vector index.

BEGIN
      DBMS_CLOUD_AI.CREATE_PROFILE(
          profile_name =>'OPENAI_ORACLE',
          attributes   =>'{"provider": "openai",
            "credential_name": "OPENAI_CRED",
            "vector_index_name": "MY_INDEX",
            "temperature": 0.2,
            "max_tokens": 4096,
            "model": "gpt-3.5-turbo-1106"
          }');
END;
/

PL/SQL procedure successfully completed.

-- Set profile
EXEC DBMS_CLOUD_AI.SET_PROFILE('OPENAI_ORACLE');

PL/SQL procedure successfully completed.                                            
 
-- create a vector index with the vector store name, object store location and
-- object store credential
BEGIN
       DBMS_CLOUD_AI.CREATE_VECTOR_INDEX(
         index_name  => 'MY_INDEX',
         attributes  => '{"vector_db_provider": "oracle",
                          "location": "https://swiftobjectstorage.us-phoenix-1.oraclecloud.com/v1/my_namespace/my_bucket/my_data_folder",
                          "object_storage_credential_name": "OCI_CRED",
                          "profile_name": "OPENAI_ORACLE",
                          "vector_dimension": 1536,
                          "vector_distance_metric": "cosine",
                          "chunk_overlap":128,
                          "chunk_size":1024
      }');
END;
/
PL/SQL procedure successfully completed.  
                                                                                
-- After the vector index is populated, we can now query the index.




-- Set profile
EXEC DBMS_CLOUD_AI.SET_PROFILE('OPENAI_ORACLE');

PL/SQL procedure successfully completed.

-- Select AI answers the question with the knowledge available in the vector database.

set pages 1000
set linesize 150
SELECT AI narrate how can I deploy an oracle machine learning model;
RESPONSE                                                  
To deploy an Oracle Machine Learning model, you would first build your model within the Oracle database. Once your in-database models are built, they become immediately available for use, for instance, through a SQL query using the prediction operators built into the SQL language. 

The model scoring, like model building, occurs directly in the database, eliminating the need for a separate engine or environment within which the model and corresponding algorithm code operate. You can also use models from a different schema (user account) if the appropriate permissions are in place.

Sources:
  - Manage-your-models-with-Oracle-Machine-Learning-on-Autonomous-Database.txt (https://objectstorage.../v1/my_namespace/my_bucket/my_data_folder/Manage-your-models-with-Oracle-Machine-Learning-on-Autonomous-Database.txt)
  - Develop-and-deploy-machine-learning-models-using-Oracle-Autonomous-Database-Machine-Learning-and-APEX.txt (https://objectstorage.../v1/my_namespace/my_bucket/my_data_folder/Develop-and-deploy-machine-learning-models-using-Oracle-Autonomous-Database-Machine-Learning-and-APEX.txt)

예: 데이터베이스 내 변환기 모델이 있는 AI 선택

이 예제는 Oracle 객체 스토리지에 저장된 사전 학습된 변환기 모델을 Oracle Database 23ai 인스턴스로 임포트한 다음 Select AI 프로파일에서 임포트된 데이터베이스 내 모델을 사용하여 문서 조각 및 사용자 프롬프트에 대한 벡터 임베딩을 생성하는 방법을 보여줍니다.

Select AI 프로파일에서 데이터베이스 내 변환기 모델을 사용하려면 다음이 있어야 합니다.
  • Oracle Database 23ai 인스턴스에서 가져온 사전 학습 모델

  • 선택적으로 Oracle Object Storage에 액세스합니다.

사전 학습된 변환기 모델을 Oracle Object Storage에서 Oracle Database 23ai로 가져오기

데이터베이스 내에서 벡터 생성을 위한 ONNX 형식의 사전 학습 모델 임포트Oracle AI Database 26ai를 위한 사전 구축된 임베딩 생성 모델 블로그의 단계를 검토하여 사전 학습된 변환기 모델을 데이터베이스로 임포트합니다.

다음 예에서는 Oracle 객체 스토리지에서 데이터베이스로 미리 유지된 변환기 모델을 임포트한 다음 임포트된 모델을 보는 방법을 보여줍니다.

- Create a Directory object, or use an existing directory object
CREATE OR REPLACE DIRECTORY ONNX_DIR AS 'onnx_model';
 
-- Object storage bucket
VAR location_uri VARCHAR2(4000);
EXEC :location_uri := 'https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/eLddQappgBJ7jNi6Guz9m9LOtYe2u8LWY19GfgU8flFK4N9YgP4kTlrE9Px3pE12/n/adwc4pm/b/OML-Resources/o/';
 
-- Model file name
VAR file_name VARCHAR2(512);
EXEC :file_name := 'all_MiniLM_L12_v2.onnx';
 
-- Download ONNX model from object storage into the directory object
BEGIN
  DBMS_CLOUD.GET_OBJECT(                           
        credential_name => NULL,
        directory_name  => 'ONNX_DIR',
        object_uri      => :location_uri || :file_name);
END;
/
 
-- Load the ONNX model into the database
BEGIN
  DBMS_VECTOR.LOAD_ONNX_MODEL(
        directory  => 'ONNX_DIR',
        file_name  => :file_name,
        model_name => 'MY_ONNX_MODEL');
END;
/
 
-- Verify
SELECT model_name, algorithm, mining_function
FROM user_mining_models
WHERE  model_name='MY_ONNX_MODEL';
일부 AI 프로파일에서 데이터베이스 내 변환기 모델 사용

다음 예에서는 Select AI 프로파일 내에서 데이터베이스 내 변환기 모델을 사용하는 방법을 보여줍니다. 하나의 프로파일은 벡터 임베딩을 생성하기 위해서만 구성되며, 다른 프로파일은 Select AI 작업과 벡터 인덱스 생성을 모두 지원합니다.

DBMS_CLOUD_AI 패키지 구성을 위한 요구 사항을 검토하여 필요 조건을 완료합니다.

다음은 벡터 임베딩만 생성하는 예입니다.

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
     profile_name => 'EMBEDDING_PROFILE',
     attributes   => '{"provider" : "database",
                       "embedding_model": "MY_ONNX_MODEL"}'
  );
END;
/

다음은 지원되는 AI 제공자를 지정할 수 있는 일반 AI 선택 작업 및 벡터 인덱스 생성의 예입니다. 이 예에서는 OCI Gen AI 프로파일 및 인증서를 사용합니다. 지원되는 공급자 목록은 를 참조하십시오. 그러나 벡터 임베딩 생성을 위해 데이터베이스 내 변환기 모델을 사용하려면 embedding_model 속성에서 "database: <MY_ONNX_MODEL>"를 사용합니다.

BEGIN                                                                        
  DBMS_CLOUD.CREATE_CREDENTIAL(                                              
    credential_name => 'GENAI_CRED',                                         
    user_ocid       => 'ocid1.user.oc1..aaaa...',
    tenancy_ocid    => 'ocid1.tenancy.oc1..aaaa...',
    private_key     => '<your_api_key>',
    fingerprint     => '<your_fingerprint>'     
  );                                                                         
END;                                                                        
/

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
     profile_name => 'OCI_GENAI',
     attributes   => '{"provider": "oci",
                       "model": "meta.llama-3.3-70b-instruct",
                       "credential_name": "GENAI_CRED",
                       "vector_index_name": "MY_INDEX",
                       "embedding_model": "database: MY_ONNX_MODEL"}'
  );
END;
/
다른 스키마에서 데이터베이스 내 변환기 모델과 함께 AI 선택 사용

이 예에서는 다른 스키마 소유자가 모델을 소유한 경우 데이터베이스 내 변환기 모델에서 Select AI를 사용하는 방법을 보여줍니다. embedding_model 속성에서 모델의 전체 이름으로 schema_name.object_name를 지정합니다. 현재 사용자가 스키마 소유자이거나 모델을 소유하는 경우 스키마 이름을 생략할 수 있습니다.

다른 스키마 소유자가 모델을 소유하는 경우 다음 권한이 있어야 합니다.
  • CREATE ANY MINING MODEL 시스템 권한
  • SELECT ANY MINING MODEL 시스템 권한
  • 특정 모델에 대한 SELECT MINING MODEL 객체 권한

시스템 권한을 부여하려면 ADMIN OPTION에 시스템 권한이 부여되었거나 GRANT ANY PRIVILEGE 시스템 권한이 부여되어 있어야 합니다.

권한을 검토하려면 Oracle Machine Learning for SQL에 대한 시스템 권한을 참조하십시오.

다음 명령문을 통해 SELECT 액세스 권한이 데이터에 부여된 경우 ADB_USER1는 모든 스키마에서 데이터에 점수를 부여하고 모델 세부정보를 볼 수 있습니다. 그러나 ADB_USER1ADB_USER1 스키마에서만 모델을 생성할 수 있습니다.

GRANT CREATE MINING MODEL TO ADB_USER1;
GRANT SELECT ANY MINING MODEL TO ADB_USER1;
BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
     profile_name => 'OCI_GENAI',
     attributes   => '{"provider": "oci",
                       "credential_name": "GENAI_CRED",
                       "vector_index_name": "MY_INDEX",
                       "embedding_model": "database: ADB_USER1.MY_ONNX_MODEL"}'
  );
END;
/

다음 예에서는 대소문자 구분 모델 객체 이름을 지정하는 방법을 보여줍니다.

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
     profile_name => 'OCI_GENAI',
     attributes   => '{"provider": "oci",
                       "credential_name": "GENAI_CRED",
                       "model": "meta.llama-3.3-70b-instruct",
                       "vector_index_name": "MY_INDEX",
                       "embedding_model": "database: \"adb_user1\".\"my_model\""}'
  );
END;
/
다양한 AI 제공업체를 활용한 포괄적 사례

이 예에서는 Select AI RAG와 함께 인데이터베이스 변환기 모델을 사용하기 위한 엔드투엔드 단계를 보여줍니다. 한 프로파일은 임베딩 벡터를 생성하기 위해 독점적으로 생성된 providerdatabase를 사용하고 다른 프로파일은 벡터 인덱스뿐 아니라 AI 선택 작업에 대해 생성된 provideroci를 사용합니다.

DBMS_CLOUD_AI 패키지 구성을 위한 요구 사항을 검토하여 필요 조건을 완료합니다.

--Grant create any directory privilege to the user
GRANT CREATE ANY DIRECTORY to ADB_USER;

- Create a Directory object, or use an existing directory object
CREATE OR REPLACE DIRECTORY ONNX_DIR AS 'onnx_model';
 
-- Object storage bucket
VAR location_uri VARCHAR2(4000);
EXEC :location_uri := 'https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/eLddQappgBJ7jNi6Guz9m9LOtYe2u8LWY19GfgU8flFK4N9YgP4kTlrE9Px3pE12/n/adwc4pm/b/OML-Resources/o/';
 
-- Model file name
VAR file_name VARCHAR2(512);
EXEC :file_name := 'all_MiniLM_L12_v2.onnx';
 
-- Download ONNX model from object storage into the directory object
BEGIN
  DBMS_CLOUD.GET_OBJECT(                           
        credential_name => NULL,
        directory_name  => 'ONNX_DIR',
        object_uri      => :location_uri || :file_name);
END;
/
 
-- Load the ONNX model into the database
BEGIN
  DBMS_VECTOR.LOAD_ONNX_MODEL(
        directory  => 'ONNX_DIR',
        file_name  => :file_name,
        model_name => 'MY_ONNX_MODEL');
END;
/
 
-- Verify
SELECT model_name, algorithm, mining_function
FROM user_mining_models
WHERE  model_name='MY_ONNX_MODEL';


--Administrator grants EXECUTE privilege to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_AI to ADB_USER; 

--Administrator grants EXECUTE privilege DBMS_CLOUD_PIPELINE to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_PIPELINE to ADB_USER;
 
-- Create the object store credential
BEGIN
      DBMS_CLOUD.CREATE_CREDENTIAL(
        credential_name => 'OCI_CRED',
        username => '<your_username>',
        password => '<OCI_profile_password>'
      );
END;
/

PL/SQL procedure successfully completed.

 -- Create the profile with Oracle Database.

BEGIN
      DBMS_CLOUD_AI.CREATE_PROFILE(
          profile_name =>'EMBEDDING_PROFILE',
          attributes   =>'{"provider": "database",
            "embedding_model": "MY_ONNX_MODEL"
          }');
END;
/

PL/SQL procedure successfully completed.

-- Set profile
EXEC DBMS_CLOUD_AI.SET_PROFILE('EMBEDDING_PROFILE');

PL/SQL procedure successfully completed.                                            
 

이 예에서는 ociprovider로 사용합니다.

--Grant create any directory privilege to the user
GRANT CREATE ANY DIRECTORY to ADB_USER;

- Create a Directory object, or use an existing directory object
CREATE OR REPLACE DIRECTORY ONNX_DIR AS 'onnx_model';
 
-- Object storage bucket
VAR location_uri VARCHAR2(4000);
EXEC :location_uri := 'https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/eLddQappgBJ7jNi6Guz9m9LOtYe2u8LWY19GfgU8flFK4N9YgP4kTlrE9Px3pE12/n/adwc4pm/b/OML-Resources/o/';
 
-- Model file name
VAR file_name VARCHAR2(512);
EXEC :file_name := 'all_MiniLM_L12_v2.onnx';
 
-- Download ONNX model from object storage into the directory object
BEGIN
  DBMS_CLOUD.GET_OBJECT(                           
        credential_name => NULL,
        directory_name  => 'ONNX_DIR',
        object_uri      => :location_uri || :file_name);
END;
/
 
-- Load the ONNX model into the database
BEGIN
  DBMS_VECTOR.LOAD_ONNX_MODEL(
        directory  => 'ONNX_DIR',
        file_name  => :file_name,
        model_name => 'MY_ONNX_MODEL');
END;
/
 
-- Verify
SELECT model_name, algorithm, mining_function
FROM user_mining_models
WHERE  model_name='MY_ONNX_MODEL';


–-Administrator Grants EXECUTE privilege to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_AI to ADB_USER; 

--Administrator Grants EXECUTE privilege DBMS_CLOUD_PIPELINE to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_PIPELINE to ADB_USER;

-- Create the object store credential
BEGIN
      DBMS_CLOUD.CREATE_CREDENTIAL(
        credential_name => 'OCI_CRED',
        username => '<your_username>',
        password => '<OCI_profile_password>'
      );
END;
/
--Create GenAI credentials
BEGIN                                                                        
  DBMS_CLOUD.CREATE_CREDENTIAL(                                              
    credential_name => 'GENAI_CRED',                                         
    user_ocid       => 'ocid1.user.oc1..aaaa...',
    tenancy_ocid    => 'ocid1.tenancy.oc1..aaaa...',
    private_key     => '<your_api_key>',
    fingerprint     => '<your_fingerprint>'     
  );                                                                         
END;                                                                        
/
--Create OCI AI profile
BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
     profile_name => 'OCI_GENAI',
     attributes   => '{"provider": "oci",
                       "model": "meta.llama-3.3-70b-instruct",
                       "credential_name": "GENAI_CRED",
                       "vector_index_name": "MY_INDEX",
                       "embedding_model": "database: MY_ONNX_MODEL"}'
  );
END;
/

-- Set profile
EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_GENAI');

PL/SQL procedure successfully completed.                                            
 
-- create a vector index with the vector store name, object store location and
-- object store credential
BEGIN
       DBMS_CLOUD_AI.CREATE_VECTOR_INDEX(
         index_name  => 'MY_INDEX',
         attributes  => '{"vector_db_provider": "oracle",
                          "location": "https://swiftobjectstorage.us-phoenix-1.oraclecloud.com/v1/my_namespace/my_bucket/my_data_folder",
                          "object_storage_credential_name": "OCI_CRED",
                          "profile_name": "OCI_GENAI",
                          "vector_dimension": 384,
                          "vector_distance_metric": "cosine",
                          "chunk_overlap":128,
                          "chunk_size":1024
      }');
END;
/
PL/SQL procedure successfully completed.  
                                                                               

-- Set profile
EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_GENAI');

PL/SQL procedure successfully completed.

-- Select AI answers the question with the knowledge available in the vector database.

set pages 1000
set linesize 150
SELECT AI narrate how can I deploy an oracle machine learning model;
RESPONSE                                                  
To deploy an Oracle Machine Learning model, you would first build your model within the Oracle database. Once your in-database models are 
built, they become immediately available for use, for instance, through a SQL query using the prediction operators built into the SQL 
language. 

The model scoring, like model building, occurs directly in the database, eliminating the need for a separate engine or environment within 
which the model and corresponding algorithm code operate. You can also use models from a different schema (user account) if the appropriate 
permissions are in place.

Sources:
  - Manage-your-models-with-Oracle-Machine-Learning-on-Autonomous-Database.txt (https://objectstorage.../v1/my_namespace/my_bucket/
my_data_folder/Manage-your-models-with-Oracle-Machine-Learning-on-Autonomous-Database.txt)
  - Develop-and-deploy-machine-learning-models-using-Oracle-Autonomous-Database-Machine-Learning-and-APEX.txt 
(https://objectstorage.../v1/my_namespace/my_bucket/my_data_folder/Develop-and-deploy-machine-learning-models-using-Oracle-Autonomous-
Database-Machine-Learning-and-APEX.txt)

예: 합성 데이터 생성

이 예에서는 실제 데이터의 특성 및 분포를 모방하는 합성 데이터를 생성하는 방법을 살펴봅니다.

주:

합성 데이터 생성 지원은 Oracle Database 19c(버전 19.29부터) 및 Oracle Database 26ai(버전 23.26부터)에서 제공됩니다.

다음 예에서는 스키마에 몇 개의 테이블을 생성하고, AI 제공자로 OCI Generative AI를 사용하여 AI 프로파일을 생성하고, DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA 함수를 사용하여 해당 테이블로 데이터를 합성하고, Select AI를 사용하여 자연어 프롬프트에 대한 응답을 쿼리하거나 생성하는 방법을 보여줍니다.

--Create tables or use cloned tables

CREATE TABLE ADB_USER.Director (
    director_id     INT PRIMARY KEY,
    name            VARCHAR(100)
);
CREATE TABLE ADB_USER.Movie (
    movie_id        INT PRIMARY KEY,
    title           VARCHAR(100),
    release_date    DATE,
    genre           VARCHAR(50),
    director_id     INT,
    FOREIGN KEY (director_id) REFERENCES ADB_USER.Director(director_id)
);
CREATE TABLE ADB_USER.Actor (
    actor_id        INT PRIMARY KEY,
    name            VARCHAR(100)
);
CREATE TABLE ADB_USER.Movie_Actor (
    movie_id        INT,
    actor_id        INT,
    PRIMARY KEY (movie_id, actor_id),
    FOREIGN KEY (movie_id) REFERENCES ADB_USER.Movie(movie_id),
    FOREIGN KEY (actor_id) REFERENCES ADB_USER.Actor(actor_id)
);

-- Create the GenAI credential
BEGIN                                                                       
  DBMS_CLOUD.create_credential(                                             
    credential_name => 'GENAI_CRED',                                        
    user_ocid       => 'ocid1.user.oc1....',
    tenancy_ocid    => 'ocid1.tenancy.oc1....',
    private_key     => 'vZ6cO...',
    fingerprint     => '86:7d:...'    
  );                                                                        
END;                                                                       
/
 
-- Create a profile
BEGIN                                                                      
  DBMS_CLOUD_AI.CREATE_PROFILE(                                            
      profile_name =>'GENAI',                                                           
      attributes  =>'{"provider": "oci",                                                                 
        "credential_name": "GENAI_CRED",                                   
        "object_list": [{"owner": "ADB_USER", 
		"oci_compartment_id": "ocid1.compartment.oc1...."}]          
       }');                                                                
END;                                                                       
/
 
 
EXEC DBMS_CLOUD_AI.set_profile('GENAI');

-- Run the API for single table
BEGIN
    DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
        profile_name => 'GENAI',
        object_name  => 'Director',
        owner_name   => 'ADB_USER',
        record_count => 5
    );
END;
/
PL/SQL procedure successfully completed.
 
 
-- Query the table to see results
SQL> SELECT * FROM ADB_USER.Director;
 
DIRECTOR_ID NAME
----------- ----------------------------------------------------------------------------------------------------
          1 John Smith
          2 Emily Chen
          3 Michael Brown
          4 Sarah Taylor
          5 David Lee
 
 
-- Or ask select ai to show the results
SQL> select ai how many directors are there;
 
NUMBER_OF_DIRECTORS
-------------------
                  5
예: 다중 테이블에 대한 합성 데이터 생성

AI 제공자 프로파일을 생성 및 설정한 후 DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA을 사용하여 여러 테이블에 대한 데이터를 생성합니다. Select AI를 쿼리하거나 사용하여 자연어 프롬프트에 응답할 수 있습니다.

BEGIN
    DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
        profile_name => 'GENAI',
        object_list => '[{"owner": "ADB_USER", "name": "Director","record_count":5},
                         {"owner": "ADB_USER", "name": "Movie_Actor","record_count":5},
                         {"owner": "ADB_USER", "name": "Actor","record_count":10},
                         {"owner": "ADB_USER", "name": "Movie","record_count":5,"user_prompt":"all movies released in 2009"}]'
    );
END;
/
PL/SQL procedure successfully completed.
 
 
-- Query the table to see results
SQL> select * from ADB_USER.Movie;

 MOVIE_ID TITLE                                                     RELEASE_D                            GENRE                                 DIRECTOR_ID	
---------- -------------------------------------------------------- --------- --------------------------------------------------------------- -----------	
         1 The Dark Knight                                           15-JUL-09                              Action                              8	
         2 Inglourious Basterds                                      21-AUG-09                              War                                 3	
         3 Up in the Air                                             04-SEP-09                              Drama                               6	
         4 The Hangover                                              05-JUN-09                              Comedy                              1	
         5 District 9                                                14-AUG-09                              Science Fiction                     10	
	

 
-- Or ask select ai to show the results
SQL> select ai how many actors are there;
 
Number of Actors
----------------
              10
예: 샘플 행으로 합성 데이터 생성 안내

AI 서비스에서 합성 데이터 생성을 안내하려면 테이블에서 기존 레코드를 임의로 선택할 수 있습니다. 예를 들어, {"sample_rows": 5}params 인수에 추가하면 테이블에서 AI 제공자로 5개의 샘플 행을 전송할 수 있습니다. 이 예에서는 Transactions 테이블의 샘플 행을 기반으로 10개의 추가 행을 생성합니다.

BEGIN
  DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
    profile_name => 'GENAI',
    object_name  => 'Transactions',
    owner_name   => 'ADB_USER',
    record_count => 10,
    params       => '{"sample_rows":5}'
  );
END;
/
예: 사용자 프롬프트로 합성 데이터 생성 사용자정의

user_prompt 인수를 사용하면 데이터 생성을 위한 추가 규칙 또는 요구 사항을 지정할 수 있습니다. 단일 테이블 또는 여러 테이블에 대한 object_list 인수의 일부로 적용할 수 있습니다. 예를 들어, DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA에 대한 다음 호출에서 프롬프트는 AI가 2009년에 릴리스된 영화에 합성 데이터를 생성하도록 지시합니다.

-- Definition for the Movie table CREATE TABLE Movie 

CREATE TABLE Movie (
    movie_id        INT PRIMARY KEY,
    title           VARCHAR(100),
    release_date    DATE,
    genre           VARCHAR(50),
    director_id     INT,
    FOREIGN KEY (director_id) REFERENCES Director(director_id)
);
 
 
 
BEGIN
  DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
    profile_name      => 'GENAI',
    object_name       => 'Movie',
    owner_name        => 'ADB_USER',
    record_count      => 10,
    user_prompt       => 'all movies are released in 2009',
    params            => '{"sample_rows":5}'
  );
END;
/
 
BEGIN
    DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
        profile_name => 'GENAI',
        object_list => '[{"owner": "ADB_USER", "name": "Director","record_count":5},
                         {"owner": "ADB_USER", "name": "Movie_Actor","record_count":5},
                         {"owner": "ADB_USER", "name": "Actor","record_count":10},
                         {"owner": "ADB_USER", "name": "Movie","record_count":5,"user_prompt":"all movies are released in 2009"}]'
    );
END;
/
예: 테이블 통계를 사용하여 합성 데이터 품질 향상

테이블에 열 통계가 있거나 메타데이터가 포함된 데이터베이스에서 복제된 경우 Select AI는 이러한 통계를 사용하여 원본 데이터와 거의 비슷하거나 일관된 데이터를 생성할 수 있습니다.

NUMBER 열의 경우 통계의 상한 및 하한 값이 값 범위를 안내합니다. 예를 들어, 원래 EMPLOYEES 테이블의 SALARY 열의 범위가 1000에서 10000 사이인 경우 이 열의 합성 데이터도 이 범위 내에 속합니다.

고유 값이 있는 열(예: 값이 CA, WATXSTATE 열)의 경우 합성 데이터가 해당 특정 값을 사용합니다. {"table_statistics": true/false} 매개변수를 사용하여 이 기능을 관리할 수 있습니다. 기본적으로 테이블 통계는 활성화되어 있습니다.

BEGIN
  DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
    profile_name      => 'GENAI',
    object_name       => 'Movie',
    owner_name        => 'ADB_USER',
    record_count      => 10,
    user_prompt => 'all movies released in 2009',
    params            => '{"sample_rows":5,"table_statistics":true}'
  );
END;
/
예제: 열 주석을 사용하여 데이터 생성 안내

열 설명이 있는 경우 Select AI는 데이터 생성 중 LLM에 대한 추가 정보를 제공하기 위해 해당 설명을 자동으로 포함합니다. 예를 들어, [트랜잭션] 테이블의 Status 열에 대한 설명에는 허용되는 값(예: successful, failed, pending, canceledneed manual check)이 나열될 수 있습니다. 또한 주석을 추가하여 열을 자세히 설명함으로써 AI 서비스에 정확한 데이터 생성을 위한 보다 정확한 지침 또는 힌트를 제공할 수 있습니다. 기본적으로 주석은 사용 안함으로 설정됩니다. 자세한 내용은 선택적 매개변수를 참조하십시오.

-- Use comment on column
COMMENT ON COLUMN Transaction.status IS 'the value for state should either be ''successful'', ''failed'', ''pending'' or ''canceled''';
/
 
BEGIN
    DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
        profile_name  => 'GENAI',
        object_name   => 'employees',
        owner_name    => 'ADB_USER',
        record_count  => 10
        params        => '{"comments":true}'
 
    );
END;
/
예: 합성 데이터 생성에서 고유 값 설정

LLM을 사용하여 대량의 합성 데이터를 생성할 때 중복 값이 발생할 수 있습니다. 이를 방지하려면 관련 열에 고유 제약 조건을 설정합니다. 이렇게 하면 Select AI가 LLM 응답에서 중복 값이 있는 행을 무시합니다. 또한 특정 열에 대한 값을 제한하려면 user_prompt를 사용하거나 설명을 추가하여 허용되는 값(예: STATE 열을 CA, WATX로 제한)을 지정할 수 있습니다.

-- Use 'user_prompt'
BEGIN
    DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
        profile_name  => 'GENAI',
        object_name   => 'employees',
        owner_name    => 'ADB_USER',
        user_prompt   => 'the value for state should either be CA, WA, or TX',
        record_count  => 10
    );
END;
/
 
 
-- Use comment on column
COMMENT ON COLUMN EMPLOYEES.state IS 'the value for state should either be CA, WA, or TX'
/
예: 병렬 처리로 합성 데이터 생성 향상

런타임을 줄이기 위해 Select AI는 기본 키가 없거나 숫자 기본 키가 있는 테이블에 대해 합성 데이터 생성 작업을 더 작은 조각으로 분할합니다. 이러한 작업은 병렬로 실행되며 AI 제공자와 상호 작용하여 데이터를 보다 효율적으로 생성합니다. 데이터베이스의 DOP(병렬도)는 Autonomous AI Database on Dedicated Exadata Infrastructure 서비스 레벨 및 ECPU 또는 OCPU 설정의 영향을 받으며 각 청크 프로세스의 레코드 수를 결정합니다. 작업을 병렬로 실행하면 일반적으로 많은 테이블에서 대량의 데이터를 생성할 때 성능이 향상됩니다. 합성 데이터 생성의 병렬 처리를 관리하려면 priority를 선택적 매개변수로 설정합니다. 선택적 매개변수를 참조하십시오.

예: 데이터 액세스 사용 또는 사용 안함

이 예에서는 관리자가 데이터 액세스를 제어하고 Select AI가 실제 스키마 테이블을 LLM으로 전송하지 못하도록 하는 방법을 보여줍니다.

데이터 액세스 사용 안함

스키마 테이블에 대한 액세스를 제한하려면 관리자로 로그인하고 다음 절차를 실행합니다.

EXEC DBMS_CLOUD_AI.DISABLE_DATA_ACCESS;
 
PL/SQL procedure successfully completed.

데이터 액세스 제한 비활성화 AI의 narrate 작업 및 합성 데이터 생성을 선택합니다. narrate 작업 및 합성 데이터 생성 시 오류가 발생합니다.

데이터베이스 사용자로 로그인하고 AI 프로파일을 만들고 구성합니다. 를 검토하여 AI 프로파일을 구성합니다.

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
          profile_name =>'DATA_ACCESS',
          attributes   =>'{"provider": "openai",
            "credential_name": "OPENAI_CRED",
            "object_list": [{"owner":"SH"}]
          }');
END;
/

EXEC DBMS_CLOUD_AI.SET_PROFILE('DATA_ACCESS');
 

select ai how many customers;

NUM_CUSTOMERS
55500

select ai narrate what are the top 3 customers in San Francisco;

ORA-20000: Data access is disabled for SELECT AI.
ORA-06512: at "C##CLOUD$SERVICE.DBMS_CLOUD", line 2228
ORA-06512: at "C##CLOUD$SERVICE.DBMS_CLOUD_AI", line 13157
ORA-06512: at line 1 https://docs.oracle.com/error-help/db/ora-20000/
The stored procedure 'raise_application_error' was called which causes this error to be generated
Error at Line: 1 Column: 6

다음 예에서는 합성 데이터를 생성하려고 할 때 트리거되는 오류를 보여 줍니다.

BEGIN
DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
profile_name => 'DATA_ACCESS_SDG',
object_name => 'CUSTOMERS_NEW',
owner_name => 'ADB_USER,
record_count => 5
);
END;
/ 

ERROR at line 1:

ORA-20000: Data access is disabled for SELECT AI.
ORA-06512: at "C##CLOUD$SERVICE.DBMS_CLOUD", line 2228
ORA-06512: at "C##CLOUD$SERVICE.DBMS_CLOUD_AI", line 13401

ORA-06512: at line 2
데이터 액세스 활성화

다음 예에서는 데이터 액세스를 사용으로 설정하는 방법을 보여줍니다. 관리자로 로그인하고 다음 절차를 실행합니다.

EXEC DBMS_CLOUD_AI.ENABLE_DATA_ACCESS;
 
PL/SQL procedure successfully completed.

데이터베이스 사용자로 로그인하고 AI 프로파일을 만들고 구성합니다. 를 검토하여 AI 프로파일을 구성합니다. narrate 작업을 실행하고 합성 데이터를 별도로 생성합니다.

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
          profile_name =>'DATA_ACCESS_NEW',
          attributes   =>'{"provider": "openai",
            "credential_name": "OPENAI_CRED",
            "object_list": [{"owner":"SH"}]
          }');
   END;
   /

PL/SQL procedure successfully completed.

EXEC DBMS_CLOUD_AI.SET_PROFILE('DATA_ACCESS_NEW');

PL/SQL procedure successfully completed.


select ai how many customers;

NUM_CUSTOMERS
55500

select ai narrate what are the top 3 customers in San Francisco;

"RESPONSE"
"The top 3 customers in San Francisco are Cody Seto, Lauren Yaskovich, and Ian Mc"

다음 예에서는 데이터 액세스를 사용으로 설정한 후 성공적인 합성 데이터 생성을 보여줍니다.

BEGIN
DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
profile_name => 'DATA_ACCESS_SDG',
object_name => 'CUSTOMERS_NEW',
owner_name => 'ADB_USER',
record_count => 5
);
END;
/ 

PL/SQL procedure successfully completed.