ai_query 函数

适用于:check marked yes Databricks SQL

重要

此功能目前以公共预览版提供。

调用现有的 Azure Databricks 模型服务终结点,然后分析并返回其响应。

要求

语法

若要查询为外部模型基础模型提供服务的终结点,请执行以下操作:

ai_query(endpointName, request)

若要查询自定义模型服务终结点,请执行以下操作:

ai_query(endpointName, request, returnType)

参数

  • endpointName:一个 STRING 文本,是同一工作区中用于调用的现有 Databricks 模型服务终结点的名称。 定义者必须对终结点具有“可查询”权限。
  • request:一个表达式,是用于调用终结点的请求。
    • 如果终结点是一个外部模型服务终结点或 Databricks 基础模型 API 终结点,则请求必须是一个字符串。
    • 如果终结点是一个自定义模型服务终结点,则请求可以是单个列或结构表达式。 结构字段名称应与终结点所需的输入特征名称匹配。
  • returnType:一个表达式,即来自终结点的预期 returnType。 这与 from_json 函数中的架构参数类似,它接受 STRING 表达式或 schema_of_json 函数的调用。 这是查询自定义模型服务终结点所必需的。

返回

来自终结点的已分析响应。

示例

若要查询外部模型服务终结点或 Databricks 基础模型,请执行以下操作:

> SELECT ai_query(
    'my-external-model-openai-chat',
    'Describe Databricks SQL in 30 words.'
  ) AS summary

  "Databricks SQL is a cloud-based platform for data analytics and machine learning, providing a unified workspace for collaborative data exploration, analysis, and visualization using SQL queries."

> CREATE FUNCTION correct_grammar(text STRING)
  RETURNS STRING
  RETURN ai_query(
    'databricks-llama-2-70b-chat',
    CONCAT('Correct this to standard English:\n', text));
> GRANT EXECUTE ON correct_grammar TO ds;
- DS fixes grammar issues in a batch.
> SELECT
    * EXCEPT text,
    correct_grammar(text) AS text
  FROM articles;

若要查询自定义模型服务终结点,请执行以下操作:


> SELECT text, ai_query(
    endpoint => 'spam-classification-endpoint',
    request => named_struct(
      'timestamp', timestamp,
      'sender', from_number,
      'text', text),
    returnType => 'BOOLEAN') AS is_spam
  FROM messages

> SELECT ai_query(
    'weekly-forecast',
    request => struct(*),
    returnType => 'FLOAT') AS predicted_revenue
  FROM retail_revenue

> SELECT ai_query(
    'custom-llama-2-7b-chat',
    request => named_struct("messages",
        ARRAY(named_struct("role", "user", "content", "What is ML?"))),
    returnType => 'STRUCT<candidates:ARRAY<STRING>>')

  {"candidates":["ML stands for Machine Learning. It's a subfield of Artificial Intelligence that involves the use of algorithms and statistical models to enable machines to learn from data, make decisions, and improve their performance on a specific task over time."]}