共用方式為


ai_query函式

適用於:核取記號為「是」Databricks SQL 核取記號為「是」Databricks Runtime

重要

這項功能處於公開預覽狀態

叫用現有的 Azure Databricks 模型服務端點 ,並剖析並傳回其回應。

請參閱下列指南, ai_query 以瞭解如何用於不同的使用案例:

需求

注意

  • 在 Databricks Runtime 14.2 和更新版本中,Databricks 筆記本支援此函式,包括在 Databricks 工作流程中作為任務執行的筆記本。
  • 在 Databricks Runtime 14.1 和更低版本中,Databricks 筆記本不支援此函式。

語法

若要查詢提供外部模型或基礎模型的端點:

ai_query(endpoint, request)

使用 模型查詢自定義模型提供的端點,schema

ai_query(endpoint, request)

若要在沒有模型的情況下查詢提供端點的自訂模型,schema:

ai_query(endpoint, request, returnType, failOnError)

引數

  • endpointSTRING 字面值、Databricks Foundation 模型服務端點名稱、外部模型服務端點,或相同工作區中的自定義模型端點以進行調用。 定義器必須具有端點 CAN QUERY 許可權。
  • request:表達式,用來叫用端點的要求。
    • 如果端點是外部模型服務端點或 Databricks Foundation 模型 API 端點,則要求必須是 STRING
    • 如果端點是提供端點的自定義模型,要求可以是單一 column 或結構表達式。 結構域名應該符合端點所預期的輸入特徵名稱。
  • returnType:來自端點的預期 returnType 表示式。 這類似於 schema中的 參數,它會接受 STRING 表示式或調用 schema_of_json 函式
    • 如果未提供此表達式,在 Databricks Runtime 14.2 和更新版本中,ai_query() 會自動從自定義模型服務端點的模型 schema 推斷傳回類型。
    • 在 Databricks Runtime 14.1 和以下版本中,查詢自定義模型服務端點時需要此運算式。
  • failOnError:(選擇性) 布爾常值預設為 true。 此旗標指出是否要在回應中包含 ai_query 錯誤狀態。
  • modelParameters(選擇性):結構體欄位,其中包含聊天、完成和內嵌模型,parameters 用於提供基礎模型或外部模型的服務。 這些模型 parameters 必須是常數 parameters,而不是數據相依。 當這些模型未被指定為 parameters 或介於 set 到 null 時,將使用預設值。 除了預設值為 temperature0.0 之外,這些模型的預設 valuesparameters 與 Foundation 模型 REST API 參考中所列的預設相同。
  • responseFormat (選擇性):JSON 字串字位,指定您想要模型遵循的回應格式。 支援三種字串型態的回應格式:
    • text
    • json_object
    • json_schema

傳回

來自端點的已剖析回應。

  • 如果 failOnError => true為 ,則函式會傳回與現有行為相同的結果,這是來自端點的已剖析回應。 剖析回應的數據類型是從模型類型、模型 schema 端點或 returnType 函式中的 ai_query 參數推斷而來。
  • 如果 failOnError => false,函式會傳回剖析的回應和錯誤狀態字串作為 STRUCT 物件。
    • 如果資料列的推斷成功,則 errorStatus 欄位是 null
    • 如果資料列的推斷因為模型端點的錯誤而失敗,response 欄位會是 null
    • 如果數據列的推斷因為其他錯誤而失敗,整個查詢就會失敗。
  • 根據 responseFormat中指定的 JSON 字串類型,會傳回下列回應:
    • 針對 responseFormat => '{“type”, “text”}',回應是字串,例如,“Here is the response”
    • 針對 responseFormat => '{“type”, “json_object”}',回應是索引鍵/值組 JSON 字串,例如 {“key”: “value”}
    • 針對 responseFormat => '{“type”, “json_schema”...}',回應是 JSON 字串。 請參閱 範例
  • 如果 failOnError => false 且您已指定 responseFormat,函式會將剖析的回應和錯誤狀態字串當做 STRUCT 物件傳回。

範例

下列範例會指定 json_schema 回應格式:


SELECT
  ai_query(
    "llama-3-1-70b",
    <request>,
    responseFormat =>'{
                        "type": "json_schema",
                        "json_schema":
                          {
                           "name": "research_paper_extraction",
                           "schema":
                             {
                              "type": "object",
                              "properties":
                               {
                                "title": { "type": "string" }
                               }
                             },
                            "strict": true
                          }
                      }'
  )

以下是指定 json_schema 回應格式的範例輸出:

{"title": "<the title of the paper>"}

以下是使用 failOnErrormodelParameters 與的max_tokenstemperature批次推斷範例。 此範例也會示範如何使用 column串連模型的提示和推斷 concat()。 有多種方式可執行串連,例如使用 ||concat()format_string()


CREATE OR REPLACE TABLE ${output_table_name} AS (
  SELECT
      ${input_column_name},
      AI_QUERY(
        "${endpoint}",
        CONCAT("${prompt}", ${input_column_name}),
        failOnError => false,
        modelParameters => named_struct('max_tokens', ${num_output_tokens},'temperature', ${temperature})
      ) as response
    FROM ${input_table_name}
    LIMIT ${input_num_rows}
)

若要查詢服務端點的外部模型:

> 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."

若要查詢 Databricks Foundation 模型 API 所支持的基礎模型:

> SELECT *,
  ai_query(
    'databricks-meta-llama-3-1-70b-instruct',
    "Can you tell me the name of the US state that serves the provided ZIP code? zip code: " || pickup_zip
    )
  FROM samples.nyctaxi.trips
  LIMIT 10

或者,您也可以在 UDF 中包裝 對 的呼叫 ai_query() ,以便呼叫函式,如下所示:

> CREATE FUNCTION correct_grammar(text STRING)
  RETURNS STRING
  RETURN ai_query(
    'databricks-meta-llama-3-1-70b-instruct',
    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
  LIMIT 10

> 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."]}

將 DLT 通道設定為預覽的範例查詢:

> create or replace materialized view
    ai_query_mv
    TBLPROPERTIES('pipelines.channel' = 'PREVIEW') AS
  SELECT
    ai_query("databricks-dbrx-instruct", text) as response
  FROM
    messages
  LIMIT 10;