使用 Select AI 從自然語言提示產生 SQL

專用 Exadata Infrastructure Select AI 上的自治式 AI 資料庫可讓您使用自然語言查詢資料。

Select AI 功能允許 Autonomous AI Database 使用具有大型語言模型 (LLM) 的生成式 AI,將使用者的輸入文字轉換為 Oracle SQL。Select AI 會處理自然語言提示,以中繼資料補充提示,然後產生和執行 SQL 查詢。

關於 Select AI

使用自然語言透過 SQL 與資料庫和 LLM 互動,以提高使用者生產力並開發 AI 型應用程式。Select AI 使用生成式 AI 來簡化和自動化,無論是從自然語言提示產生、執行和說明 SQL、使用向量儲存區擷取增強生成、產生合成資料或與 LLM 交談。

使用 Select AI 時,Autonomous AI Database 會管理將自然語言轉換為 SQL 的程序。這表示您可以提供自然語言提示,而非 SQL 程式碼來與資料互動。Select AI 可作為 SQL 使用者和開發人員的生產力工具,讓非專業 SQL 使用者無須瞭解資料結構或技術語言,即可從資料中取得有用的洞察力。

Select AI 還可將擷取增強生成 (RAG) 流程自動化,從產生向量內嵌,到根據您的提示使用向量儲存區進行語意相似性搜尋,擷取相關內容。其他功能包括合成資料產生、支援對話的交談歷史記錄以及其他功能,全都來自 SQL 介面。

DBMS_CLOUD_AI 套裝程式可與使用者指定的 LLM 整合,以使用自然語言提示產生 SQL 程式碼。為了生成 SQL 的自然語言,此套件為包含相關資料庫綱要中繼資料的 LLM 提供增強的提示。這會啟用根據自然語言提示產生、執行及說明 SQL 查詢。它也有助於使用向量儲存區產生檢索增強,產生合成資料,並允許與 LLM 交談。DBMS_CLOUD_AI 套裝軟體可與 Select Your AI Provider and LLMs 中列出的 AI 提供者搭配使用。

注意:

支援的平台

客戶專用 Exadata 基礎架構和雲端上的 Autonomous AI Database Serverless 和 Autonomous AI Database 支援 Select AI。

相關術語

請務必先瞭解與 Select AI 搭配使用的各種術語,再加以使用。

下列是與 Select AI 功能相關的詞彙:

詞彙 定義
對話 Select AI 中的對話代表使用者與系統之間的互動交換,讓使用者能夠透過一系列的自然語言提示查詢或與資料庫互動。Select AI 結合以階段作業為基礎的短期對話,根據先前的互動為目前的提示產生感知情境的回應。最多 10 個先前的提示會併入具有短期對話的目前要求中,建立已傳送至 LLM 的增強提示。Select AI 支援使用可自訂的長期對話,讓您能夠在不混合環境定義的情況下使用具有不同主題的 Select AI,可透過 DBMS_CLOUD_AI 套件的對話 API 進行設定。請參閱使用及自訂對話以瞭解詳細資訊。
資料庫證明資料 「資料庫證明資料」是用來存取和與資料庫互動的認證證明資料。它們通常由使用者名稱和密碼組成,有時也會由其他認證因素 (例如安全記號) 補充。這些證明資料主要用來建立應用程式或使用者與資料庫之間的安全連線,確保只有獲得授權的個人或系統才能存取和操控資料庫中儲存的資料。
LLM 幻覺 「大型語言模型」相關資訊環境中的幻燈片指的是模型產生與輸入提示不正確、非敏感或無關之文字的現象。儘管模型嘗試產生一致的文字,但這些執行個體可以包含構成、誤導或純粹想像的資訊。由於訓練資料的基礎、缺乏適當的情境理解,或模型訓練過程中的限制,因此可能會發生幻覺。
IAM Oracle Cloud Infrastructure Identity and Access Management (IAM) 可讓您控制能夠存取雲端資源的對象。您可以控制使用者群組具備的存取類型,以及特定資源的存取類型。若要進一步瞭解,請參閱身分識別與存取管理簡介
反覆精簡

反覆精簡是指透過反饋或評估的重複調整週期,逐步改善解決方案或模型的過程。它從初始近似值開始,逐步調整,並繼續直到達到所需的準確性或結果為止。每個反覆運算都建立在上一個,結合更正或最佳化來更接近目標。

在文字摘要產生中,反覆精簡查詢對於處理大型檔案或文件非常有用。處理程序會將文字分割成可管理的區塊,例如符合 LLM 的記號限制、產生一個區塊的摘要,然後依序合併下列區塊來改善摘要。

反覆精簡的使用案例:

  • 最適用於情境準確性和一致性至關重要的情況,例如摘要每個零件在先前建置的複雜或高度互連文字時。
  • 適合可接受循序處理的較小規模任務。

請參閱彙總技術

MapReduce

一般而言,MapReduce 程式設計模型會將工作分成兩個階段來處理大量資料:對應與減少。

  • 對應:處理輸入資料並將其轉換成索引鍵 - 值組。
  • 減少:根據索引鍵聚總和摘要對應的資料。MapReduce 執行大型資料集的平行處理。

如果是 Select AI Summarize,MapReduce 將文字分割成多個區塊,並以平行和獨立的方式處理,為每個區塊產生個別摘要。接著,這些摘要會結合以形成一致的整體摘要。

減少地圖的使用案例:

  • 最適用於速度和可擴展性為優先事項的大規模平行任務,例如彙總非常大型的資料集或文件。
  • 適合可接受區塊獨立性的情況,日後可彙總摘要。

請參閱彙總技術

中繼資料

中繼資料是描述資料的資料。在 Select AI 中,中繼資料是資料庫中繼資料,意指描述資料庫表格與檢視之結構、組織及特性的資料。

對於資料庫表格和視觀表,描述資料包括資料欄名稱和類型、限制條件和索引鍵、視觀表定義、關係、歷程、品質和新鮮度指標、安全性分類以及存取原則。妥善管理的描述資料可讓您探索、更正使用狀況、調整效能及符合規範。選取 AI 可使用包含表格定義 (表格名稱、資料欄名稱及其資料類型) 的表格描述資料增強 NL2SQL 提示,以及選擇性地使用表格和資料欄註解、註解和限制條件。

描述資料強化

以高品質描述、註解和註解增強資料庫綱要的實務,讓 LLM 得以更加瞭解表格和資料欄的意圖、釐清業務意義,並產生更準確的 SQL。它會將裸機表格或資料欄名稱轉換為具有明確意圖、關係及限制的良好文件資產。

應徵者資訊包括:

  • 表格與資料欄描述:用途、業務定義、單位以及允許的值範圍
  • 關鍵碼與關係:主要 / 外來關鍵碼、結合路徑
  • 資料語意:時間資料值、維度變更緩慢、去除重複規則
  • 限制與品質:可為空值、唯一性、驗證規則、資料新鮮度
  • 同義字與別名:對應至技術名稱的通用商業詞彙
  • 範例和樣式:範例值、一般篩選或聚總

請參閱 AI 強化簡介,深入瞭解如何透過 Visual Studio Code 使用 Oracle SQL Developer for VS Code 新增這類中繼資料。

自然語言提示 自然語言提示是人類可讀的指示或要求,用於引導生成式 AI 模型,例如大型語言模型。使用者不需使用特定的程式設計語言或命令,即可以更具對話性或自然性的語言表單輸入提示,與這些模型互動。然後,模型會根據提供的提示產生輸出。
網路存取控制清單 (ACL) 「網路存取控制清單」是一組規則或權限,定義允許透過網路裝置 (例如路由器、防火牆或閘道) 傳送的網路流量。ACL 會根據各種條件 (例如 IP 位址、連接埠號碼以及協定) 來控制及篩選內送和外送流量。他們在網路安全性中扮演關鍵角色,可讓管理員管理及限制網路流量,以防止未經授權的存取、潛在的攻擊及資料外洩。
相似性搜尋 相似性搜尋會透過比較向量儲存區中的特徵向量來識別和擷取與指定查詢相符的資料點。
向量的距離 向量距離透過計算多維空間中特徵向量之間的距離來測量特徵向量之間的相似性或不相似性。
向量索引 向量索引可組織和儲存特徵向量,以有效率地搜尋和擷取相關資料。
向量存放區 向量儲存包括儲存、管理和啟用涉及向量內嵌語意相似性搜尋的系統。這包括獨立向量資料庫和 Oracle Database 23ai AI Vector Search。

選取 AI 使用案例

Select AI 可增強資料互動,讓開發人員能夠直接從 SQL 建置 AI 驅動的應用程式、將自然語言提示轉換為 SQL 查詢和文字回應、支援與 LLM 的交談互動、使用 RAG 提高目前資料的回應準確度,以及產生合成資料。

使用案例包括:

用法指導方針

提供用法指導方針,確保有效且正確地使用自然語言提示產生 SQL,以確保增強的使用者體驗。

預定用途

此功能用於產生與執行由使用者提供的自然語言提示所產生的 SQL 查詢。它會結合使用者選擇的大型語言模型 (LLM),根據其綱要描述資料自動執行手動作業。

雖然可以提供任何提示 (包括與 SQL 查詢結果生產無關的提示),但 Select AI 著重於 SQL 查詢產生。Select AI 可使用 chat 動作提交一般要求。

提示擴增資料

資料庫會以資料庫中繼資料增強使用者指定的提示,以減輕 LLM 中的虛構。增強提示接著會傳送至使用者指定的 LLM 以產生查詢。

資料庫僅會以綱目中繼資料來增強提示。此描述資料可能包括綱要定義、表格和資料欄註解,以及可從資料說明和目錄取得的內容。為了產生 SQL,在擴增提示時,資料庫不會提供表格或檢視內容 (實際列或欄值)。

不過,narrate 動作會將查詢結果 (可能包含資料庫資料) 提供給使用者指定的 LLM,以產生描述查詢結果的自然語言文字。

警告:大型語言模型 (LLM) 已接受廣泛的文字文件和內容訓練,通常來自網際網路。因此,LLM 可能包含無效或惡意內容的模式,包括 SQL 資料隱碼攻擊。因此,儘管 LLM 堅持產生有用且相關的內容,但它們也可以產生不正確和錯誤的資訊,包括產生不準確結果的 SQL 查詢和 (或) 危害資料的安全性。將會在您的資料庫中執行由使用者指定的 LLM 提供者代表您產生的查詢。貴方對本功能的使用須自行承擔風險,並且儘管 Oracle 提供之服務相關的任何其他條款與條件,仍構成貴方接受該風險,並明確排除 Oracle 對該使用所造成之任何損害的責任或責任。

選取您的 AI 提供者與 LLM

選擇符合您安全標準並符合特定需求 (例如文字或程式碼產生) 的 AI 提供者和 LLM。

不同的 LLM 會根據其訓練資料和目標,在各種任務中脫穎而出。有些模型非常適合產生文字,但在產生程式碼時可能表現不佳,其他模型則專門針對編碼工作進行最佳化。選擇最符合您需求的 LLM。

AI 提供者 LLM RAG 的內嵌模型 目的
OCI 生成式 AI
  • meta.llama-3.3-70b-instruct (預設)
  • 中繼 -3.2-90b-vision-instruct
  • meta.llama-3.2-11b-vision-instruct
  • meta.llama-3.1-70b-instruct
  • meta.llama-3.1-405b-instruct
  • cohere.command-r-08-2024
  • cohere.command-r-plus-08-2024
  • cohere.command-r-16k (已不再使用)
  • cohere.command-r-plus (已不再使用)
  • xai.grok-3
  • xai.grok-3 速

請參閱:

  • cohere.embed-english-v3.0 (預設)
  • cohere.embed- 多語言 -v3.0
  • cohere.embed- 英文 -light-v3.0
  • cohere.embed-multilingual-light-v3.0

請參閱關於在生成式 AI 中內嵌模型

所有 SELECT AI 動作 (例如 runsqlshowsqlexplainsqlnarratechat) 都支援 OCI Generative AI Chat 模型。

只有 SELECT AI chat 動作支援「OCI 產生」文字模型。

若要設定您的設定檔屬性,請參閱設定檔屬性

Azure OpenAI 服務

  • GPT-4o
  • GPT-4
  • GPT-4 Turbo 願景
  • GPT-3.5 渦輪增壓機

文字嵌入 -ada-002 最適合從自然語言提示、chat 動作和 Select AI RAG 產生 SQL。
OpenAI

  • gpt-3.5-turbo (預設)
  • gpt-4o
  • gpt-4o-mini
  • gpt-4
  • gpt-4-0613
  • gpt-4-32k
  • gpt-4-32k-0613
  • gpt-3.5-turbo-0613
  • gpt-3.5-turbo-16k
  • gpt-3.5-turbo-16k-0613

文字嵌入 -ada-002 最適合從自然語言提示、chat 動作和 Select AI RAG 產生 SQL。
OpenAI 相容

OpenAI 相容提供者的模型,例如:

  • 煙火人工智慧
  • 公司簡介
  • 其他人

從 OpenAI 相容提供者嵌入模型。例如,請參閱 Fireworks AI 內嵌模型 支援廣泛的使用案例。
Cohere

  • 指令 (預設)
  • 每晚命令 (實驗中)
  • 指令 r
  • 命令加
  • 命令光源
  • 每晚命令 (實驗中)
  • 自訂模式

中文 (繁體) v2.0 最適用於 chat 動作。
Google

  • gemini-1.5-flash (預設)
  • gemini-1.5-pro
  • gemini-1.0-pro

text-embedding-004 (預設) 最適合從自然語言提示、chat 動作和 Select AI RAG 產生 SQL。
人類

  • claude-3-5-sonnet-20240620 (預設)
  • 20240229 年 3 月
  • claude-3-sonnet-20240229
  • 3- 海庫 -20240307

最適合從自然語言提示、chat 動作和 Select AI RAG 產生 SQL。
Hugging Face

  • Mixtral-8x7B-Instruct-v0.1 (預設)
  • Meta-Llama-3-70B- 指示
  • Qwen1.5-1.8B
  • 其他聊天模式

最適合從自然語言提示、chat 動作和 Select AI RAG 產生 SQL。
AWS

  • amazon.titan-embed-text-v1
  • amazon.titan-embed-text-v2:0
  • 繁體中文 (台灣)
支援廣泛的使用案例。

注意:

使用 DBMS_CLOUD_AI 設定 AI 設定檔

自治式 AI 資料庫使用 AI 設定檔來協助和設定對 LLM 的存取,並根據自然語言提示設定以產生、執行及說明 SQL。它也有助於使用內嵌模型和向量索引產生檢索增強生成,並允許與 LLM 交談。

AI 設定檔包含作為自然語言查詢目標的資料庫物件。這些目標中使用的描述資料可以包括資料庫表格名稱、資料欄名稱、資料欄資料類型以及註解。您可以使用 DBMS_CLOUD_AI.CREATE_PROFILEDBMS_CLOUD_AI.SET_PROFILE 程序建立和設定 AI 設定檔。

DBMS_CLOUD_AI 的需求

必須執行下列項目,才能執行 DBMS_CLOUD_AI

若要設定 DBMS_CLOUD_AI,請執行下列動作:

  1. DBMS_CLOUD_AI 套裝程式的 EXECUTE 權限授予想要使用 Select AI 的使用者。

    依照預設,只會授予 ADMIN 使用者 EXECUTE 權限。ADMIN 使用者可以將 EXECUTE 權限授予其他使用者。

    下列範例將 EXECUTE 權限授與 ADB_USER

     grant execute on DBMS_CLOUD_AI to ADB_USER;
    

    下列範例授予 ADB_USER 使用 api.openai.com 端點的權限。

     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;
     /
    
  2. 將網路 ACL 存取權授予想要使用 Select AI 的使用者以及 AI 提供者端點的使用者。

    ADMIN 使用者可授予網路 ACL 存取權。請參閱 Oracle Database 19c PL/SQL Packages and Types Reference 中的 APPEND_HOST_ACE ProcedureOracle Database 26ai PL/SQL Packages and Types Reference ,瞭解詳細資訊。

  3. 建立證明資料以啟用 AI 提供者的存取權。

    請參閱 CREATE_CREDENTIAL 程序以瞭解詳細資訊。

    以下範例說明如何建立證明資料以啟用對 OpenAI 的存取。

     EXEC DBMS_CLOUD.CREATE_CREDENTIAL('OPENAI_CRED', 'OPENAI', '*your_api_token`');
    

APPEND_HOST_ACE 函數參數

Parameter - 參數 描述
host

主機,可以是主機的名稱或 IP 位址。您可以使用萬用字元來指定網域或 IP 子網路。主機或網域名稱不區分大小寫。

若為 OpenAI,請使用 api.openai.com

若為 Cohere,請使用 api.cohere.ai

若為 Azure OpenAI 服務,請使用 <azure_resource_name>.openai.azure.com 。如需有關 azure_resource_name 的詳細資訊,請參閱設定檔屬性

若為 Google,請使用 generativelanguage.googleapis.com

對於人類,請使用 api.anthropic.com

對於 Hugging Face,請使用 api-inference.huggingface.co

ace 存取控制項目 (ACE)。系統會提供 XS$ACE_TYPE 類型來建構 ACL 的每個 ACE 項目。

如需詳細資訊,請參閱 Oracle Database 19c Real Application Security Administrator's and Developer's Guide 中的 Creating ACLs and ACEsOracle Database 26ai Real Application Security Administrator's and Developer's Guide

DBMS_CLOUD.CREATE_CREDENTIAL 參數

Parameter - 參數 描述
credential_name 要儲存之證明資料的名稱。credential_name 參數必須符合 Oracle 物件命名慣例,此慣例不允許空格或連字號。
username

同時使用 usernamepassword 引數指定您的 AI 提供者憑證。

username 是使用者指定的使用者名稱。

password

同時使用 usernamepassword 引數指定您的 AI 提供者憑證。

password 是您的 AI 提供者秘密 API 金鑰,取決於提供者:OpenAI、Cohere、Azure OpenAI Service、OCI、Google、Anthropic 或 Hugging Face。請參閱以瞭解詳細資訊。

建立和設定 AI 設定檔

說明建立和啟用 AI 設定檔的步驟。

使用 DBMS_CLOUD_AI.CREATE_PROFILE 建立 AI 設定檔。接下來,請啟動 DBMS_CLOUD_AI.SET_PROFILE 來啟用 AI 設定檔,讓您可以搭配自然語言提示使用 SELECT AI

注意:您必須先在每個新的資料庫階段作業 (連線) 中執行 DBMS_CLOUD_AI.SET_PROFILE,才能使用 SELECT AI

下列具有 OpenAI 提供者的範例會建立名為 OPENAIAI 設定檔,並設定目前使用者階段作業的 OPENAI 設定檔。

-- Create AI profile
--
SQL> BEGIN
  DBMS_CLOUD_AI.create_profile(
      'OPENAI',
      '{"provider": "openai",
        "credential_name": "OPENAI_CRED",
        "object_list": [{"owner": "SH", "name": "customers"},
                        {"owner": "SH", "name": "sales"},
                        {"owner": "SH", "name": "products"},
                        {"owner": "SH", "name": "countries"}]
       }');
END;
/
--
-- Enable AI profile in current session
--
EXEC DBMS_CLOUD_AI.set_profile('OPENAI');

使用 AI 關鍵字輸入提示

使用 AI 作為 SELECT 陳述式中的關鍵字,以使用自然語言提示與資料庫互動。

SELECT 陳述式中的 AI 關鍵字會指示 SQL 執行引擎使用作用中 AI 設定檔中識別的 LLM 來處理自然語言並產生 SQL。

您可以在 Oracle 從屬端 (例如 SQL Developer、OML Notebooks 和第三方工具) 的查詢中使用 AI 關鍵字,以自然語言與資料庫互動。

注意:您無法使用 AI 關鍵字執行 PL/SQL 敘述句、DDL 敘述句或 DML 敘述句。

語法

執行 AI 提示的語法如下:

SELECT AI `action` `natural_language_prompt`

參數

下列是 action 參數可用的參數:

Parameter - 參數 描述
runsql 使用自然語言提示執行提供的 SQL 命令。這是預設動作,可以選擇是否指定此參數。
showsql 顯示自然語言提示的 SQL 陳述式。
narrate 提示的輸出會以自然語言說明。此選項會將 SQL 結果傳送給 AI 提供者,以產生自然語言摘要。
chat 根據提示直接從 LLM 產生回應。如果 DBMS_CLOUD_AI.CREATE_PROFILE 函數中的 conversation 設為 true,此選項會包含先前互動或提示的內容 (可能包括綱要描述資料)。
explainsql 提示所產生的 SQL 以自然語言解釋。此選項會將產生的 SQL 傳送至 AI 提供者,以產生自然語言說明。

使用注意事項

使用及自訂對話

Select AI 中的對話指使用者與系統之間的互動對話,其中儲存並管理一連串使用者提供的自然語言提示,以支援 LLM 互動的長期記憶體。

Select AI 支援在 AI 設定檔中啟用的短期、以階段作業為基礎的對話,以及使用特定程序或函數和對話 ID 啟用的長期具名對話。

注意:從 19.30 版開始,Oracle Database 19c 以及從 23.26.1 版開始的 Oracle Database 26ai 中提供 Select AI 對話支援。

對話的類型

Select AI 支援以階段作業為基礎的短期對話和可自訂的對話。

以階段作業為基礎的短期對話:Select AI 包含以階段作業為基礎的短期對話,可根據先前的互動為目前提示產生感知情境的回應。

您可以在 AI 設定檔中將 conversation 屬性設為 true|false 來啟用它。與多個對話功能不同,以階段作業為基礎的對話存放區提示只會在階段作業的持續時間內顯示。提示會儲存在暫時表格中、階段作業結束時自動刪除,而且無法在對話之間重複使用和切換。

可自訂的長期對話:Select AI 支援建立和使用可自訂的對話,讓您可以將 Select AI 與不同的主題搭配使用,而無需混合內容,從而提高彈性和效率。您可以透過 DBMS_CLOUD_AI 對話程序和功能來建立、設定、刪除及更新對話。當您啟用對話時,Select AI 會擷取提示歷史記錄,並將其傳送至 LLM 以產生目前提示的回應。這些回應會儲存在永久表格中以供日後使用。

注意:「選取 AI 對話」支援下列動作:runsqlshowsqlexplainsqlnarratechat

如何使用可自訂對話

您可以使用 Select AI 進行可自訂的對話,方法如下:

注意:如果您同時使用多個對話和 conversation: [true|false] 設定,系統會忽略 conversation 設定。

在 SQL 查詢產生 (NL2SQL) 的相關資訊環境中,對話提供更直觀且可存取的方式來處理資料,讓使用者更輕鬆地擷取洞察分析並執行工作,而不需要對 SQL 的深入技術知識。對話也可以與 Select AI 的交談和 RAG 功能搭配使用。

例如,對話提供直觀的方式來分析資料:

若要啟用對話,請參閱範例:在 Select AI 中啟用對話以取得完整範例。

以階段作業為基礎的對話與可自訂的對話

下表比較 Select AI 中的階段作業式對話與可自訂對話:

問題 以階段作業為基礎的短期對話 可自訂的長期對話
何時該使用? 最適合快速、臨時的交談,您希望模型在單一階段作業中記住最近的問題與答案。當您稍後不需要儲存或重複使用對話時,此功能相當實用。 專為可能跨多個階段作業的較長或持續對話所設計。當您想要追蹤、複查或管理對話歷史記錄,或者當應用程式的不同部分需要在一段時間內存取相同的對話相關資訊環境時,此功能非常有用。
我該如何啟用? 在您的 AI 設定檔中設定 {"conversation": true or false} 使用 DBMS_CLOUD_AI.SET_CONVERSATION_ID 程序或 DBMS_CLOUD_AI.GENERATE
允許多少對話? 一、

您可以建立多個對話。

如果您明確指定對話 ID,您可以替代對話 ID,視需要將提示與適當的對話建立關聯。

提示的儲存位置和儲存時間為何? 提示會儲存在暫時表格中,並在階段作業結束時刪除。

提示會儲存在永久表格中。

提示會保留在資料庫中,以保留 retention_days 參數在 DBMS_CLOUD_AI.CREATE_CONVERSATION 程序中指定的天數。在保留期間之後,對話及其提示會自動刪除。您也可以使用 DBMS_CLOUD_AI.DELETE_CONVERSATION_PROMPT 程序,手動刪除提示。

會儲存多少個提示,以及將多少個提示傳送至 LLM? 最多可儲存 10 個提示並傳送至 LLM。您無法自訂此限制。

系統會儲存所有提示。

依預設,系統會將 10 個最新的提示傳送至 LLM。您可以使用 conversation_length 參數自訂此參數。請參閱 CREATE_CONVERSATION 屬性

是否可以刪除個別提示? 否,您無法手動刪除個別提示。 您可以使用 USER_CLOUD_AI_CONVERSATION_PROMPTS 檢視中指定的提示 ID,並使用 DBMS_CLOUD_AI.DELETE_CONVERSATION_PROMPT 程序來刪除特定的個別提示。
AI 設定檔是否用於擷取對話? 是,Select AI 會擷取先前使用相同 AI 設定檔產生的提示和回應。 否,Select AI 會追蹤儲存提示和回應時使用的 AI 設定檔,但不會根據該設定檔限制擷取。它會將所有對話歷史記錄傳送給 LLM 以引導產生回應,無論用來產生回應的設定檔為何。
哪裡可以查看提示歷史記錄? 提示會儲存在 CLOUD USER 下的暫時表格中,但無法存取以進行查詢。 您可以透過 DBMS_CLOUD_AI 對話檢視來查詢和複查對話和提示。請參閱 DBMS_CLOUD_AI 檢視瞭解詳細資訊。

提供意見以改善 LLM

Select AI 可讓您提供意見回饋,協助改善所選 LLM 產生更準確的 SQL 查詢的能力。

注意:此功能僅適用於 Oracle Database 23ai。您可以將它與現有的 Select AI 動作搭配使用:runsqlshowsqlexplainsql。請確定您的 AI 設定檔已設定為產生 NL2SQL 而不是 RAG。

您可以提供意見,以透過 feedback 動作或 DBMS_CLOUD_AI.FEEDBACK 程序改善產生之 SQL 的準確性。當您第一次使用意見回饋功能時,選取 AI 會使用預設屬性建立名為 <profile_name>_FEEDBACK_VECINDEX 的預設向量索引。此索引可協助根據提供的意見來縮小未來產生的 SQL。如需詳細資訊,請參閱 FEEDBACK 的向量索引

提示:當指定的 LLM 無法產生正確的 SQL 查詢或未從其中一個 NL2SQL SELECT AI 動作傳回預期的結果時,請使用 DBMS_CLOUD_AI.FEEDBACK 程序。您也可以使用 DBMS_CLOUD_AI.FEEDBACK 程序,將正確的 SQL 直接新增至向量表格。這有助於引導未來 SQL 產生,作為類似提示的參照。

接受下列類型的意見回饋:

使用意見回饋的優點

Select AI 的意見回饋動作與程序引進了可提高 SQL 查詢產生準確性的提示調整機制。

AI 設定檔的擁有者可以針對產生的 SQL 查詢提供意見,以及隨著時間的推移,從使用者互動中學習 Select AI 系統。此學習涉及在提示與意見內容的儲存庫中,使用向量搜尋來識別與目前提示類似的提示。在增強的提示中,會提供最符合的範例作為 LLM 的中繼資料。以下為優點:

如何提供意見

Select AI 可讓您使用 feedback 動作或呼叫 DBMS_CLOUD_AI.FEEDBACK 程序來提供意見。

注意:在擁有 AI 設定檔的單一資料庫使用者下,多位使用者共用資料庫階段作業的應用程式中,請勿使用意見反應動作。AI 設定檔擁有者應在確認更正後的查詢適用於該設定檔的所有使用者之後,才提供意見回饋。

您可以包含下列項目來提供意見:

注意:若要使用上一個 SQL,請確定在 Oracle SQL*Plus 或 Oracle SQLcl 中將伺服器輸出設為關閉。您必須具備 sys.v_$sessionv_$mapped_sql 表格的 READ 權限。

  GRANT READ ON SYS.V_$MAPPED_SQL TO ADB_USER;
  GRANT READ ON SYS.V_$SESSION TO ADB_USER;

請參閱 FEEDBACK 程序範例:選取 AI 意見以瞭解詳細資訊。

使用特性圖表查詢圖表資料

Select AI 會使用自然語言在 Oracle Property Graphs 上產生 Property Graph 查詢 (PGQ)。它可讓使用者以最少的 SQL 知識,透過 GRAPH_TABLE 運算子查詢圖表資料。

Select AI 將自然語言延伸至 SQL (NL2SQL) 功能,以圖形結構,讓您能夠使用自然語言查詢 SQL 屬性圖形。Select AI 會套用 GRAPH_TABLE 運算子,以解譯圖形結構化資料中的關係和屬性。它會根據 AI 設定檔中定義的資料物件產生 SQL 或 PGQ 圖表查詢。在 AI 設定檔中包含特性圖表時,Select AI 會使用生成式 AI 來建立透過 GRAPH_TABLE 運算子參考圖表的 PGQ 查詢。LLM 會自動接收圖形物件的中繼資料 (例如 CREATE PROPERTY GRAPH 陳述式),以產生準確的查詢。指定表格、視觀表或關聯物件時,Select AI 會產生 SQL 查詢。此功能可簡化 Oracle AI Database 中儲存之圖表資料的樣式比對查詢,並減少手動建構 SQL 查詢的相依性。

當您使用 object_list 屬性中定義的一或多個特性圖表建立 AI 設定檔時,AI 設定檔中定義的 LLM 會使用指定特性圖表的內容解譯提示。Select AI 會建立增強的提示,其中包括:

此擴增提示會傳送至 LLM。Select AI 會執行查詢並傳回結果。如果特性圖與其他物件類型 (例如 AI 設定檔中的表格、綱要或視觀表) 一起指定,則 Select AI 會產生錯誤。

SQL 與 PGQ

使用 Select AI 時,產生的查詢類型取決於 AI 設定檔的 object_list 屬性中定義的物件。

請參閱 SQL 特性圖表SQL GRAPH 查詢以瞭解詳細資訊。

在特性圖表上使用 Select AI 的優勢

資料庫使用者可以使用 Select AI,從自然語言生成圖表查詢,減少手動工作並改善對圖表關係的理解。

主要優點包括:

限制

「特性圖的選取 AI」不支援下列功能:

如何在特性圖表上使用 Select AI

Select AI 可讓您使用 DBMS_CLOUD_AI.GENERATE 函數或使用 Select AI <action> <prompt> 來瀏覽圖表資料。

在 AI 設定檔的 object_list 屬性中定義特性圖表之後,您可以使用:

以下為支援的動作:runsqlshowsqlexplainsqlnarrateshowpropmt。Select AI for Property Graph 也支援基於工作階段的短期和可自訂的長期對話。

請參閱範例:為特性圖表選取 AI範例:特性圖表的範例提示以瞭解詳細資訊。

使用 Select AI 產生摘要

Select AI 可讓您產生文字摘要,尤其是大型文字,通常支援多達 1 GB 的 AI 供應商。您可以根據特定需求,從文字或大型檔案擷取關鍵洞察分析。此功能使用 AI 設定檔中指定的 LLM 產生指定文字的摘要。

Select AI 以下列方式提供內容的摘要:

注意:

彙總技術

您可以輸入全文作為 LLM 提示,以摘要大型文件。不過,由於 LLM 具有記號限制,因此 Select AI 會套用不同的技術來摘要大型文件。

Select AI 使用反覆精簡功能和 MapReduce 作為彙總技術。請參閱相關術語以瞭解詳細資訊。

根據指定 LLM 的最大權杖大小,Select AI 可以將大型內容細分為較小且容易處理的區塊,以符合 LLM 的限制。然後,選取 AI 可以使用反覆精簡查詢或對應縮小技術來產生摘要。Select AI 使用 MapReduce 作為預設設定。請參閱 SUMMARIZE 函數SUMMARIZE 參數以瞭解詳細資訊。

使用 Select AI 翻譯文字

透過 Select AI,您可以使用 OCI 翻譯服務的生成式 AI,將您的文字翻譯成您選擇的語言。

您可以將此功能與現有的 Select AI RAG 搭配使用。您可以將 translateDBMS_CLOUD_AI.GENERATEnarrate 結合使用生成式 AI,以您偏好的語言產生翻譯輸出。

請參閱 TRANSLATE FunctionGENERATE FunctionExample:Select AI TRANSLATE 以深入瞭解。

使用翻譯的優點

Select AI 中的翻譯功能可讓您在下方翻譯不同語言的輸入文字:

如何使用翻譯

Select AI 可讓您使用 translate 動作或呼叫 DBMS_CLOUD_AI.GENERATEDBMS_CLOUD_AI.TRANSLATE 函數,將文字輸入翻譯成您偏好的語言。

若要使用「選取 AI」翻譯功能,您必須具備適當的 IAM 原則權限,才能存取 Oracle Cloud Infrastructure Language 服務。

授予在 IAM 原則中使用 ai-service-language-family 資源的權限。將權限授予特定區間中使用者群組的原則敘述句範例如下:

allow group <your group name> to use ai-service-language-family in compartment <your_compartment>

「動態群組」會比對其 OCID 或標記來識別資料庫或函數之類的資源,而「使用者群組」則包含個別的 IAM 使用者。

當原則套用至 OCI 資源時使用動態群組,並在原則套用至人工使用者時使用使用者群組。如需建立動態與使用者群組的詳細步驟,請參閱管理動態群組

如需詳細資訊,請參閱語言原則

您可使用下列翻譯文字:

為 Python 選取 AI

Select AI for Python 將生成式 AI 功能整合至 Autonomous AI Database 工作流程中。Select AI for Python 提供用戶端程式庫 select_ai,可讓您在 Python 的 Autonomous AI Database 中使用 DBMS_CLOUD_AI 功能。Select AI for Python 支援增強生成式 AI 工作流程、摘要、意見回饋機制、一致的中繼資料管理和代理 AI 功能。它也支援 Python 3。14,並包含更新過的 HTML 文件網站 (新)

您可以執行的作業

支援的平台

Select AI for Python 已通過 Autonomous Database 19 c 和 Autonomous AI Database 26ai 認證。Python 適用的 Select AI 可在其他平台上運作,但未經認證。

按一下 https://github.com/oracle/python-select-ai/issues 以報告問題。

注意:專用 Exadata 基礎架構上的自治式 AI 資料庫不提供 Select AI Agent for Python。

Select AI 設定檔的支援函數 (同步和非同步)

當您透過設定檔傳送提示時,可以選擇為 AI 設定檔物件定義的數個函數。有些情況如下:

如需完整的函數清單,請參閱 Select AI for Python 指南。另請參閱使用 AI 關鍵字輸入提示,瞭解有關 Select AI 動作的詳細資訊。

支援的類別

此程式庫包含管理提供者、設定檔、對話、向量索引以及合成資料的類別。同時提供同步和非同步版本。

ProfileConversationVectorIndex 類別有非同步等效項目。

如需完整的 API 參考資料,請參閱 Select AI for Python 指南。

API 與屬性更新增強功能

目前提供下列增強功能:

權限和 HTTP 存取

權限管理與 HTTP 存取組態不同。

權限 API:

權限會更新以包含:

HTTP 存取 API:

其他增強功能

使用 Select AI 的範例

探索如何將 Oracle Select AI 與各種支援的 AI 供應商整合,以從自然語言提示產生、執行和解釋 SQL,或與 LLM 交談。

範例:選取 AI 動作

下列範例說明可以使用 SELECT AI 執行的動作,例如 runsql (預設值)、showsqlnarratechatexplainsqlfeedbacksummarize。這些範例使用 sh 綱要與 DBMS_CLOUD_AI.CREATE_PROFILE 函數中指定的 AI 提供者和設定檔屬性。在目前階段作業中使用 DBMS_CLOUD_AI.SET_PROFILE 程序設定 AI 設定檔之後,請使用「選取 AI 動作」。

若要產生文字摘要,請使用 SELECT AI SUMMARIZE <TEXT>

select ai how many customers exist;
CUSTOMER_COUNT
--------------
         55500
select ai showsql how many customers exist;
RESPONSE
----------------------------------------------------
SELECT COUNT(*) AS total_customers
FROM SH.CUSTOMERS
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 constantly changes due to various factors such as population growth, new businesses, and customer turnover. Additionally, the term "customer" can refer to individuals, businesses, or organizations, making it difficult to provide a specific number.
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:
select ai feedback for query "select ai showsql how many watch histories in total", please use sum instead of count;
-- Positive feedback example:
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:
select ai feedback please use sum instead of count for sql_id  1v1z68ra6r9zf;
-- Positive feedback example:
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:
select ai feedback please use ascending sorting for ranking;
-- Positive feedback example:
select ai feedback the result is correct;
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.

範例:使用 AWS 選取 AI

此範例顯示如何使用 AWS 從自然語言提示產生、執行及說明 SQL,或使用 AWS 提供的模型進行交談。

以下範例說明如何使用 AWS 作為 Amazon Bedrock 的 AI 供應商及其基礎模型。此範例顯示建立 AWS 證明資料、提供網路存取、建立 AI 設定檔,以及使用 Select AI 動作從自然語言提示產生 SQL 查詢,以及使用 AWS 基礎模型進行交談。

若要使用 AWS,請取得存取金鑰、秘密金鑰以及模型 ID。請參閱使用 DBMS_CLOUD_AI 設定 AI 設定檔中的 AWS 特定指示。使用模型 ID 作為 DBMS_CLOUD_AI.CREATE_PROFILE 程序中的 model 屬性。您必須明確指定 model 屬性,因為未提供預設模型。

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

--
-- Create Credential for AI provider
--
BEGIN
      DBMS_CLOUD.CREATE_CREDENTIAL(
        credential_name => 'AWS_CRED',
        username    => '<your_AWS_access_key>',
        password    => '<your_AWS_secret_key>'
      );
END;
/
--
-- Grant Network ACL for AWS
--
BEGIN
      DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
        host => 'bedrock-runtime.us-east-1.amazonaws.com',
        ace  => xs$ace_type(privilege_list => xs$name_list('http'),
                    principal_name => 'ADB_USER',
                    principal_type => xs_acl.ptype_db)
       );
END;
/
--
-- Create AI profile
--
BEGIN
      DBMS_CLOUD_AI.CREATE_PROFILE(
        profile_name =>'AWS',
        attributes   =>'{"provider": "aws",
          "credential_name": "AWS_CRED",
          "object_list": [{"owner": "SH", "name": "customers"},
                        {"owner": "SH", "name": "countries"},
                        {"owner": "SH", "name": "supplementary_demographics"},
                        {"owner": "SH", "name": "profits"},
                        {"owner": "SH", "name": "promotions"},
                        {"owner": "SH", "name": "products"}],
           "model" : "anthropic.claude-v2",
           "conversation" : "true"
          }');
END;
/
--
-- Enable AI profile in current session
--
EXEC DBMS_CLOUD_AI.SET_PROFILE('AWS');
--
-- Use AI
--

SELECT AI how many customers exist;
"RESPONSE"
"COUNT(*)"
55500

SELECT AI how many customers in San Francisco are married;
"RESPONSE"
"COUNT(*)"
46

SELECT AI showsql how many customers in San Francisco are married;
"RESPONSE"
"SELECT COUNT(*) AS "Number of Married Customers in San Francisco"
FROM "SH"."CUSTOMERS" C
WHERE UPPER(C."CUST_CITY") = UPPER('San Francisco')
AND UPPER(C."CUST_MARITAL_STATUS") = UPPER('Married')"

SELECT AI explainsql how many customers in San Francisco are married;

"RESPONSE""SELECT
COUNT(*) AS "Number of Married Customers in San Francisco"
FROM "SH"."CUSTOMERS" C
WHERE C."CUST_CITY" = 'San Francisco'
AND C."CUST_MARITAL_STATUS" = 'Married'

Explanation:
- Used table alias C for CUSTOMERS table 
- Used easy to read column names like CUST_CITY, CUST_MARITAL_STATUS
- Enclosed table name, schema name and column names in double quotes
- Compared string values in WHERE clause without UPPER() since the values are not in double quotes
- Counted number of rows satisfying the condition and aliased the count as "Number of Married Customers in San Francisco""

SELECT AI narrate what are the top 3 customers in San Francisco;
"RESPONSE"
The top 3 customers in San Francisco ordered by credit limit in descending order are:

1. Bert Katz
2. Madallyn Ladd
3. Henrietta Snodgrass

SELECT AI chat what is Autonomous AI Database;
"RESPONSE"
"An Autonomous AI Database is a cloud database service provided by Oracle Corporation. Some key features of Oracle Autonomous AI Database include:

- Fully automated and self-driving - The database automatically upgrades, patches, tunes, and backs itself up without any human intervention required.

- Self-securing - The database uses machine learning to detect threats and automatically apply security updates.

- Self-repairing - The database monitors itself and automatically recovers from failures and errors without downtime.

- Self-scaling - The database automatically scales compute and storage resources up and down as needed to meet workload demands.

- Serverless - The database is accessed as a cloud service without having to manually provision any servers or infrastructure.

- High performance - The database uses Oracle's advanced automation and machine learning to continuously tune itself for high performance.

- Multiple workload support - Supports transaction processing, analytics, graph processing, etc in a single converged database.

- Fully managed - Oracle handles all the management and administration of the database. Users just load and access their data.

- Compatible - Supports common SQL and Oracle PL/SQL for easy migration from on-prem Oracle databases.

So in summary, an Oracle Autonomous AI Database is a fully automated, self-driving, self-securing, and self-repairing database provided as a simple cloud service. The automation provides high performance, elasticity, and availability with minimal human labor required."
--
--Clear the profile
--
BEGIN
   DBMS_CLOUD_AI.CLEAR_PROFILE;
END;
/
--
--Drop the profile
--
EXEC DBMS_CLOUD_AI.DROP_PROFILE('AWS');

範例:在 Select AI 中啟用對話

這些範例說明如何在 Select AI 中啟用對話。

注意:具有管理員權限 (ADMIN) 的使用者必須授予 EXECUTE 並啟用網路存取控制清單 (ACL)。

以階段作業為基礎的對話

建立您的 AI 設定檔。將設定檔中的 conversation 屬性設為 true,此動作包括先前互動或提示的內容 (可能包括綱要描述資料),以及設定您的設定檔。設定檔啟用後,您就可以開始與資料進行對話。使用自然語言提出問題並視需要進行追蹤。

--Grants EXECUTE privilege to ADB_USER
--
grant execute on DBMS_CLOUD_AI to ADB_USER;

-- Grant Network ACL for 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;
/
--
-- Create Credential for AI provider
--
EXEC
DBMS_CLOUD.CREATE_CREDENTIAL(
CREDENTIAL_NAME   => 'OPENAI_CRED',
username          =>  'OPENAI',
password          =>  '`<your_api_token>`');
--
-- Create AI profile
--
BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
  profile_name   => 'OPENAI',
  attributes     =>'{"provider": "openai",
        "credential_name": "OPENAI_CRED",
        "object_list": [{"owner": "SH", "name": "customers"},
                        {"owner": "SH", "name": "countries"},
                        {"owner": "SH", "name": "supplementary_demographics"},
                        {"owner": "SH", "name": "profits"},
                        {"owner": "SH", "name": "promotions"},
                        {"owner": "SH", "name": "products"}],
        "conversation": "true"
       }');
     END;
     /
--
-- Enable AI profile in current session
--
EXEC DBMS_CLOUD_AI.SET_PROFILE('OPENAI');
--
-- Get Profile in current session
--
SELECT DBMS_CLOUD_AI.get_profile() from dual;
DBMS_CLOUD_AI.GET_PROFILE()
--------------------------------------------------------------------------------
"OPENAI"
--
-- Use AI
--
what are the total number of customers;
CUSTOMER_COUNT
--------------
         55500
break out count of customers by country;
RESPONSE
-----------------
COUNTRY_NAME 			CUSTOMER_COUNT
Italy 				7780
Brazil 				832
Japan 				624
United Kingdom 			7557
Germany 			8173
United States of America 	18520
France 				3833
Canada 				2010
Spain 				2039
China 				712
Singapore 			597
New Zealand 			244
Poland 	708
Australia 			831
Argentina 			403
Denmark 			383
South Africa 			88
Saudi Arabia 			75
Turkey 				91
what age group is most common;
RESPONSE
--------------------------------------------------------------------------------
AGE_GROUP 	CUSTOMER_COUNT
65+ 		28226
select ai keep the top 5 customers and their country by their purchases and include a rank in the result;
RESPONSE
--------------------------------------------------------------------------------
RANK 	CUSTOMER_NAME 		COUNTRY 	PURCHASES
1 	Abigail Ruddy 		Japan 		276
2 	Abigail Ruddy 		Italy 		168
3 	Abigail Ruddy 		Japan 		74
3 	Abner Robbinette 	Germany 	74
5 	Abner Everett 		France 		68
EXEC DBMS_CLOUD_AI.DROP_PROFILE('OPENAI');

可自訂對話

下列範例示範使用支援可自訂對話的對話管理 API。若要使用 Select AI 進行多個對話:

  1. 建立對話

  2. 設定目前使用者階段作業中的對話

  3. 使用 Select AI <action> <prompt>

您可以使用下列方式建立及設定對話:

範例:建立及設定可自訂的對話

下列範例示範如何使用 DBMS_CLOUD_AI.CREATE_CONVERSATION 函數建立對話,並使用 DBMS_CLOUD_AI.SET_CONVERSATION_ID 程序加以設定。

SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION;  -- in 19c, run SELECT DBMS_CLOUD_AI.create_conversation FROM dual;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
EXEC DBMS_CLOUD_AI.SET_CONVERSATION_ID('30C9DB6E-EA4D-AFBA-E063-9C6D46644B92');

下列範例示範執行 DBMS_CLOUD_AI.CREATE_CONVERSATION 程序來直接建立和設定 conversation_id

EXEC DBMS_CLOUD_AI.create_conversation;

您也可以自訂對話屬性,例如 titledescriptionretention_daysconversation_length 屬性。

SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION(
            attributes => '{"title":"My first conversation",
			"description":"this is my first conversation",
			"retention_days":5,
			"conversation_length":5}');
CREATE_CONVERSATION
------------------------------------
38F8B874-7687-2A3F-E063-9C6D4664EC3A

您可以查詢 DBA/USER_CLOUD_AI_CONVERSATIONS 檢視來檢視特定對話是否存在。

-- Verify the setup
SELECT conversation_id, conversation_title, description, retention_days,
conversation_length FROM DBA_CLOUD_AI_CONVERSATIONS WHERE
conversation_id = '38F8B874-7687-2A3F-E063-9C6D4664EC3A';
CONVERSATION_ID                      	CONVERSATION_TITLE                              DESCRIPTION                        RETENTION_DAYS                 CONVERSATION_LENGTH
------------------------------------ 	----------------------------------------------- ---------------------------------- ------------------------------ -------------------
38F8B874-7687-2A3F-E063-9C6D4664EC3A 	My first conversation                           this is my first conversation     +00005 00:00:00.000000         5

您也可以呼叫 DBMS_CLOUD_AI.GET_CONVERSATION_ID 函數來驗證對話是否已設定。

SELECT DBMS_CLOUD_AI.GET_CONVERSATION_ID;
--------------------------------------------------------------------------------
30C9DB6E-EA4F-AFBA-E063-9C6D46644B92

範例:搭配 Select AI 使用可自訂對話

建立並設定對話並啟用 AI 設定檔之後,您就可以開始與資料互動。使用自然語言提出問題並視需要進行追蹤。

使用 SELECT AI <ACTION> <PROMPT>

SELECT AI CHAT What is the difference in weather between Seattle and San Francisco?;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco are both located on the West Coast of the United States, but they have distinct weather patterns due to their unique geography and climate conditions. Here are the main differences:

1. **Rainfall**: Seattle is known for its rainy reputation, with an average annual rainfall of around 37 inches (94 cm). San Francisco, on the other hand, recei
ves significantly less rainfall, with an average of around 20 inches (51 cm) per year.
2. **Cloud Cover**: Seattle is often cloudy, with an average of 226 cloudy days per year. San Francisco is also cloudy, but to a lesser extent, with an average of 165 cloudy days per year.

......
SELECT AI CHAT Explain the difference again in one paragraph only.;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco have different weather patterns despite both experiencing a mild oceanic climate. San Francisco tends to be slightly warmer, with average temperatures ranging from 45?F to 67?F, and receives less rainfall, around 20 inches per year, mostly during winter. In contrast, Seattle is cooler, with te
mperatures ranging from 38?F to 64?F, and rainier, with around 37 inches of rainfall per year, distributed throughout the year. San Francisco is also known for its fog, particularly during summer, and receives more sunshine, around 160 sunny days per year, although it's often filtered through the fog. Overall, San Fran
cisco's weather is warmer and sunnier, with more pronounced seasonal variations, while Seattle's is cooler and rainier, with more consistent temperatures throughout the year.

範例:使用 GENERATE 函數比較兩個對話

下列範例顯示如何交替使用兩個對話來提問並驗證正確回應。每個對話都以一個著重於比較的不同問題開始。之後,當您在兩個對話中提出相同的後續追蹤問題時,每個對話都會根據其先前的內容傳回不同的答案。

-- First conversation
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
-- Second conversation
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
-- Call generate using the first conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
        prompt       =>  'What is the difference in weather between Seattle and San Francisco?',
        profile_name =>  'GENAI',
        action       =>  'CHAT',
        params       =>  '{"conversation_id":"30C9DB6E-EA4D-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco, both located in the Pacific Northwest and Northern California respectively, experience a mild oceanic climate. However, there are some notable differences in their weather patterns:
1. **Temperature**: San Francisco tends to be slightly warmer than Seattle, especially during the summer months. San Francisco's average temperature ranges from 45?F (7?C) in winter to 67?F (19?C) in summer, while Seattle's average temperature ranges from 38?F (3?C) in winter to 64?F (18?C) in summer.
2. **Rainfall**: Seattle is known for its rainy reputation, with an average annual rainfall of around 37 inches (94 cm). San Francisco receives less rainfall, with an average of around 20 inches (51 cm) per year. However, San Francisco's rainfall is more concentrated during the winter months, while Seattle's rainfall i
s more evenly distributed throughout the year.

......
-- Call generate using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
        prompt       =>  'How does the cost of living compare between New York and Los Angeles?',
        profile_name =>  'GENAI',
        action       =>  'CHAT',
        params       =>  '{"conversation_id":"30C9DB6E-EA4E-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
The cost of living in New York and Los Angeles is relatively high compared to other cities in the United States. However, there are some differences in the cost of living between the two cities. Here's a comparison of the cost of living in New York and Los Angeles:
1. Housing: The cost of housing is significantly higher in New York than in Los Angeles. The median home price in New York is around $999,000, while in Los Angeles it's around $849,000. Rent is also higher in New York, with the average rent for a one-bedroom apartment being around $3,000 per month, compared to around $2,400 per month in Los Angeles.
2. Food: The cost of food is relatively similar in both cities, with some variation in the cost of certain types of cuisine. However, eating out in New York can be more expensive, with the average cost of a meal at a mid-range restaurant being around $15-20 per person, compared to around $12-18 per person in Los Angeles.

......
-- Call generate using the first conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
        prompt       =>  'Explain the difference again in one paragraph only.',
        profile_name =>  'GENAI',
        action       =>  'CHAT',
        params       =>  '{"conversation_id":"30C9DB6E-EA4D-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco have different weather patterns despite both experiencing a mild oceanic climate. San Francisco tends to be slightly warmer, with average temperatures ranging from 45?F to 67?F, and receives less rainfall, around 20 inches per year, mostly during winter. In contrast, Seattle is cooler, with temperatures ranging from 38?F to 64?F, and rainier, with around 37 inches of rainfall per year, distributed throughout the year. San Francisco is also known for its fog, particularly during summer, and receives more sunshine, around 160 sunny days per year, although it's often filtered through the fog. Overall, San Francisco's weather is warmer and sunnier, with more pronounced seasonal variations, while Seattle's is cooler and rainier, with more consistent temperatures throughout the year.
-- Call generate using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
        prompt       =>  'Explain the difference again in one paragraph only.',
        profile_name =>  'GENAI',
        action       =>  'CHAT',
        params       =>  '{"conversation_id":"30C9DB6E-EA4E-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
The cost of living in New York is approximately 20-30% higher than in Los Angeles, mainly due to the higher cost of housing and transportation. New York has a median home price of around $999,000 and average rent of $3,000 per month for a one-bedroom apartment, compared to Los Angeles' median home price of $849,000 and average rent of $2,400 per month. While the cost of food and utilities is relatively similar in both cities, the cost of transportation is higher in Los Angeles due to its car-centric culture, but the cost of public transportation is higher in New York. Overall, the total monthly expenses for a single person in New York can range from $4,600, compared to around $4,050 in Los Angeles, making New York the more expensive city to live in.

您可以在不指定對話的情況下呼叫 DBMS_CLOUD_AI.GENERATE 函數;不過,在這種情況下,不應預期有意義的回應。

-- Ask SELECT AI using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
        prompt       =>  'Explain the difference again in one paragraph only.',
        profile_name =>  'GENAI',
        action       =>  'CHAT') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
There is no previous explanation to draw from, as this is the beginning of our conversation. If you would like to ask a question or provide a topic, I would be happy to explain the differences related to it in one paragraph.

範例:透過 DBMS_CLOUD_AI 檢視驗證對話

您可以查詢 DBMS_CLOUD_AI 對話檢視以複查對話和提示詳細資訊。請參閱 DBMS_CLOUD_AI 檢視以瞭解詳細資訊。

注意:具有 DBA_ 前置碼的「檢視」僅適用於具有管理員權限 (ADMIN) 的使用者。

SELECT conversation_id, conversation_title, description FROM dba_cloud_ai_conversations;
CONVERSATION_ID
------------------------------------
CONVERSATION_TITLE
----------------------------------------------------------------------------------------------------
DESCRIPTION
--------------------------------------------------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
Seattle vs San Francisco Weather
The conversation discusses the comparison of weather patterns between Seattle and San Francisco, focusing on the differences in temperature, rainfall, fog, sunshine, and seasonal variation between the two cities.

30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
NY vs LA Cost Comparison
The conversation discusses and compares the cost of living in New York and Los Angeles, covering housing, food, transportation, utilities, and taxes to provide an overall view of the expenses in both cities.
SELECT conversation_id, count(*) FROM dba_cloud_ai_conversation_prompts
     GROUP BY conversation_id;
CONVERSATION_ID                COUNT(*)
------------------------------------ ----------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92          2
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92          2

範例:更新對話詳細資料

您可以使用 DBMS_CLOUD_AI.UPDATE_CONVERSATION 程序來更新對話的 titledescriptionretention_days。您可以查詢 DBMS_CLOUD_AI 對話檢視來驗證更新。

-- Update the second conversation's title, description and retention_days
EXEC DBMS_CLOUD_AI.update_conversation(conversation_id => '30C9DB6E-EA4E-AFBA-E063-9C6D46644B92',
											attributes => '{"retention_days":20,
														"description":"This a description",
														"title":"a title",
														"conversation_length":20}');
-- Verify the information for the second conversation
SELECT conversation_title, description, retention_days
FROM dba_cloud_ai_conversations
WHERE conversation_id = '30C9DB6E-EA4E-AFBA-E063-9C6D46644B92';
CONVERSATION_TITLE         DESCRIPTION                          RETENTION_DAYS         LENGTH
-------------------------- ------------------------------------ -------------- --------------
a title                    This a description                   20                         20

範例:刪除提示

您可以從對話中刪除個別提示,並透過查詢 DBMS_CLOUD_AI 對話檢視來驗證修改。

-- Find the latest prompt for first conversation
SELECT conversation_prompt_id FROM dba_cloud_ai_conversation_prompts
     WHERE conversation_id = '30C9DB6E-EA4D-AFBA-E063-9C6D46644B92'
     ORDER BY created DESC
     FETCH FIRST ROW ONLY;
CONVERSATION_PROMPT_ID
------------------------------------
30C9DB6E-EA61-AFBA-E063-9C6D46644B92
-- Delete the prompt
EXEC DBMS_CLOUD_AI.DELETE_CONVERSATION_PROMPT('30C9DB6E-EA61-AFBA-E063-9C6D46644B92');
-- Verify if the prompt is deleted
SELECT conversation_prompt_id FROM dba_cloud_ai_conversation_prompts
WHERE conversation_id = '30C9DB6E-EA4D-AFBA-E063-9C6D46644B92';
-- Only one prompt now
CONVERSATION_PROMPT_ID
------------------------------------
30C9DB6E-EA5A-AFBA-E063-9C6D46644B92

範例:刪除對話

您可以刪除整個對話,這也會移除與其關聯的所有提示。

-- Delete the first conversation
EXEC DBMS_CLOUD_AI.DROP_CONVERSATION('30C9DB6E-EA4D-AFBA-E063-9C6D46644B92');

-- Verify if the conversation and its prompts are removed
SELECT conversation_id FROM dba_cloud_ai_conversations;
-- We only have the second conversation now
CONVERSATION_ID
------------------------------------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
SELECT conversation_id, count(*) FROM dba_cloud_ai_conversation_prompts GROUP BY conversation_id;
-- We only have prompts in the second conversation
CONVERSATION_ID                COUNT(*)
------------------------------------ ----------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92          2

範例:選取 AI 意見回饋

這些範例示範如何使用 DBMS_CLOUD_AI.FEEDBACK 程序和不同的案例來提供意見,以改善後續的 SQL 查詢產生。

注意:即使先前未執行提示,您仍可以提供「選取 AI SQL」提示的意見。在提交意見回饋之前,選取 AI 不需要在查詢中使用 SQL 提示;您可以隨時提供任何有效提示的意見回饋。

範例:提供負面意見

下列範例示範使用 feedback_type 作為 negative 並提供 SQL 查詢,為產生的 SQL 提供更正作為回饋 (負反饋)。

您可以呼叫含有提示之 sql_text 參數的 DBMS_CLOUD_AI.FEEDBACK 程序,將意見回饋新增至名為 OCI_FEEDBACK1 的 AI 設定檔。請參閱意見反應程序以瞭解屬性。然後,從連結至該特定 SQL 查詢的 <profile_name>_FEEDBACK_VECINDEX$VECTAB 表格擷取 contentattributes 資料欄。當您第一次使用意見回饋功能時,選取 AI 會自動建立此向量表。如需詳細資訊,請參閱意見回饋的向量索引

SQL> select ai showsql how many movies;
RESPONSE
------------------------------------------------------------------------
SELECT COUNT(m."MOVIE_ID") AS "Number of Movies" FROM "ADB_USER"."MOVIES" m
exec DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1', sql_text=> 'select ai showsql how many movies', feedback_type=> 'negative', response=>'SELECT SUM(1) FROM "ADB_USER"."MOVIES"');
select CONTENT, ATTRIBUTES from OCI_FEEDBACK1_FEEDBACK_VECINDEX$VECTAB where JSON_VALUE(attributes, '$.sql_text') = 'select ai showsql how many movies';
CONTENT
----------------------------------------------------------------------------------------------------
how many movies
ATTRIBUTES
----------------------------------------------------------------------------------------------------

{"response":"SELECT SUM(1) FROM "ADB_USER"."MOVIES"","feedback_type":"negative","sql_id":null,"sql_text":"select ai showsql how many movies","feedback_content":null}

範例:提供正面意見

下列範例示範核准您同意並使用 feedback_type 作為 positive ,並確認產生的 SQL (正反饋)。

在此範例中,查詢會從指定提示的 v$mapped_sql 檢視擷取 sql_id。請參閱 V_MAPPED_SQL 以取得詳細資訊。

您可以使用 sql_id 參數呼叫 DBMS_CLOUD_AI.FEEDBACK 程序,將您的意見新增至名為 OCI_FEEDBACK1 的 AI 設定檔。然後,從連結至該特定 SQL 查詢的 <profile_name>_FEEDBACK_VECINDEX$VECTAB 表格擷取 contentattributes 資料欄。當您第一次使用意見回饋功能時,選取 AI 會自動建立此向量表。如需詳細資訊,請參閱意見回饋的向量索引

select ai showsql how many distinct movie genres?;
RESPONSE
-----------------------------------------------------------------------------------------
SELECT COUNT(DISTINCT g."GENRE_NAME") AS "Number of Movie Genres" FROM "ADB_USER"."GENRES" g
SELECT sql_id FROM v$mapped_sql WHERE sql_text = 'select ai showsql how many distinct movie genres?';
SQL_ID
-------------
852w8u83gktc1
exec DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1', sql_id=> '852w8u83gktc1', feedback_type=>'positive', operation=>'add');
SELECT content, attributes FROM OCI_FEEDBACK1_FEEDBACK_VECINDEX$VECTAB WHERE JSON_VALUE(attributes, '$.sql_id') ='852w8u83gktc1';
CONTENT
----------------------------------------------------------------------------------------------------
how many distinct movie genres?
ATTRIBUTES
----------------------------------------------------------------------------------------------------
{"response":"SELECT COUNT(DISTINCT g."GENRE_NAME") AS "Number of Movie Genres" FROM "ADB_USER"."GENRES" g","feedback_type":"positive","sql_id":"852w8u83gktc1","sql_text":"select ai showsql how many distinct movie genres?","feedback_content":null}

範例:提供沒有先前用途的意見

即使先前未使用過提示,您仍可以提供 SQL 提示的意見回饋。舉例而言:

BEGIN
  DBMS_CLOUD_AI.FEEDBACK(
    profile_name=>'AI_PROFILE',
    sql_text=>'select ai runsql how many products named PAD', -- Prior usage not required
    feedback_type=>'negative',
    response=>'SELECT COUNT(*) AS "Num" FROM "PRODUCTS"."CATG" o WHERE UPPER(o."NAME") LIKE ''%PAD%''',
    feedback_content=>'Use LIKE instead of ='
  );
END;
/

在此情況下,會提交提示 select ai runsql how many products named PAD 的意見,而不需要事先使用提示。

範例:新增或刪除產生之 SQL 的意見

下列範例示範藉由指定 DBMS_CLOUD_AI.FEEDBACK 程序參數來新增或刪除所產生 SQL 的意見回饋。此範例示範使用 sql_idsql_text 以及其他參數。

注意:對於每個 sql_id,Select AI 僅允許單一意見項目。如果您對相同的 sql_id 提供其他意見,Select AI 會將上一個項目取代為新的項目。

請參閱意見反應程序,瞭解參數的詳細資訊。

EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
                                   sql_id=> '852w8u83gktc1',
                                   feedback_type=>'positive',
                                   operation=>'add');
EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
                                   sql_text=> 'select ai showsql how many movies',
                                   feedback_type=> 'negative',
                                   response=>'SELECT SUM(1) FROM "ADB_USER"."MOVIES"',
                                   feedback_content=>'Use SUM instead of COUNT');
EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
                                   sql_id=> '852w8u83gktc1',
                                   operation=>'delete');

範例:搭配上一個 AI SQL 使用意見回饋動作以提供負面意見回饋

此範例示範如何使用 feedback 動作,透過建議使用自然語言進行修改來改善產生的 SQL。

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
    profile_name=>'OCI_FEEDBACK1',
    attributes=>'{"provider": "oci",
      "credential_name": "GENAI_CRED",
      "oci_compartment_id": "ocid1.compartment.oc1..aaaa...",
      "object_list": [{"owner": "ADB_USER", "name": "users"},
                      {"owner": "ADB_USER", "name": "movies"},
                      {"owner": "ADB_USER", "name": "genres"},
                      {"owner": "ADB_USER", "name": "watch_history"},
                      {"owner": "ADB_USER", "name": "movie_genres"},
                      {"owner": "ADB_USER", "name": "employees1"},
                      {"owner": "ADB_USER", "name": "employees2"}
                        ]
      }');
END;
/

EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_FEEDBACK1');
select ai showsql rank movie duration;
RESPONSE
-------------------------------------------------------------------------------
SELECT "DURATION" AS "Movie Duration" FROM "ADB_USER"."MOVIES" ORDER BY "DURATION"
select ai feedback use ascending sorting;
RESPONSE
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "rank movie duration" is successfully refined. The refined SQL query as following:
SELECT m."DURATION" AS "Movie Duration" FROM "ADB_USER."MOVIES" m ORDER BY m."DURATION" ASC
select ai showsql rank the movie duration;
RESPONSE
-----------------------------------------------------------------------------------------
SELECT m."DURATION" AS "Movie Duration" FROM "ADB_USER."MOVIES" m ORDER BY m."DURATION" ASC

範例:搭配上一個 AI SQL 使用意見回饋動作來提供正面意見回饋

此範例示範如何使用 feedback 動作來接受使用自然語言產生的 SQL。

--Positive feedback

select ai showsql which movies are comedy?;
RESPONSE
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT DISTINCT m."TITLE" AS "Movie Title" FROM "ADB_USER"."MOVIES" m INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID" INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID" WHERE g."GENRE_NAME" = 'comedy'
select ai feedback this is correct;
RESPONSE
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Thank you for your positive feedback. The SQL query for prompt "which movies are comedy?" is correctly implemented and delivering the expected results. It will be referenced for future optimizations and improvements.
Select AI Feedback Action Referring SQL_ID

範例:使用具有 SQL_ID 的意見回饋動作來提供意見回饋

此範例示範使用 SQL_ID 搭配 feedback 動作,為特定產生的 SQL 查詢提供意見。您可以查詢 v$MAPPED_SQL 表格來取得 SQL_ID

-- Query mentioned with SQL_ID

select ai showsql how many movies are in each genre;
RESPONSE
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT g."GENRE_NAME" AS "Genre Name", COUNT(m."MOVIE_ID") AS "Number of Movies" FROM "ADB_USER"."MOVIES" m INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID" INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID" GROUP BY g."GENRE_NAME"
select sql_id from v$cloud_ai_sql where sql_text = 'select ai showsql how many movies are in each genre';
SQL_ID
-------------
8azkwc0hr87ga
select ai feedback for query with sql_id = '8azkwc0hr87ga', rank in descending sorting;
RESPONSE
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "how many movies are in each genre" is successfully refined. The refined SQL query as following:
SELECT g."GENRE_NAME" AS "Genre Name", COUNT(m."MOVIE_ID") AS "Number of Movies"
FROM "ADB_USER"."MOVIES" m
INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID"
INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID"
GROUP BY g."GENRE_NAME"
ORDER BY COUNT(m."MOVIE_ID") DESC

範例:搭配查詢文字使用意見動作

此範例顯示特定 Select AI 查詢的 feedback 動作,其中包含引號中的 Select AI 提示,後面接著您的意見回饋。

-Query mentioned with SQL_TEXT

select ai showsql how many watch history in total;
RESPONSE
----------------------------------------------------------------------------------
SELECT COUNT(w."WATCH_ID") AS "Total Watch History" FROM "ADB_USER"."WATCH_HISTORY" w
select ai feedback for query "select ai showsql how many watch history in total", name the column as total_watch;
RESPONSE
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "how many watch history in total" is successfully refined. The refined SQL query as following:
SELECT COUNT(w."WATCH_ID") AS "total_watch" FROM "ADB_USER"."WATCH_HISTORY" w

範例:為特性圖表選取 AI

此範例顯示如何使用 DBMS_CLOUD_AI.GENERATE 程序和自然語言提示來產生查詢圖表資料的 PGQ 圖表查詢。

範例:在 AI 設定檔中指定多個圖表

此範例顯示如何在 AI 設定檔中定義多個特性圖表,包括範例查詢及其輸出。

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
      profile_name =>'OPENAI',
      attributes   =>'{"provider": "openai",
        "model": "gpt-4o",
        "credential_name": "OPENAI_CRED",
        "object_list": [{"owner": "ADB_USER", "name": "LDBC_GRAPH"},
                        {"owner": "ADB_USER", "name": "G"}]
       }');
END;
/

SQL> EXEC DBMS_CLOUD_AI.SET_PROFILE(profile_name => 'OPENAI');
select ai who bought a dress;
CUSTOMER_N
----------
Kate

1 row selected.

範例:特性圖表的範例提示

這些範例顯示如何使用指定提示的 showsql 動作來建立範例資料及顯示產生的 SQL。

範例:建立特性圖表表格

下列範例會建立範例表格與特性圖表。

CREATE TABLE Person
(
    id         NUMBER PRIMARY KEY,
    firstName  VARCHAR2(20 CHAR),
    lastName   VARCHAR2(20 CHAR),
    age        NUMBER,
    jsonProp   VARCHAR2(40 CHAR)
);

CREATE TABLE Post
(
    id         NUMBER PRIMARY KEY,
    content    VARCHAR2(20 CHAR)
);

CREATE TABLE personLikesPost
(
    idPerson NUMBER REFERENCES Person (id),
    idPost   NUMBER REFERENCES Post (id)
);

CREATE TABLE personKnowsPerson
(
    idPerson1 NUMBER REFERENCES Person (id),
    idPerson2 NUMBER REFERENCES Person (id)
);

CREATE PROPERTY GRAPH person_graph
  VERTEX TABLES (
    Person KEY (id) LABEL Person
      PROPERTIES (firstName, lastName, age, jsonProp),
    Post KEY (id) LABEL Post
      PROPERTIES(content)
  )
  EDGE TABLES (
    personLikesPost
      KEY(idPerson, idPost)
      SOURCE KEY (idPerson) REFERENCES Person (id)
      DESTINATION KEY (idPost) REFERENCES POST (id)
      LABEL Likes NO PROPERTIES,
    personKnowsPerson
      KEY(idPerson1, idPerson2)
      SOURCE KEY (idPerson1) REFERENCES Person (id)
      DESTINATION KEY (idPerson2) REFERENCES Person (id)
      LABEL Knows NO PROPERTIES
  );

insert into Person values (1, 'John', 'Doe',23, '{"key1":"value1","key2":"value2"}');
insert into Person values (2, 'Scott', 'Tiger', 25, '{"key1":"value3","key2":"value4"}');
insert into Person values (3, 'Max', 'Power', 27, '{"key1":"value5","key2":"value6"}');
insert into Person values (4, 'Jane', 'Doe', 22, '{"key1":"value7","key2":"value8"}');
insert into Person (id, Firstname, age) values (5, 'Hans', 23);
insert into Person (id, Firstname, age) values (6, 'Franz', 24);

INSERT INTO Post VALUES (10, 'Lorem ipsum...');
INSERT INTO Post VALUES (11, 'Nulla facilisi...');
INSERT INTO Post VALUES (12, 'Vestibulum eget ..');
INSERT INTO Post VALUES (13, 'Sed fermentum...');
INSERT INTO Post VALUES (14, 'Fusce at ...');
INSERT INTO Post VALUES (15, 'Pellentesque sit ...');
INSERT INTO Post VALUES (16, 'Integer...');
INSERT INTO Post VALUES (17, 'Curabitur luctus ...');
INSERT INTO Post VALUES (18, 'Nam in ...');
INSERT INTO Post VALUES (19, 'Etiam ac ...');

insert into personKnowsPerson values (1, 2);
insert into personKnowsPerson values (2, 3);
insert into personKnowsPerson values (3, 4);
insert into personKnowsPerson values (4, 5);
insert into personKnowsPerson values (5, 6);
insert into personKnowsPerson values (6, 2);
insert into personKnowsPerson values (5, 3);

INSERT INTO personLikesPost VALUES (1, 10);
INSERT INTO personLikesPost VALUES (1, 11);
INSERT INTO personLikesPost VALUES (1, 12);
INSERT INTO personLikesPost VALUES (2, 10);
INSERT INTO personLikesPost VALUES (2, 13);
INSERT INTO personLikesPost VALUES (2, 14);
INSERT INTO personLikesPost VALUES (3, 11);
INSERT INTO personLikesPost VALUES (3, 15);
INSERT INTO personLikesPost VALUES (3, 16);
INSERT INTO personLikesPost VALUES (4, 12);
INSERT INTO personLikesPost VALUES (4, 17);
INSERT INTO personLikesPost VALUES (4, 18);
INSERT INTO personLikesPost VALUES (5, 13);
INSERT INTO personLikesPost VALUES (5, 14);
INSERT INTO personLikesPost VALUES (5, 19);
INSERT INTO personLikesPost VALUES (6, 15);
INSERT INTO personLikesPost VALUES (6, 16);
INSERT INTO personLikesPost VALUES (6, 17);
INSERT INTO personLikesPost VALUES (1, 18);
INSERT INTO personLikesPost VALUES (2, 19);

commit;

範例:符合不含標籤的頂點

提示:Find all the people IDs

SELECT person_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (v IS "PERSON")
    COLUMNS (VERTEX_ID(v) AS person_id))

範例:不使用標籤比對邊緣

提示:Find all the edge IDs

SELECT edge_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (v1) -[e]-> (v2)
    COLUMNS (EDGE_ID(e) AS edge_id))

範例:邊緣與標籤相符

提示:Find all the knows relationship IDs

SELECT knows_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p1 IS "PERSON") -[e IS "KNOWS"]-> (p2 IS "PERSON")
    COLUMNS (EDGE_ID(e) AS knows_id))

範例:比對包含一或多個躍點的路徑樣式

提示:List all people who know someone who liked the post 'Sed fermentum...'

SELECT person_id, person_firstname, person_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p1 IS "PERSON") -[e1 IS "KNOWS"]-> (p2 IS "PERSON") -[e2 IS "LIKES"]-> (post IS "POST")
    WHERE UPPER(post."CONTENT") = UPPER('Sed fermentum...')
    COLUMNS (VERTEX_ID(p1) AS person_id, p1."FIRSTNAME" AS person_firstname, p1."LASTNAME" AS person_lastname))

範例:存取 Vertex 和 Edge 特性

提示:Find first name and last name of all people

SELECT first_name, last_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p IS "PERSON")
    COLUMNS (p."FIRSTNAME" AS first_name, p."LASTNAME" AS last_name))

範例:篩選資料

提示:Find post contents liked by John Doe

SELECT post_content
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p IS "PERSON") -[e IS "LIKES"]-> (post IS "POST")
    WHERE UPPER(p."FIRSTNAME") = UPPER('John') AND UPPER(p."LASTNAME") = UPPER('Doe')
    COLUMNS (post."CONTENT" AS post_content))

範例:函數和表示式

提示:Show all people (full name) and display their key1 value from jsonProp property

SELECT person_fullname, json_key1
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p IS "PERSON")
    COLUMNS (
	(p."FIRSTNAME" || ' ' || p."LASTNAME") AS person_fullname,
	JSON_QUERY(p."JSONPROP", '$.key1') AS json_key1
    )
)

範例:排序資料

提示:Find friends of Scott Tiger ordered by their last name

SELECT friend_firstname, friend_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p IS "PERSON") -[e IS "KNOWS"]-> (f IS "PERSON")
    WHERE UPPER(p."FIRSTNAME") = UPPER('Scott') AND UPPER(p."LASTNAME") = UPPER('Tiger')
    COLUMNS (f."FIRSTNAME" AS friend_firstname, f."LASTNAME" AS friend_lastname)
)
ORDER BY friend_lastname

範例:資料列限制

提示:Find all people ordered by first name. Skip one result and return 2 results only

SELECT person_firstname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p IS "PERSON")
    COLUMNS (p."FIRSTNAME" AS person_firstname))
ORDER BY person_firstname
OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLY

不支援的查詢

對於下列查詢,某些 LLM 會產生有效的 NL2SQL,但產生的 SQL 會使用 Oracle AI Database 26ai 尚未支援的功能。

範例:需要不符合特定樣式的查詢

提示:Find people that do not know Scott.

不支援 EXISTS 子查詢。

SELECT person_id, first_name, last_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (p1 IS "PERSON")
    WHERE NOT EXISTS (
	SELECT 1
	FROM GRAPH_TABLE("ADB_USER"."PERSONGRAPH"
	    MATCH (p2 IS "PERSON") -[e IS "PERSONKNOWSPERSON"]-> (p3 IS "PERSON"
)
	    WHERE p2."ID" = p1."ID" AND UPPER(p3."FIRSTNAME") = UPPER('Scott')
	    COLUMNS (1 AS dummy_value))
    )
    COLUMNS (p1."ID" AS person_id, p1."FIRSTNAME" AS first_name, p1."LASTNAME" A
S last_name))

範例:需要選擇性比對特定樣式的查詢

提示:Show all people and how many posts they have liked (show people even if they have not liked a post).

不支援 OPTIONAL 比對。

SELECT person_id, person_firstname, person_lastname, liked_post_ids
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p is "PERSON") OPTIONAL MATCH (p) -[l is "PERSONLIKESPOST"]-> (post is "POST")
COLUMNS(
    VERTEX_ID(p) as person_id,
    p."FIRSTNAME" as person_firstname,
    p."LASTNAME" as person_lastname,
    JSON_ARRAYAGG(VERTEX_ID(post)) as liked_post_ids
))

範例:未繫結的遞迴路徑樣式

提示:Find all people that Scott can reach.

不支援使用未繫結數量詞的查詢。

SELECT person_id, person_firstname, person_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSONGRAPH"
    MATCH (src IS "PERSON") -[e IS "PERSONKNOWSPERSON"]->* (dst IS "PERSON")
    WHERE src."FIRSTNAME" = 'Scott'
    COLUMNS (
	VERTEX_ID(dst) AS person_id,
	dst."FIRSTNAME" AS person_firstname,
	dst."LASTNAME" AS person_lastname
    )
)

間歇性查詢

在翻譯需要多個 GRAPH_TABLE 運算子的查詢時,已顯示 LLM 奮鬥。以下為範例:

提示:Show people who have liked all the same posts as Hans

SELECT person_id, person_name
FROM GRAPH_TABLE("PERSON_GRAPH"
  MATCH (hans is "PERSON") -[likes_hans is "PERSONLIKESPOST"]-> (post is "POST"),
	(other_person is "PERSON") -[likes_other is "PERSONLIKESPOST"]-> (post)
  WHERE hans."FIRSTNAME" = 'Hans'
  COLUMNS (VERTEX_ID(other_person) as person_id, other_person."FIRSTNAME" AS person_name)
)
WHERE NOT EXISTS (
  SELECT 1
  FROM GRAPH_TABLE("PERSONGRAPH"
    MATCH (hans is "PERSON") -[likes_hans is "PERSONLIKESPOST"]-> (post is "POST")
    WHERE hans."FIRSTNAME" = 'Hans'
    COLUMNS (VERTEX_ID(post) as post_id)
  ) hans_posts
  LEFT JOIN GRAPH_TABLE("PERSONGRAPH"
    MATCH (other_person is "PERSON") -[likes_other is "PERSONLIKESPOST"]-> (post
 is "POST")
    COLUMNS (VERTEX_ID(post) as post_id)
  ) other_posts
  ON hans_posts.post_id = other_posts.post_id
  WHERE other_posts.post_id IS NULL
)

範例:比對遞迴路徑樣式與定義的界限。

提示:Find all names of the people that can be reached in a 1 to 3 edge path

SELECT person_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (start_person IS "PERSON") -[e IS "KNOWS"]->{1,3} (end_person IS "PERSON")
    COLUMNS (end_person."FIRSTNAME" AS person_name))

範例:篩選遞迴路徑中節點的資料

提示:Find all names of the people that can be reached in a 1 to 3 edge path where each person is younger than the next one

SELECT person_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
    MATCH (start_person IS "PERSON") ((v1 IS "PERSON") -[e IS "KNOWS"]-> (v2 IS"PERSON") WHERE v1."AGE" < v2."AGE"){1,3} (end_person IS "PERSON")
    COLUMNS (end_person."FIRSTNAME" AS person_name))

範例:分組與聚總

LLM 通常難以翻譯需要分組和聚總的查詢。常見的錯誤是將聚總放在 COLUMNS 子句而非 SELECT 子句中。

提示:Find the average number of posts liked by all the users

SELECT AVG(COUNT(post)) AS average_liked_count
FROM GRAPH_TABLE("PERSON_GRAPH"
MATCH (p IS "PERSON") -[e IS "PERSONLIKESPOST"]-> (post IS "POST")
COLUMNS (VERTEX_ID(p) AS person, VERTEX_ID(post) AS post))
GROUP BY person;

範例:改善 SQL 查詢產生

這些範例示範了資料庫表格和資料欄中的註解、註解、外來索引鍵以及參照完整性限制條件如何改善從自然語言提示產生 SQL 查詢。

範例:使用表格和資料欄註解改善 SQL 產生

如果您的資料庫表格中有表格和資料欄註解,請啟用 DBMS_CLOUD_AI.CREATE_PROFILE 函數中的 "comments":"true" 參數,以擷取表格層次和資料欄層次註解。註解會新增至 LLM 的中繼資料,以產生更佳的 SQL。

-- Adding comments to table 1, table 2, and table 3. Table 1 has 3 columns, table 2 has 7 columns, table 3 has 2 columns.

-- TABLE1
COMMENT ON TABLE table1 IS 'Contains movies, movie titles and the year it was released';
COMMENT ON COLUMN table1.c1 IS 'movie ids. Use this column to join to other tables';
COMMENT ON COLUMN table1.c2 IS 'movie titles';
COMMENT ON COLUMN table1.c3 IS 'year the movie was released';
-- TABLE2
COMMENT ON TABLE table2 IS 'transactions for movie views - also known as streams';
COMMENT ON COLUMN table2.c1 IS 'day the movie was streamed';
COMMENT ON COLUMN table2.c2 IS 'genre ids. Use this column to join to other tables';
COMMENT ON COLUMN table2.c3 IS 'movie ids. Use this column to join to other tables';
COMMENT ON COLUMN table2.c4 IS 'customer ids. Use this column to join to other tables';
COMMENT ON COLUMN table2.c5 IS 'device used to stream, watch or view the movie';
COMMENT ON COLUMN table2.c6 IS 'sales from the movie';
COMMENT ON COLUMN table2.c7 IS 'number of views, watched, streamed';

-- TABLE3
COMMENT ON TABLE table3 IS 'Contains the genres';
COMMENT ON COLUMN table3.c1 IS 'genre id. use this column to join to other tables';
COMMENT ON COLUMN table3.c2 IS 'name of the genre';


BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
    profile_name => 'myprofile',
    attributes =>
        '{"provider": "azure",
          "azure_resource_name": "my_resource",
          "azure_deployment_name": "my_deployment",
          "credential_name": "my_credential",
          "comments":"true",
          "object_list": [
            {"owner": "moviestream", "name": "table1"},
            {"owner": "moviestream", "name": "table2"},
            {"owner": " moviestream", "name": "table3"}
          ]
          }'
    );

    DBMS_CLOUD_AI.SET_PROFILE(
        profile_name => 'myprofile'
    );

END;
/
--Prompts
select ai what are our total views;
RESPONSE
-------------------------------------------------
TOTAL_VIEWS
-----------
   97890562
select ai showsql what are our total views;
RESPONSE
-------------------------------------------------------------------------
SELECT SUM(QUANTITY_SOLD) AS total_views
FROM "moviestream"."table"
select ai what are our total views broken out by device;
DEVICE                     TOTAL_VIEWS
-------------------------- -----------
mac                           14719238
iphone                        20793516
ipad                          15890590
pc                            14715169
galaxy                        10587343
pixel                         10593551
lenovo                         5294239
fire                           5296916

8 rows selected.
select ai showsql what are our total views broken out by device;
RESPONSE
---------------------------------------------------------------------------------------
SELECT DEVICE, COUNT(*) AS TOTAL_VIEWS
FROM "moviestream"."table"
GROUP BY DEVICE

範例:使用表格和資料欄註解改善 SQL 查詢產生

此範例示範在 Oracle Database 23ai 中適用的 Select AI 中註解整合。註釋會新增至傳送至 LLM 的中繼資料。

如果您的綱要中有含有註解的表格,請在 DBMS_CLOUD_AI.CREATE_PROFILE 函數中啟用 "annotations":"true",指示 Select AI 將註解新增至描述資料。

--
-- Annotations
--

CREATE TABLE emp2 (
    empno NUMBER,
    ename VARCHAR2(50) ANNOTATIONS (display 'lastname'),
    salary NUMBER ANNOTATIONS ("person_salary", "column_hidden"),
    deptno NUMBER ANNOTATIONS (display 'department')
)ANNOTATIONS (requires_audit 'yes', version '1.0', owner 'HR Organization');
BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
   profile_name => 'GOOGLE_ANNOTATIONS',
   attributes   => '{"provider": "google",
      "credential_name": "GOOGLE_CRED",
      "object_list": [{"owner": "ADB_USER", "name": "emp2"}],
      "annotations" : "true"
      }');
END;
/
EXEC DBMS_CLOUD_AI.SET_PROFILE('GOOGLE_ANNOTATIONS');

範例:使用外來索引鍵和參考索引鍵限制條件改善 SQL 查詢產生

此範例示範 LLM 在 LLM 的中繼資料中擷取外來索引鍵和參考索引鍵限制條件,以產生準確的 JOIN 條件。外來索引鍵和參考索引鍵限制條件提供表格與 LLM 之間的結構化關係資料。

DBMS_CLOUD_AI.CREATE_PROFILE 函數中啟用 "constraints":"true",讓 Select AI 擷取外來索引鍵與參考索引鍵。

--
-- Referential Constraints
--
CREATE TABLE dept_test (
    deptno NUMBER PRIMARY KEY,
    dname VARCHAR2(50)
);
CREATE TABLE emp3 (
    empno NUMBER PRIMARY KEY,
    ename VARCHAR2(50),
    salary NUMBER,
    deptno NUMBER,
    CONSTRAINT emp_dept_fk FOREIGN KEY (deptno) REFERENCES dept_test(deptno)
);
BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
    profile_name=>'GOOGLE_CONSTRAINTS',
    attribues   =>'{"provider": "google",
      "credential_name": "GOOGLE_CRED",
      "object_list": [{"owner": "ADB_USER", "name": "dept_test"},
                      {"owner": "ADB_USER", "name": "emp3"}],
      "constraints" : "true"
      }');
END;
/
EXEC DBMS_CLOUD_AI.SET_PROFILE('GOOGLE_CONSTRAINTS');

範例:自動偵測相關表格描述資料

這些範例顯示 Select AI 如何自動偵測相關表格,並僅針對與 Oracle Database 23ai 中查詢相關的特定表格傳送中繼資料。若要啟用此功能,請將 object_list_mode 設為 automated 。這會自動建立名為 <profile_name>_OBJECT_LIST_VECINDEX 的向量索引。向量索引是以預設屬性和值 (例如 refresh_ratesimilarity_thresholdmatch_limit) 初始化。您可以透過 DBMS_CLOUD_AI.UPDATE_VECTOR_INDEX 修改部分屬性。請參閱 UPDATE_VECTOR_INDEX 程序以瞭解詳細資訊。

一個設定檔設定為使用 object_list 來指定綱要或綱要中的物件,而另一個設定檔則未指定 object_list。不過,預期會有相同的 SQL 建構。

請參閱 Select AI 的先決條件,以提供對 DBMS_CLOUD_AI 套件的存取,並提供 AI 提供者的網路存取。

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
    profile_name=>'OCI_AUTO',
    attributes=>'{"provider": "oci",
      "credential_name": "GENAI_CRED",
      "object_list": [{"owner": "SH"}],
      "oci_compartment_id": "ocid1.compartment.oc1..aaaa...",
      "model" : "meta.llama-3.3-70b-instruct"
      }');
END;
/
EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_AUTO');
select ai showsql how many customers in San Francisco are married;
RESPONSE
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT COUNT(DISTINCT c."CUST_ID") AS "NUMBER_OF_CUSTOMERS"
FROM "SH"."CUSTOMERS" c
WHERE UPPER(c."CUST_CITY") = UPPER('San Francisco')
AND UPPER(c."CUST_MARITAL_STATUS") = UPPER('married')

下列範例會在不使用 object_list 的情況下比較相同的案例。當您未指定 object_list 時,「選取 AI」會自動選擇目前綱要可用的所有物件。

BEGIN
  DBMS_CLOUD_AI.CREATE_PROFILE(
    profile_name=>'OCI_AUTO1',
    attributes=>'{"provider": "oci",
      "credential_name": "GENAI_CRED",
      "oci_compartment_id": "ocid1.compartment.oc1..aaaa...",
      "object_list_mode": "automated",
      "model" : "meta.llama-3.3-70b-instruct"
      }');
END;
/
EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_AUTO1');
select ai showsql how many customers in San Francisco are married?;
RESPONSE
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT COUNT(c."CUST_ID") AS "Number_of_Customers"
FROM "SH"."CUSTOMERS" c
WHERE UPPER(c."CUST_CITY") = UPPER('San Francisco')
AND UPPER(c."CUST_MARITAL_STATUS") = UPPER('Married')

範例:選取 AI 摘要

這些範例顯示如何使用 summarize 動作和 DBMS_CLOUD_AI.SUMMARIZE 函數。此外,使用函數自訂內容的摘要產生。

範例:在 SQL 命令行使用彙總動作

下列範例使用 SUMMARIZE 作為 Select AI 動作。在 SQL 命令行中使用 SELECT AI SUMMARIZE <TEXT> 來產生輸入文字的摘要。

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.

提示:在 SQL*Plus 中,會將單引號 (') 視為字串分界字元。如果您的文字包含單引號,請將引號加倍 ('''),或使用 q'[]' 引號機制將文字括住。如果文字包含空的雙引號 (""),請使用 q'[]' 機制將文字括住。舉例而言:

SELECT AI SUMMARIZE q'[this's a text]';

範例:使用 DBMS_CLOUD_AI.SUMMARIZE 程序來產生摘要

這些範例示範使用與 DBMS_CLOUD_AI.SUMMARIZE 程序不同的參數來產生摘要。

您可以使用 DBMS_CLOUD_AI.SUMMARIZE,將物件儲存連結指定為 location_uri 參數,並將雲端帳戶證明資料指定為 credential_name,從儲存在 OCI 物件儲存中的超過 3000 個文字產生摘要。

SELECT DBMS_CLOUD_AI.SUMMARIZE(
                location_uri => 'https://objectstorage.ca-toronto-1.oraclecloud.com/n/' ||
                    'namespace-string/b/bucketname/o/data_folder/' ||
                    'summary/test_4000_words.txt',
                credential_name => 'STORE_CRED',
                profile_name => 'GENAI')
from DUAL;

另一種從儲存在 OCI 物件儲存中的文字產生摘要的方式是使用 content 參數來呼叫 DBMS_CLOUD.GET_OBJECT 程序。

SELECT DBMS_CLOUD_AI.SUMMARIZE(
                content => TO_CLOB(
                            DBMS_CLOUD.GET_OBJECT(
                                credential_name => 'STORE_CRED',
                                location_uri => 'https://objectstorage.ca-toronto-1.oraclecloud.com/n/' ||
                    'namespace-string/b/bucketname/o/data_folder/' ||
                    'summary/test_4000_words.txt')),
                profile_name => 'GENAI'>)
from DUAL;

範例:透過指定使用者提示、字詞數下限及字詞數上限來產生摘要

下列範例會藉由指定下列參數,示範產生超過 3000 個文字文字的摘要:

SELECT DBMS_CLOUD_AI.SUMMARIZE(
                content => TO_CLOB(
                             DBMS_CLOUD.GET_OBJECT(
                             credential_name =>'STORE_CRED',
                             location_uri =>'https://objectstorage.ca-toronto-1.oraclecloud.com/n/' ||
                                   'namespace-string/b/bucketname/o/data_folder/' ||
                                   'summary/test_4000_words.txt')),
                profile_name    => 'GENAI',
                user_prompt     => 'The summary should start with ''The summary of ' ||
                                   'the article is: ''',
                params          => '{"min_words":50,"max_words":100}')
As response FROM dual;
RESPONSE
--------------------------------------------------------------------------------
The summary of the article is: The music streaming industry, led by Spotify, has revolutionized the way people consume music, with streaming accounting for about eighty per cent of the American recording industry's revenue. However, this shift has also raised concerns about the impact on artists, with many struggling to make a living due to low royalty rates and the dominance of playlists. The article explores the history of music streaming, from the early days of Napster to the current landscape, and how it has changed the way people listen to music. It also delves into the issues of autonomy and creativity in the music industry, with some artists feeling pressured to conform to certain styles or formulas to succeed on platforms like Spotify. The article cites examples of artists who have spoken out against the streaming economy, including Taylor Swift and Neil Young, and discusses the rise of alternative platforms like Bandcamp and Nina. Ultimately, the article suggests that the streaming economy has created a perverse vision for art, where music is valued for its ability to be ignored rather than appreciated, and that this has significant implications for the future of music and creativity. With the rise of AI-generated music and the increasing importance of data-driven decision making in the music industry, the article asks what the m
usic we're not hearing sounds like, and what the consequences of this shift will be for artists and listeners alike. The article concludes by highlighting the need for a more nuanced understanding of the music industry and the impact of streaming on artists and listeners, and for alternative models that prioritize creativity and autonomy over profit and convenience.

範例:透過指定使用者提示、字詞數上限及摘要樣式來產生摘要

下列範例示範藉由指定下列參數,產生超過 12000 個文字文字的摘要:

SELECT DBMS_CLOUD_AI.SUMMARIZE(
                location_uri    => 'https://objectstorage.ca-toronto-1.' ||
                                   'oraclecloud.com/n/namespace-string/b/' ||
                                   '/bucketname/o/data_folder/' ||
                                   'summary/dreams.txt',
                credential_name => 'STORE_CRED',
                profile_name    => 'GENAI',
                user_prompt     => 'The summary should start with ''The summary of ' ||
                                   'the article is: ''',
                params          => '{"max_words":100, "summary_style":"list"}')
As response FROM dual;
RESPONSE
--------------------------------------------------------------------------------
The summary of the article is:
- The book "Dreams" by Henri Bergson explores the concept of dreams and their significance in understanding human consciousness.
- Bergson argues that dreams are not just random thoughts, but rather a way for our unconscious mind to process and consolidate memories.
- He suggests that dreams are a result of the relaxation of our mental faculties, which allows our unconscious mind to freely associate and create new connections between memories.
- The book also discusses the role of sensations, such as visual and auditory impressions, in shaping our dreams.
- Bergson's theory of dreams is compared to other theories, including those of Freud and Jung, and is seen as a unique and insightful contribution to the field of psychology.
- The book concludes by highlighting the importance of studying dreams in order to gain a deeper understanding of human consciousness and the workings of the mind.

範例:產生工作簿摘要

此範例示範將 35.66 MiB 檔案當作輸入來產生摘要。DBMS_CLOUD_AI.SUMMARIZE 函數會使用反覆修正方法來處理區塊。如需詳細資訊,請參閱選取 AI 術語

SELECT DBMS_CLOUD_AI.SUMMARIZE(
       location_uri    => 'https://objectstorage.ca-toronto-1.oraclecloud.com/n/namespace-string/b/' ||
                          'bucketname/o/data_folder/summary/Descartes_An_Intellectual_Biography.pdf',
       credential_name => 'STORE_CRED',
       profile_name    => 'GENAI',
       params          =>  '{"chunk_processing_method":"iterative_refinement"}')
AS response FROM dual;
RESPONSE
--------------------------------------------------------------------------------
Stephen Gaukroger's intellectual biography of Rene Descartes provides a detailed  examination of the philosopher's crucial role in shaping modern thought, placing him within the cultural, religious, and scientific context of the early seventeenth century. It traces Descartes' intellectual journey from his education at La Fleche, where he rejected Aristotelian logic, to his influential interactions with figures like Isaac Beeckman, which shaped his mechanistic worldview evident in works like his hydrostatics manuscript and *Compendium Musicae*. The biography underscores Descartes' dual commitment to philosophy and science, highlighting his social status among the gentry, mathematical innovations such as solving the Pappus problem through algebraic geometry, and his epistemology based on clear and distinct ideas. It explores his mechanistic explanations of bodily functions, challenging traditional soul-body distinctions, and his extensive natural philosophy in texts like *Le Monde* and *L'Homme*. Gaukroger also delves into Descartes' cosmological theories, including the vortex theory and laws of motion linked to divine immutability, as well as his nuanced perspectives on animal cognition versus human consciousness. Central to the narrative is Descartes' use of hyperbolic doubt to combat skepticism and establish metaphysical foundations through the *cogito*, alongside his classification of ideas and theological proofs of God's existence. The complex relationship between his natural philosophy and metaphysics, especially in defining motion as a mode, and his innovative approach to the passions in *Passions of the Soul*, rejecting Stoic views for a mind-body union, are key themes. This portrayal captures Descartes' struggle with traditional paradigms during a transformative era, emphasizing his enduring impact on p
hilosophy and science.

範例:選取 AI 轉譯

這些範例示範如何使用 translate 功能。

若要使用「選取 AI」翻譯功能,您必須具備適當的 IAM 原則權限,才能存取 Oracle Cloud Infrastructure Language 服務。

授予在 IAM 原則中使用 ai-service-language-family 資源的權限。將權限授予特定區間中使用者群組的原則敘述句範例如下:

allow group <your group name> to use ai-service-language-family in compartment <your_compartment>

「動態群組」會比對其 OCID 或標記來識別資料庫或函數之類的資源,而「使用者群組」則包含個別的 IAM 使用者。

當原則套用至 OCI 資源時使用動態群組,並在原則套用至人工使用者時使用使用者群組。如需建立動態和使用者群組的詳細步驟,請參閱管理 Dymanic 群組

如需詳細資訊,請參閱語言原則

範例:在 SQL 命令行使用轉譯動作

下列範例顯示 SQL 命令行使用 translate 動作。

注意:您的 AI 設定檔必須指定目標語言。只有提供者 OCI 才支援此功能。

--Create an AI profile with language parameters
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
      profile_name =>'GENAI_NEW',
      attributes   =>'{"provider": "oci",
        "credential_name": "GENAI_CRED",
		"target_language": "french",
		"object_list": [{"owner": "SH", "name": "customers"},
                        {"owner": "SH", "name": "countries"},
                        {"owner": "SH", "name": "supplementary_demographics"},
                        {"owner": "SH", "name": "profits"},
                        {"owner": "SH", "name": "promotions"},
                        {"owner": "SH", "name": "products"}]
       }');
END;
/
exec DBMS_CLOUD_AI.SET_PROFILE('GENAI_NEW');
select ai translate I need to translate this;
RESPONSE
---------------------
Je dois traduire ceci

範例:在 DBMS_CLOUD_AI.GENERATE 函數中使用轉譯

以下範例顯示使用轉譯作為 DBMS_CLOUD_AI.GENERATE 函數內的 Select AI 動作。如需詳細資訊,請參閱 GENERATE 函數

注意:如果在 DBMS_CLOUD_AI.GENERATE 中以屬性形式傳送目標語言參數,則 AI 設定檔可以略過指定目標語言參數。

translate 動作與 target_languagesource_language 一起在 DBMS_CLOUD_AI.GENERATE 函數中提供。此範例使用生成式 AI 翻譯。輸入文字 this is a document (英文為 source_language: "en") 會翻譯成法文 (target_language: "fr")。

SELECT DBMS_CLOUD_AI.GENERATE('select ai translate text to be translated')
          FROM dual;

      DECLARE
         l_attributes  clob := '{"target_language": "fr", "source_language": "en"}';
         output clob;
      BEGIN
         output := DBMS_CLOUD_AI.GENERATE(
                        prompt            => 'this is a document',
                        profile_name      => 'oci_translate',
                        action            => 'translate',
                        attributes        => l_attributes
                     );

範例:使用 DBMS_CLOUD_AI.TRANSLATE 函數進行翻譯

此範例會呼叫 DBMS_CLOUD_AI.TRANSLATE 函數使用生成式 AI 轉譯,使用指定的 AI 設定檔將輸入文字從英文 (source_language) 轉換成法文 (target_language)。

請參閱 TRANSLATE 函數瞭解詳細資訊。

BEGIN
   output_text := DBMS_CLOUD_AI.TRANSLATE(
   profile_name    => 'GENAI_NEW'
   text            => 'text to be translated',
   source_language => 'English',
   target_language => 'French');
END;
/

範例:顯示提供者的支援語言

查詢 AI_TRANSLATION_LANGUAGES 檢視以查看 AI 提供者支援的語言清單。請參閱 AI_TRANSLATION_LANGUAGES 檢視以瞭解詳細資訊。

SELECT* FROM AI_TRANSLATION_LANGUAGES;
LANGUAGE_NAME        LANGUAGE_CODE        PROVIDER
-------------------- -------------------- ---------------
ARABIC               ar                   OCI
CROATIAN             hr                   OCI
CZECH                cs                   OCI
DANISH               da                   OCI
GERMAN               de                   OCI
GREEK                el                   OCI
ENGLISH              en                   OCI
SPANISH              es                   OCI
FINNISH              fi                   OCI
FRENCH               fr                   OCI
FRENCH CANADA        fr-CA                OCI
HEBREW               he                   OCI
HUNGARIAN            hu                   OCI
ITALIAN              it                   OCI

相關內容