使用 ai_query() 查询外部模型

注意

此功能目前以公共预览版提供。 要查询提供外部模型的终结点,必须注册公共预览版。 请填写并提交 AI Functions 公共预览登记表

本文介绍如何使用内置的 Databricks SQL 函数 ai_query() 设置和查询外部模型终结点。 该示例使用 Mosaic AI 模型服务中的外部模型支持来查询 OpenAI 提供的 gpt-4 并完成聊天任务。 请参阅 Azure Databricks 上的 AI 函数,详细了解此 AI 函数。

先决条件

创建外部模型终结点

下面创建一个外部模型服务终结点,为 OpenAI gpt-4 的聊天任务提供服务。

要创建个人访问令牌,请参阅 Databricks 自动化身份验证

import requests
import json

personal_access_token = "your-personal-access-token"
headers = {
    "Authorization": "Bearer " + personal_access_token,
}
host = "https://oregon.cloud.databricks.com/"
url = host + "api/2.0/serving-endpoints"

data = {
    "name": "my-external-openai-chat",
    "config": {
        "served_entities": [
            {
                "name": "my_entity",
                "external_model": {
                    "name": "gpt-4",
                    "provider": "openai",
                    "openai_config": {
                        "openai_api_key": "{{secrets/my-external-model/openai}}",
                    },
                    "task": "llm/v1/chat",
                },
            }
        ],
    },
}

response = requests.post(url, headers=headers, json=data)

print("Status Code", response.status_code)
print("JSON Response ", json.dumps(json.loads(response.text), indent=4))

使用 ai_query() 查询外部模型

在 Databricks SQL 查询编辑器中,可以编写 SQL 查询来查询外部模型服务终结点。

查询示例:

SELECT ai_query(
    "my-external-openai-chat",
    "What is a large language model?"
  )

SELECT question, ai_query(
    "my-external-openai-chat",
    "You are a customer service agent. Answer the customer's question in 100 words: " || question
  ) AS answer
FROM
  uc_catalog.schema.customer_questions

SELECT
 sku_id,
 product_name,
 ai_query(
   "my-external-openai-chat",
   "You are a marketing expert for a winter holiday promotion targeting GenZ. Generate a promotional text in 30 words mentioning a 50% discount for product: " || product_name
 )
FROM
 uc_catalog.schema.retail_products
WHERE
 inventory > 2 * forecasted_sales

其他资源