2024年8月13日

GPT Actions 库 - Snowflake Direct

这个特定的GPT Action提供了如何连接到Snowflake数据仓库的概述。该Action接收用户的问题,扫描相关表格以收集数据模式,然后编写SQL查询来回答用户的问题。

注意:本指南返回的是ResultSet SQL语句,而非不受GPT Actions应用JSON负载限制的完整结果。对于生产环境和高级用例,需要中间件来返回CSV文件。您可以按照GPT Actions - Snowflake中间件指南中的说明来实现此流程。

价值:用户现在可以利用ChatGPT的自然语言能力直接连接到Snowflake的数据仓库。

示例用例:

  • 数据科学家可以连接到表格并使用ChatGPT的数据分析功能运行数据分析
  • 公民数据用户可以对其交易数据提出基本问题
  • 用户可以更清晰地查看其数据及潜在异常

在开始之前,请确保您已在应用程序环境中完成以下步骤:

  • 配置一个Snowflake数据仓库
  • 确保通过ChatGPT验证进入Snowflake的用户拥有必要的角色权限,可以访问数据库、模式和表

自定义GPT指令

创建自定义GPT后,请将以下文本复制到指令面板中。有问题吗?查看入门示例详细了解此步骤的操作方法。

**Context**: You are an expert at writing Snowflake SQL queries. A user is going to ask you a question. 

**Instructions**:
1. No matter the user's question, start by running `runQuery` operation using this query: "SELECT column_name, table_name, data_type, comment FROM {database}.INFORMATION_SCHEMA.COLUMNS" 
-- Assume warehouse = "<insert your default warehouse here>", database = "<insert your default database here>", unless the user provides different values 
2. Convert the user's question into a SQL statement that leverages the step above and run the `runQuery` operation on that SQL statement to confirm the query works. Add a limit of 100 rows
3. Now remove the limit of 100 rows and return back the query for the user to see
4. Use the <your_role> role when querying Snowflake
5. Run each step in sequence. Explain what you are doing in a few sentences, run the action, and then explain what you learned. This will help the user understand the reason behind your workflow. 

**Additional Notes**: If the user says "Let's get started", explain that the user can provide a project or dataset, along with a question they want answered. If the user has no ideas, suggest that we have a sample flights dataset they can query - ask if they want you to query that

OpenAPI 规范

创建自定义GPT后,请将以下文本复制到操作面板中。按照此处说明,将服务器URL更新为您的Snowflake账户名称URL加上/api/v2。有问题吗?查看入门示例了解此步骤的详细工作原理。

openapi: 3.1.0
info:
  title: Snowflake Statements API
  version: 1.0.0
  description: API for executing statements in Snowflake with specific warehouse and role settings.
servers:
  - url: 'https://<orgname>-<account_name>.snowflakecomputing.com/api/v2'


paths:
  /statements:
    post:
      summary: Execute a SQL statement in Snowflake
      description: This endpoint allows users to execute a SQL statement in Snowflake, specifying the warehouse and roles to use.
      operationId: runQuery
      tags:
        - Statements
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                warehouse:
                  type: string
                  description: The name of the Snowflake warehouse to use for the statement execution.
                role:
                  type: string
                  description: The Snowflake role to assume for the statement execution.
                statement:
                  type: string
                  description: The SQL statement to execute.
              required:
                - warehouse
                - role
                - statement
      responses:
        '200':
          description: Successful execution of the SQL statement.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                  data:
                    type: object
                    additionalProperties: true
        '400':
          description: Bad request, e.g., invalid SQL statement or missing parameters.
        '401':
          description: Authentication error, invalid API credentials.
        '500':
          description: Internal server error.

以下是设置与这个第三方应用程序进行身份验证的说明。有问题吗?查看入门示例以更详细地了解此步骤的工作原理。

在ChatGPT中设置身份验证之前,请在Snowflake中执行以下步骤。

1. 可选:为ChatGPT配置IP白名单

对于设置了通过IP限制连接的Snowflake账户,可能需要为ChatGPT添加例外规则。

  • 查阅Snowflake关于网络策略的文档
  • 前往Snowflake工作表
  • 创建一个网络规则,包含ChatGPT的出站IP范围,具体列表请参见此处
  • 创建相应的网络策略
## Example with ChatGPT IPs as of October 23, 2024
## Make sure to get the current IP ranges from https://platform.openai.com/docs/actions/production
CREATE NETWORK RULE chatgpt_network_rule
  MODE = INGRESS
  TYPE = IPV4
  VALUE_LIST = ('23.102.140.112/28',
                '13.66.11.96/28',
                '104.210.133.240/28',
                '70.37.60.192/28',
                '20.97.188.144/28',
                '20.161.76.48/28',
                '52.234.32.208/28',
                '52.156.132.32/28',
                '40.84.220.192/28',
                '23.98.178.64/28',
                '51.8.155.32/28',
                '20.246.77.240/28',
                '172.178.141.0/28',
                '172.178.141.192/28',
                '40.84.180.128/28');

CREATE NETWORK POLICY chatgpt_network_policy
  ALLOWED_NETWORK_RULE_LIST = ('chatgpt_network_rule');

网络策略可以在账户、安全集成和用户级别应用。最具体的网络策略会覆盖更通用的网络策略。根据这些策略的应用方式,除了安全集成外,您可能还需要为个别用户修改策略。如果遇到此问题,可能会遇到Snowflake的错误代码390422。

CREATE SECURITY INTEGRATION CHATGPT_INTEGRATION
  TYPE = OAUTH
  ENABLED = TRUE
  OAUTH_CLIENT = CUSTOM
  OAUTH_CLIENT_TYPE = 'CONFIDENTIAL'
  OAUTH_REDIRECT_URI = 'https://oauth.pstmn.io/v1/callback' --- // this is a temporary value while testing your integration. You will replace this with the value your GPT provides
  OAUTH_ISSUE_REFRESH_TOKENS = TRUE
  OAUTH_REFRESH_TOKEN_VALIDITY = 7776000
  NETWORK_POLICY = chatgpt_network_policy; --- // this line should only be included if you followed step 1 above
  • 获取您的OAuth客户端ID、授权URL和令牌URL
DESCRIBE SECURITY INTEGRATION CHATGPT_INTEGRATION;

您可以在以下3列中找到所需的信息:

../../../images/snowflake_direct_oauth.png

  • 使用SHOW_OAUTH_CLIENT_SECRETS检索您的OAuth客户端密钥
SELECT 
trim(parse_json(SYSTEM$SHOW_OAUTH_CLIENT_SECRETS('CHATGPT_INTEGRATION')):OAUTH_CLIENT_ID) AS OAUTH_CLIENT_ID
, trim(parse_json(SYSTEM$SHOW_OAUTH_CLIENT_SECRETS('CHATGPT_INTEGRATION')):OAUTH_CLIENT_SECRET) AS OAUTH_CLIENT_SECRET;

在ChatGPT中,点击"身份验证"并选择"OAuth"。输入以下信息。

表单字段
认证类型OAuth
客户端ID来自SHOW_OAUTH_CLIENT_SECRETS的OAUTH_CLIENT_ID
客户端密钥来自SHOW_OAUTH_CLIENT_SECRETS的OAUTH_CLIENT_SECRET
授权URL来自DESCRIBE SECURITY INTEGRATION的OAUTH_AUTHORIZATION_ENDPOINT
令牌URL来自DESCRIBE SECURITY INTEGRATION的OAUTH_TOKEN_ENDPOINT
作用范围session:role:your_role*
令牌交换方法默认(POST请求)

*Snowflake 作用域传递角色时采用格式 session:role:,例如 session:role:CHATGPT_INTEGRATION_ROLE。虽然可以留空并在指令中指定角色,但在此处添加会将其包含在 OAuth 同意请求中,有时会更可靠。

在ChatGPT中设置好身份验证后,按照应用程序中的以下步骤完成Action的最终设置。

  • 从GPT Action复制回调URL
  • 将您的安全集成中的重定向URI更新为ChatGPT提供的回调URL。
ALTER SECURITY INTEGRATION CHATGPT_INTEGRATION SET OAUTH_REDIRECT_URI='https://chat.openai.com/aip/<callback_id>/oauth/callback';
  • 本指南旨在说明一般概念,仅供参考用途。我们无法为第三方API集成提供全面支持。
  • 如果您更新了YAML文件,回调URL可能会发生变化,请在修改时仔细确认其正确性。
  • 回调URL错误: 如果您在ChatGPT中遇到回调URL错误,请特别注意上述的后续操作步骤。您需要直接将回调URL添加到安全集成中,才能使操作正确完成身份验证
  • Schema调用了错误的仓库或数据库: 如果ChatGPT调用了错误的仓库或数据库,建议更新您的指令,使其更明确地指出(a)应该调用哪个仓库/数据库,或者(b)要求在运行查询前用户必须提供这些确切细节

是否有您希望我们优先考虑的集成方案?我们的集成是否存在错误?请在GitHub上提交PR或问题,我们会尽快查看。