使用 Select AI 从自然语言提示生成 SQL

专用 Exadata 基础结构上的自治 AI 数据库 Select AI 允许您使用自然语言查询数据。

Select AI 功能允许 Autonomous AI Database 使用具有大语言模型 (LLM) 的生成式 AI 将用户的输入文本转换为 Oracle SQL。选择 AI 将处理自然语言提示,使用元数据补充提示,然后生成并运行 SQL 查询。

关于选择 AI

使用自然语言通过 SQL 与数据库和 LLM 进行交互,以提高用户工作效率并开发基于 AI 的应用。选择 AI 可使用生成式 AI 简化和自动化,包括从自然语言提示生成、运行和解释 SQL、使用向量存储的检索增强生成、生成合成数据或与 LLM 聊天。

使用 Select AI 时,Autonomous AI Database 可管理将自然语言转换为 SQL 的过程。这意味着您可以提供自然语言提示,而不是 SQL 代码来与数据交互。Select AI 可作为 SQL 用户和开发人员的工作效率工具,让非专家 SQL 用户无需了解数据结构或技术语言即可从数据中获取有用的洞察。

选择 AI 还会自动执行检索增强生成 (RAG) 流程,从生成向量嵌入到使用向量存储通过语义相似性搜索根据提示检索相关内容。其他功能包括合成数据生成、支持对话的聊天历史记录以及其他功能,所有这些功能都来自 SQL 界面。

DBMS_CLOUD_AI 软件包允许与用户指定的 LLM 集成,以便使用自然语言提示生成 SQL 代码。对于生成 SQL 的自然语言,此程序包会向包含相关数据库方案元数据的 LLM 提供增强提示。这允许基于自然语言提示生成、运行和解释 SQL 查询。它还可以使用向量存储和合成数据生成来促进检索增强生成,并允许与 LLM 聊天。DBMS_CLOUD_AI 软件包适用于 Select your AI Provider and LLMs 中列出的 AI 提供程序。

注:

受支持的平台

Autonomous AI Database Serverless 和 Autonomous AI Database on Dedicated Exadata Infrastructure 和 Cloud at Customers 支持 Select AI。

相关术语

在使用 Select AI 之前,了解其使用的各种术语非常重要。

以下是与 Select AI 功能相关的术语:

术语 定义
对话 Select AI 中的对话表示用户与系统之间的交互式交换,允许用户通过一系列自然语言提示查询或与数据库交互。选择 AI 会合并基于会话的短期对话,以根据以前的交互为当前提示生成上下文感知响应。最多将 10 个以前的提示合并到当前请求中,并进行短期对话,从而创建发送到 LLM 的增强提示。Select AI 支持使用可定制的长期对话,使您可以将 Select AI 与不同主题一起使用,而无需混合上下文,这些上下文可以通过 DBMS_CLOUD_AI 程序包中的对话 API 进行配置。有关更多详细信息,请参见 Use and Customize Conversations
数据库身份证明 数据库身份证明是用于访问数据库并与数据库交互的验证身份证明。它们通常由用户名和密码组成,有时由其他验证因素(如安全令牌)补充。这些身份证明用于在应用程序或用户与数据库之间建立安全连接,确保只有授权的个人或系统才能访问和处理数据库中存储的数据。
LLM 中的幻觉 大语言模型上下文中的幻觉是指模型生成与输入提示不正确、无意义或无关的文本的现象。尽管是模型试图生成一致文本的结果,但这些实例可以包含虚构,误导或纯粹想象的信息。幻觉可能是由于训练数据中的偏见,缺乏适当的上下文理解,或模型训练过程的限制。
IAM 借助 Oracle Cloud Infrastructure Identity and Access Management (IAM),您可以控制哪些人可以访问您的云资源。您可以控制一组用户具有的访问类型以及特定资源。要了解详细信息,请参阅身份和访问管理概览
迭代细化

迭代细化是通过基于反馈或评估的重复调整周期逐步改进解决方案或模型的过程。它从初始近似开始,逐步细化它,并继续,直到达到所需的准确性或结果。每个迭代都基于前一个迭代,结合更正或优化,以更接近目标。

在文本摘要生成中,迭代细化可用于处理大型文件或文档。该进程将文本拆分为可管理大小的块,例如,适合于 LLM 令牌限制的块,生成一个块的摘要,然后通过依次合并以下块来改进摘要。

迭代细化的用例:

  • 最适合情境准确性和一致性至关重要的情况,例如在汇总复杂或高度互连的文本时,每个部分都基于前一个部分。
  • 非常适合可接受顺序处理的小规模任务。

请参阅汇总技术

MapReduce

通常,MapReduce 编程模型允许通过将任务分为两个阶段来处理大容量数据:Map 和 Reduce。

  • Map:处理输入数据并将其转换为键 - 值对。
  • Reduce:基于键聚合和汇总映射的数据。MapReduce 对大型数据集执行并行处理。

在 Select AI Summarize 的情况下,MapReduce 将文本分成多个块,并并行和独立地处理它们,为每个块生成单独的摘要。然后将这些摘要组合起来,形成一个有凝聚力的整体摘要。

map reduce 的用例:

  • 最适合大规模并行任务,其中速度和可扩展性是优先事项,例如汇总非常大的数据集或文档。
  • 对于块独立性是可以接受的,并且可以稍后汇总摘要的情况,这是理想的选择。

请参阅汇总技术

元数据

元数据是用于描述数据的数据。对于 Select AI,元数据是数据库元数据,它指的是描述数据库表和视图的结构、组织和属性的数据。

对于数据库表和视图,元数据包括列名和类型、约束条件和键、视图定义、关系、沿袭、质量和新鲜度指示器、安全分类和访问策略。管理良好的元数据支持可发现性、正确使用、性能优化和合规性。选择 AI 会使用包含表定义的表元数据(表名、列名及其数据类型)以及表和列注释、注释和约束条件(可选)来增强 NL2SQL 提示。

元数据扩充

通过高质量的说明、注释和注释来增强数据库方案的练习,以便 LLM 可以更好地了解表和列的意图,阐明业务含义并生成更准确的 SQL。它将裸表或列名转换为有清晰意图、关系和约束条件的有充分记录的资产。

要包括的候选人信息:

  • 表和列说明:用途、业务定义、单位和允许的值范围
  • 键和关系:主键/外键、联接路径
  • 数据语义:时间粒度、维度缓慢变化、重复数据删除规则
  • 约束条件和质量:空性、唯一性、验证规则、数据更新
  • 同义词和别名:映射到技术名称的通用业务术语
  • 示例和模式:示例值、常用筛选器或聚合

有关使用 Oracle SQL Developer for VS Code 通过 Visual Studio Code 添加此类元数据的更多信息,请参见 AI 扩充概述

自然语言提示 自然语言提示是提供的人类可读指令或请求,用于指导生成式 AI 模型,例如大型语言模型。用户无需使用特定的编程语言或命令,而是可以通过以更具对话性或自然语言形式输入提示来与这些模型进行交互。然后,模型将根据提供的提示生成输出。
Network Access Control List,ACL(网络访问控制的列表) 网络访问控制列表是一组规则或权限,用于定义允许哪些网络流量通过网络设备(例如路由器、防火墙或网关)。ACL 用于根据 IP 地址、端口号和协议等各种条件来控制和过滤传入和传出通信。它们在网络安全中发挥着至关重要的作用,使管理员能够管理和限制网络流量,以防止未经授权的访问、潜在的攻击和数据泄露。
相似性搜索 相似性搜索通过比较向量存储中的特征向量来标识和检索与给定查询密切匹配的数据点。
矢量距离 向量距离通过计算特征向量在多维空间中的距离来测量特征向量之间的相似性或差异。
向量索引 向量索引组织和存储特征向量,以便高效地搜索和检索相关数据。
向量存储 向量存储包括用于存储、管理和启用涉及向量嵌入的语义相似性搜索的系统。这包括独立的向量数据库和 Oracle Database 23ai AI Vector Search。

选择 AI 用例

选择 AI 可增强数据交互,使开发人员能够直接从 SQL 构建 AI 驱动的应用,将自然语言提示转换为 SQL 查询和文本响应,支持与 LLM 的聊天交互,使用 RAG 提高当前数据的响应准确性,并生成合成数据。

使用场景包括:

使用准则

提供使用准则,确保有效和正确地使用自然语言提示以生成 SQL,以确保增强用户体验。

预期用途

此功能用于生成和运行由用户提供的自然语言提示生成的 SQL 查询。它结合用户选择的大型语言模型 (LLM),自动执行用户可以手动执行的方案元数据操作。

虽然可以提供任何提示(包括与生成 SQL 查询结果无关的提示),但 Select AI 侧重于 SQL 查询生成。选择 AI 可以通过 chat 操作提交常规请求。

提示增强数据

数据库使用数据库元数据扩充用户指定的提示,以缓解 LLM 中的幻觉。然后将增强提示发送到用户指定的 LLM 以生成查询。

数据库仅使用方案元数据来扩充提示。此元数据可能包括方案定义、表和列注释以及数据字典和目录中提供的内容。为了生成 SQL,在增加提示时,数据库不提供表或视图内容(实际行或列值)。

但是,narrate 操作会向用户指定的 LLM 提供查询结果(其中可能包含数据库数据),以便从中生成描述查询结果的自然语言文本。

警告:大型语言模型 (LLM) 已通过广泛的文本文档和内容(通常来自 Internet)进行训练。因此,LLM 可能已整合了来自无效或恶意内容的模式,包括 SQL 注入。因此,尽管 LLM 擅长生成有用且相关的内容,但它们也可以生成不正确和虚假的信息,包括产生不准确结果和/或损害数据安全性的 SQL 查询。由用户指定的 LLM 提供程序代表您生成的查询将在数据库中运行。贵方对此功能的使用完全由贵方自行承担风险,并且,尽管存在与 Oracle 提供的服务相关的任何其他条款和条件,但贵方接受该风险并明确排除 Oracle 对因该使用而造成的任何损害的责任或责任。

选择您的 AI 提供商和 LLM

选择符合安全标准并符合特定需求(如文本或代码生成)的 AI 提供商和 LLM。

不同的 LLM 擅长基于其训练数据和预期目的的各种任务。一些模型对于文本生成非常出色,但在代码生成方面可能表现不佳,而其他模型则专门针对编码任务进行了优化。选择最适合您需求的 LLM。

AI 提供方 LLM RAG 的嵌入模型 用途
OCI 生成式 AI
  • meta.llama-3.3-70b-instruct(默认值)
  • meta.llama-3.2-90b- 视像指令
  • meta.llama-3.2-11b- 视像指令
  • 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-multilingual-v3.0
  • cohere.embed-english-light-v3.0
  • cohere.embed-multilingual-light-v3.0

请参阅关于在生成式 AI 中嵌入模型

OCI Generative AI Chat 模型支持所有 SELECT AI 操作,例如 runsqlshowsqlexplainsqlnarratechat

OCI 生成文本模型仅支持 SELECT AI chat 操作。

要配置配置文件属性,请参见 Profile Attributes

Azure OpenAI 服务

  • GPT-4o
  • GPT-4
  • GPT-4 带视觉功能的涡轮增压器
  • GPT-3.5-Turbo

文本嵌入 -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 兼容的提供商的模型,例如:

  • 烟花 AI
  • xAI
  • 其他人

从 OpenAI 兼容提供商嵌入模型。例如,请参阅 Fireworks AI embedding models 支持各种用例。
Cohere

  • 命令(默认)
  • 命令每晚(实验性)
  • 命令 -r
  • 命令加
  • 命令灯
  • 命令每晚(实验性)
  • 自定义模型

embed-english-v2.0 最适合 chat 操作。
Google

  • gemini-1.5-flash(默认值)
  • 双子座 -1.5-pro
  • 双子座 -1.0-pro

text-embedding-004(默认) 最适合从自然语言提示、chat 操作和 Select AI RAG 生成 SQL。
人造

  • claude-3-5-sonnet-20240620(默认值)
  • claude-3-opus-20240229
  • claude-3-sonnet-20240229
  • claude-3-haiku-20240307

NA 最适合从自然语言提示、chat 操作和 Select AI RAG 生成 SQL。
Hugging Face

  • Mixtral-8x7B-Instruct-v0.1(默认值)
  • Meta-Llama-3-70B- 说明
  • Qwen1.5-1.8B
  • 其他聊天模型

NA 最适合从自然语言提示、chat 操作和 Select AI RAG 生成 SQL。
AWS

  • amazon.titan-embed-text-v1
  • amazon.titan-embed-text-v2:0
  • cohere.embed-english-v3
支持各种用例。

注:

使用 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. 向要使用 Select AI 和 AI 提供者端点的用户授予网络 ACL 访问权限。

    ADMIN 用户可以授予网络 ACL 访问权限。有关详细信息,请参阅《Oracle Database 19c PL/SQL Packages and Types Reference 》或《Oracle Database 26ai PL/SQL Packages and Types Reference 》中的 APPEND_HOST_ACE Procedure

  3. 创建身份证明以允许访问 AI 提供程序。

    有关更多信息,请参见 CREATE_CREDENTIAL Procedure

    下面是一个如何创建凭证以允许访问 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 的更多信息,请参见 Profile Attributes

对于 Google,请使用 generativelanguage.googleapis.com

对于 Anthropic,使用 api.anthropic.com

对于拥抱面,请使用 api-inference.huggingface.co

ace 访问控制条目 (Access Control Entry,ACE)。提供了 XS$ACE_TYPE 类型以构造 ACL 的每个 ACE 条目。

有关更多详细信息,请参见《Oracle Database 19c Real Application Security Administrator’s and Developer’s Guide 》或《Oracle Database 26ai Real Application Security Administrator’s and Developer’s Guide 》中的 Creating ACLs and ACEs

DBMS_CLOUD.CREATE_CREDENTIAL 参数

Parameter (参数) 说明
credential_name 要存储的凭证的名称。credential_name 参数必须符合 Oracle 对象命名约定,该约定不允许有空格或连字符。
username

usernamepassword 参数一起指定 AI 提供者凭证。

username 是用户指定的用户名。

password

usernamepassword 参数一起指定 AI 提供者凭证。

password 是您的 AI 提供商密钥,并且依赖于提供商,即 OpenAI、Cohere、Azure OpenAI 服务、OCI、Google、Anthropic 或 Hugging Face。有关详细信息,请参见

创建和设置 AI 配置文件

介绍创建和启用 AI 配置文件的步骤。

使用 DBMS_CLOUD_AI.CREATE_PROFILE 创建 AI 配置文件。接下来,启动 DBMS_CLOUD_AI.SET_PROFILE 以启用 AI 配置文件,以便可以在自然语言提示符下使用 SELECT AI

注:在使用 SELECT AI 之前,必须在每个新数据库会话(连接)中运行 DBMS_CLOUD_AI.SET_PROFILE

以下 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 支持基于会话的短期对话和可定制的对话。

基于会话的短期会话:选择 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 功能一起使用。

例如,对话提供了一种直观的数据分析方法:

要启用对话,请参见 Example:Enable Conversations in Select AI 以了解完整示例。

基于会话的对话与可定制的对话

下表比较了 Select AI 中的基于会话的对话和可定制的对话:

问题 基于会话的短期对话 可定制的长期对话
何时使用? 最适合您希望模型在单个会话中记住最近问题和答案的快速临时聊天。当以后不需要保存或重复使用对话时,这很有用。 专为可能跨多个会话的较长或持续对话而设计。当您想要跟踪、查看或管理对话历史记录时,或者当应用程序的不同部分需要随着时间的推移访问相同的对话上下文时,它非常有用。
我如何启用? 在 AI 配置文件中设置 {"conversation": true or false} 使用 DBMS_CLOUD_AI.SET_CONVERSATION_ID 过程或 DBMS_CLOUD_AI.GENERATE
允许进行多少次对话? 一。

您可以创建多个对话。

如果显式指定对话 ID,则可以在它们之间交替进行,以便根据需要将提示与适当的对话关联。

提示存储在何处以及保存多长时间? 提示存储在临时表中,并在会话结束时删除。

提示存储在永久表中。

提示在数据库中保留 DBMS_CLOUD_AI.CREATE_CONVERSATION 过程中的 retention_days 参数指定的天数。在保留期之后,会话及其提示将被自动删除。还可以使用 DBMS_CLOUD_AI.DELETE_CONVERSATION_PROMPT 过程手动删除提示。

存储了多少个提示,并向 LLM 发送了多少个提示? 最多存储 10 个提示并将其发送到 LLM。您无法自定义此限制。

将存储所有提示。

缺省情况下,系统向 LLM 发送 10 个最新提示。您可以使用 conversation_length 参数定制此项。请参见 CREATE_CONVERSATION Attributes

是否可以删除个人提示? 不可以,您不能手动删除单个提示。 可以使用在 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

通过选择 AI,您可以提供反馈来帮助提高所选 LLM 生成更准确 SQL 查询的能力。

注:此功能仅适用于 Oracle Database 23ai。您可以将其与现有的 Select AI 操作一起使用:runsqlshowsqlexplainsql。确保您的 AI 配置文件已配置为生成 NL2SQL 而非 RAG。

您可以通过 feedback 操作或 DBMS_CLOUD_AI.FEEDBACK 过程提供反馈以提高生成的 SQL 的准确性。首次使用反馈功能时,选择 AI 会创建名为 <profile_name>_FEEDBACK_VECINDEX 的默认向量索引,其中包含默认属性。此索引有助于根据提供的反馈细化将来生成的 SQL。有关更多信息,请参见 Vector Index for FEEDBACK

提示:当指定的 LLM 无法生成正确的 SQL 查询或者未返回 NL2SQL SELECT AI 操作之一的预期结果时,请使用 DBMS_CLOUD_AI.FEEDBACK 过程。还可以使用 DBMS_CLOUD_AI.FEEDBACK 过程将正确的 SQL 直接添加到向量表中。这有助于指导将来的 SQL 生成,因为它可以作为类似提示的参考。

接受以下类型的反馈:

使用反馈的好处

Select AI 中的反馈操作和过程引入了提示优化机制,可提高 SQL 查询生成的准确性。

AI 配置文件的所有者可以为生成的 SQL 查询提供反馈,并且可以从用户交互中随着时间的推移选择 AI 系统学习。此学习涉及收集提示和反馈内容的存储库,其中向量搜索用于标识与当前提示类似的提示。顶级匹配示例作为增强提示的一部分作为 LLM 的元数据提供。有以下优点:

如何提供反馈

选择 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 ProcedureExample:Select AI FEEDBACK

使用属性图形查询图形数据

选择 AI 将使用自然语言在 Oracle Property Graphs 上生成属性图形查询 (PGQ)。它使用户能够以最少的 SQL 知识通过 GRAPH_TABLE 运算符查询图形数据。

选择 AI 会将其自然语言扩展到 SQL (NL2SQL) 功能,以图形方式显示结构,使您能够使用自然语言查询 SQL 属性图形。选择 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 通过使用指定属性图形的上下文来解释提示。选择 AI 会构建一个增强提示,其中包括:

此增强提示将发送到 LLM。选择 AI 将运行查询并返回结果。如果属性图与 AI 配置文件中的表、方案或视图等其他对象类型一起指定,则选择 AI 会引发错误。

SQL 与 PGQ

使用 Select AI 时,生成的查询类型取决于 AI 配置文件的 object_list 属性中定义的对象。

有关详细信息,请参阅 SQL 属性图形SQL GRAPH 查询

在属性图上使用 Select AI 的好处

数据库用户可以使用 Select AI 查询属性图形,从自然语言生成图形查询,减少手动工作并提高对图形关系的理解。

主要优点包括:

限制

为属性图形选择 AI 不支持以下功能:

如何在属性图形上使用选择 AI

通过选择 AI,您可以使用 DBMS_CLOUD_AI.GENERATE 函数或使用 Select AI <action> <prompt> 浏览图形数据。

在 AI 配置文件的 object_list 属性中定义属性图形后,可以使用:

以下是支持的操作:runsqlshowsqlexplainsqlnarrateshowpropmt。Select AI for Property Graph 还支持基于会话的短期和可定制的长期对话。

要了解更多信息,请参见 Example:Select AI for Property GraphsExample:Sample Prompts for Property Graphs

使用 Select AI 生成概要

选择 AI 可以生成文本摘要,特别是大文本,通常使用 AI 提供程序最多支持 1 GB。您可以根据您的特定需求从文本或大文件中提取关键洞察。此功能使用 AI 配置文件中指定的 LLM 生成给定文本的摘要。

通过以下方式选择 AI 提供的内容汇总:

注:

汇总技术

您可以通过输入全文作为 LLM 的提示来汇总大型文档。但是,由于 LLM 具有令牌限制,因此 Select AI 应用不同的技术来汇总大型文档。

选择 AI 会使用迭代细化,选择 MapReduce 作为汇总技术。有关详细信息,请参见 Related Terminology

根据给定 LLM 的最大令牌大小,Select AI 可以将大内容分解为更小、更易于处理的块,使其符合 LLM 的限制。然后,选择 AI 可以使用迭代细化或映射简化技术来生成汇总。选择 AI 会使用 MapReduce 作为默认设置。有关更多详细信息,请参见 SUMMARIZE FunctionSUMMARIZE Parameters

使用 Select AI 翻译文本

借助 Select AI,您可以使用 OCI 翻译服务中的生成式 AI,将文本翻译为您选择的语言。

您可以将此功能与现有 Select AI RAG 一起使用。您可以将 translateDBMS_CLOUD_AI.GENERATEnarrate 组合使用生成式 AI 来生成首选语言的转换输出。

请参阅 TRANSLATE FunctionGENERATE FunctionExample:Select AI TRANSLATE 以了解更多信息。

使用翻译的好处

Select AI 中的转换功能使您能够为以下底部转换不同语言的输入文本:

如何使用翻译

通过选择 AI,您可以使用 translate 操作或调用 DBMS_CLOUD_AI.GENERATEDBMS_CLOUD_AI.TRANSLATE 函数将文本输入转换为首选语言。

要使用 Select 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 功能集成到自治 AI 数据库工作流中。Select AI for Python 提供了一个客户端库 select_ai,使您可以从 Python 使用自治 AI 数据库中的 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 认证。选择 AI for Python 可以在其他平台上工作,但是它没有经过认证。

单击 https://github.com/oracle/python-select-ai/issues 报告问题。

注:选择适用于 Python 的 AI 代理在专用 Exadata 基础结构上的自治 AI 数据库上不可用。

用于选择 AI 配置文件的受支持函数(同步和异步)

通过配置文件发送提示时,可以在为 AI 配置文件对象定义的多个函数中进行选择。其中一些如下:

有关函数的完整列表,请参见 Select AI for Python 指南。有关选择 AI 操作的更多信息,另请参见 Use AI Keyword to Enter Prompts

支持的类

该库包括用于管理提供程序、配置文件、对话、向量索引和合成数据的类。同步和异步版本都可用。

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 配置文件后,使用 Select 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 使用 AWS 提供的模型从自然语言提示或聊天中生成、运行和解释 SQL。

以下示例说明如何将 AWS 用作 Amazon Bedrock 及其基础模型的 AI 提供者。此示例显示如何创建 AWS 凭证、提供网络访问、创建 AI 配置文件,以及使用 Select AI 操作从自然语言提示生成 SQL 查询以及使用 AWS 基础模型进行聊天。

要使用 AWS,请获取访问密钥、密钥和模型 ID。请参见 Configure AI Profiles Using DBMS_CLOUD_AI 中的 AWS specific instruction 。将模型 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');

示例:在选择 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 查询生成。

注:即使以前未运行该提示,也可以为 Select AI SQL 提示提供反馈。选择 AI 不需要在提交反馈之前在查询中使用 SQL 提示;您可以随时为任何有效提示提供反馈。

示例:提供负反馈

以下示例演示如何使用 feedback_type 作为 negative 来更正生成的 SQL 作为反馈(负反馈),并提供 SQL 查询。

通过使用包含提示的 sql_text 参数调用 DBMS_CLOUD_AI.FEEDBACK 过程,可以将反馈添加到名为 OCI_FEEDBACK1 的 AI 配置文件。要了解属性,请参阅反馈过程。然后,从 <profile_name>_FEEDBACK_VECINDEX$VECTAB 表检索 contentattributes 列,该表链接到该特定的 SQL 查询。首次使用反馈功能时,选择 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 配置文件中。然后,从 <profile_name>_FEEDBACK_VECINDEX$VECTAB 表检索 contentattributes 列,该表链接到该特定的 SQL 查询。首次使用反馈功能时,选择 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,选择 AI 仅允许一个反馈条目。如果为同一 sql_id 提供其他反馈,则 Select AI 会将上一个条目替换为新条目。

有关参数的更多详细信息,请参见 Feedback Procedure

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_IDfeedback 操作结合使用来为特定生成的 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))

示例:访问顶点和边缘属性

提示: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 查询生成

本示例演示了 Select AI 中适用于 Oracle Database 23ai 的注释的集成。注释将添加到发送到 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 函数中为 Select AI 启用 "constraints":"true" 以检索外键和引用键。

--
-- 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 构造。

查看 Prerequisites for 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,Select 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 函数使用迭代细化方法来处理块。有关更多信息,请参见 Select AI Terminology

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 功能。

要使用 Select 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 资源时使用动态组,当策略应用于人工用户时使用用户组。有关创建动态组和用户组的详细步骤,请参见 Managing Dymanic Groups

有关详细信息,请参阅语言策略

示例:对 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 操作。有关详细信息,请参阅生成函数

注:如果 AI 配置文件作为 DBMS_CLOUD_AI.GENERATE 中的属性传递,则可以跳过指定目标语言参数。

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 Function

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

相关内容