GPT Actions - Snowflake 直接连接
简介
本页面为开发者提供了一个针对特定应用程序构建 GPT Action 的说明和指南。在继续之前,请确保您已熟悉以下信息:
此特定的 GPT Action 提供了连接到 Snowflake 数据仓库的概述。此 Action 接收用户的问题,扫描相关表以收集数据模式,然后编写 SQL 查询来回答用户的问题。
注意:此 cookbook 返回的是 ResultSet SQL 语句,而不是受 GPT Actions 应用程序/JSON 载荷限制的完整结果。对于生产和高级用例,需要一个中间件来返回 CSV 文件。您可以按照 GPT Actions - Snowflake Middleware cookbook 中的说明来实现此流程。
价值 + 示例业务用例
价值:用户现在可以利用 ChatGPT 的自然语言功能直接连接到 Snowflake 的数据仓库。
示例用例:
- 数据科学家可以使用 ChatGPT 的数据分析功能连接到表并运行数据分析
- 普通数据用户可以询问有关其交易数据的基础问题
- 用户可以更深入地了解他们的数据和潜在的异常情况
应用程序信息
应用程序关键链接
在开始之前,请查看应用程序中的这些链接:
- 应用程序网站:https://app.snowflake.com/
- 应用程序 API 文档:https://docs.snowflake.com/en/developer-guide/sql-api/intro
应用程序先决条件
在开始之前,请确保在您的应用程序环境中完成以下步骤:
- 预配 Snowflake 数据仓库
- 确保通过 ChatGPT 进行身份验证到 Snowflake 的用户拥有对数据库、模式和表的访问权限,并具有必要的角色。
1. 配置自定义 GPT
设置 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.
2. 配置 Snowflake 集成
以下是有关与此第三方应用程序设置身份验证的说明。有疑问吗?请查看 入门示例,了解此步骤的详细信息。
配置 ChatGPT 的 IP 白名单
网络策略限制按 IP 连接的 Snowflake 账户可能需要为 ChatGPT 添加例外。
## ChatGPT IP ranges available at https://openai.com/chatgpt-actions.json
CREATE NETWORK RULE chatgpt_network_rule
MODE = INGRESS
TYPE = IPV4
VALUE_LIST = ('23.102.140.112/28',...,'40.84.180.128/28');
CREATE NETWORK POLICY chatgpt_network_policy
ALLOWED_NETWORK_RULE_LIST = ('chatgpt_network_rule');
网络策略可以应用于账户、安全集成和用户级别。最具体的网络策略将覆盖更通用的网络策略。根据这些策略的应用方式,您可能需要更改单个用户的策略以及安全集成。如果遇到此问题,您可能会遇到 Snowflake 的错误代码 390422 或通用的“无效客户端”错误。
创建安全集成
- 查看 Snowflake OAuth 概述:https://docs.snowflake.com/en/user-guide/oauth-snowflake-overview
- 通过 安全集成 创建新的 OAuth 凭据 - 您需要为每个 OAuth 应用/自定义 GPT 创建一个新的,因为 Snowflake 重定向 URI 是 1 对 1 映射到安全集成
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
可选:自动化网络规则配置
ChatGPT 现在使用超过 100 个出口 IP 地址。该列表会不定期更新,且不会提前通知。为了跟上它的更新,我们可以每天获取列表并将其应用于我们的网络规则。
### 允许与 OpenAI 出站流量的网络规则
sql
CREATE OR REPLACE NETWORK RULE chatgpt_actions_rule
MODE = EGRESS -- outbound
TYPE = HOST_PORT
VALUE_LIST = ('openai.com:443');
### 应用该规则的访问集成
sql
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION chatgpt_actions_integration
ALLOWED_NETWORK_RULES = (chatgpt_actions_rule)
ENABLED = TRUE;
### 用于获取 IP 地址范围的 UDF
```sql
CREATE OR REPLACE FUNCTION getChatGPTActionsAddresses()
RETURNS ARRAY -- array
def get_ip_address_ranges():
resp = requests.get("https://openai.com/chatgpt-actions.json", timeout=10)
resp.raise_for_status()
data = [entry["ipv4Prefix"] for entry in resp.json().get("prefixes", []) if "ipv4Prefix" in entry]
return data
$$;
### 用于更新网络规则的过程
sql
CREATE OR REPLACE PROCEDURE update_chatgpt_network_rule()
RETURNS STRING
LANGUAGE SQL
AS
$$
DECLARE
ip_list STRING;
BEGIN
-- Properly quote the IPs for use in VALUE_LIST
ip_list := '''' || ARRAY_TO_STRING(getChatGPTActionsAddresses(), ''',''') || '''';
-- Run the dynamic SQL to update the rule EXECUTE IMMEDIATE 'ALTER NETWORK RULE chatgpt_network_rule SET VALUE_LIST = (' || ip_list || ')';
RETURN 'chatgpt_network_rule updated with ' || ARRAY_SIZE(getChatGPTActionsAddresses()) || ' entries'; END; $$; ```
### 调用该过程
sql
CALL update_chatgpt_network_rule();
### 每天太平洋时间早上 6 点运行该过程
sql
CREATE OR REPLACE TASK auto_update_chatgpt_network_rule
WAREHOUSE = COMPUTE_WH
SCHEDULE = 'USING CRON 0 6 * * * America/Los_Angeles'
AS
CALL update_chatgpt_network_rule();
3. 配置 GPT Action 身份验证
收集 Snowflake 的关键信息
- 检索您的 OAuth 客户端 ID、授权 URL 和令牌 URL
DESCRIBE SECURITY INTEGRATION CHATGPT_INTEGRATION;
您将在以下 3 行中找到所需信息:
- 使用 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;
现在是时候在 Postman 中测试您的 Snowflake 集成了。如果您为安全集成配置了网络策略,请确保它包含您用于测试的机器的 IP。
在 GPT Action 身份验证中设置 OAuth 值
在 ChatGPT 中,点击“身份验证”并选择“OAuth”。在此处输入信息。
| 表单字段 | 值 |
表单字段 | 值 |
---|---|
身份验证类型 | OAuth |
客户端 ID | OAUTH_CLIENT_ID from SHOW_OAUTH_CLIENT_SECRETS |
客户端密钥 | OAUTH_CLIENT_SECRET from SHOW_OAUTH_CLIENT_SECRETS |
授权 URL | OAUTH_AUTHORIZATION_ENDPOINT from DESCRIBE SECURITY INTEGRATION |
令牌 URL | OAUTH_TOKEN_ENDPOINT from DESCRIBE SECURITY INTEGRATION |
范围 | session:role:CHATGPT_INTEGRATION_ROLE* |
令牌交换方法 | 默认 (POST 请求) |
*Snowflake 范围以 session:role:<your_role>
的格式传递角色,例如 session:role:CHATGPT_INTEGRATION_ROLE
。您可以选择将此字段留空并在 GPT 指令中指定角色,但在此处添加它会将其包含在 OAuth 同意请求中,这有时会更可靠。
4. 更新 Snowflake 集成重定向 URI
在 ChatGPT 中设置身份验证后,请按照以下步骤在应用程序中完成操作。
- 复制 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 直接添加到安全集成中,操作才能正确进行身份验证。
- 模式调用了错误的数据仓库或数据库: 如果 ChatGPT 调用了错误的数据仓库或数据库,请考虑更新您的指令,使其更明确地(a)指定应调用哪个数据仓库/数据库,或(b)要求用户在运行查询前提供这些详细信息。
您希望我们优先处理哪些集成?我们的集成是否存在错误?在我们的 GitHub 上提交 PR 或 issue,我们会进行查看。