適用於:
Databricks SQL
Databricks Runtime
叫用現有的 Azure Databricks 模型服務端點 ,並剖析並傳回其回應。
ai_query 是一般用途 的 AI 函數 ,可讓您查詢現有端點以取得即時推論或批次推論工作負載。
- 請參閱 一般用途功能:
ai_query以取得支援的模型和必要的端點組態。 - 您也可以用來
ai_query查詢部署在 ML 模型服務端點上的 AI 代理程式,請參閱 查詢已部署的 Mosaic AI 代理程式 - 若要
ai_query在生產工作流程中使用,請參閱 部署批次推斷管線。
需求
此函數不適用於 Azure Databricks SQL Classic。
您必須啟用 Azure Private Link ,才能在 Pro SQL 倉儲上使用這項功能。
建議使用 Databricks Runtime 15.4 LTS 或更新版本。 使用 Databricks Runtime 15.3 或更低版本可能會導致效能速度變慢。
您的工作區必須位於支援的 模型服務區域中。
現有模型服務端點,並已載入模型。 如果您使用 Databricks 裝載的基礎模型,則會為您建立端點。 否則,請參閱 建立提供端點的自定義模型 或 建立服務端點的基礎模型。
預設會啟用查詢基礎模型 API。 若要查詢用於自訂模型或外部模型的端點:
- 在 Databricks 預覽 UI 中啟用自定義模型和外部模型的 AI_Query。
目前的 Lakeflow Spark 宣告式管線倉儲通道不會使用支援
ai_query()的最新 Databricks Runtime 版本。 在資料表屬性中,將pipelines.channel設定為'preview'以使用ai_query()。> create or replace materialized view ai_query_mv TBLPROPERTIES('pipelines.channel' = 'PREVIEW') AS SELECT ai_query("databricks-meta-llama-3-3-70b-instruct", text) as response FROM messages LIMIT 10;
Syntax
若要查詢提供 基礎模型的端點:
ai_query(endpoint, request)
若要查詢自訂模型服務端點,請使用 模型架構:
ai_query(endpoint, request)
若要在沒有模型架構的情況下查詢提供端點的自定義模型:
ai_query(endpoint, request, returnType, failOnError)
參數和返回值
| Argument | Description | Returns |
|---|---|---|
endpoint |
Databricks Foundation Model 服務端點的名稱、外部模型服務端點或相同工作區中的自定義模型端點,以 STRING 字面量方式調用。 定義器必須具有端點 CAN QUERY 許可權。 |
|
request |
用來叫用端點做為表達式的要求。
|
|
returnType |
(Databricks Runtime 15.2 和更新版本的選擇性)端點的預期 returnType 運算式。 這類似於函數中的from_json模式參數,它同時接受STRING函數的schema_of_json表達式或調用。
responseFormat使用 參數來指定聊天基礎模型的回應格式。 |
|
failOnError |
(選擇性)預設值為 true 的布爾常值。 需要 Databricks Runtime 15.3 或更新版本。 此旗標指出是否要在回應中包含 ai_query 錯誤狀態。如需範例,請參閱使用 failOnError處理錯誤。 |
下列是根據 failOnError 案例的傳回行為描述。
|
modelParameters |
(選擇性)結構字段,其中包含用於服務基礎模型或外部模型的聊天、完成和內嵌模型參數。 這些模型參數必須是常數參數,而不是數據相依。
如需範例,請參閱傳遞模型參數來設定模型。 |
|
responseFormat |
(選擇性)指定您希望聊天基礎模型遵循的回應格式。
如需範例,請參閱 使用結構化輸出強制執行輸出架構 。 |
下列描述在指定failOnError的時候,也設定responseFormat時會發生什麼情況:
|
files |
(選用)使用 files=>content指定要在多模態輸入請求中使用的檔案和內容。
files 是模型預期的多模態輸入參數名稱,並 content 參考 DataFrame 中的資料行,其中包含您要在查詢中使用的影像檔案的二進位內容。
|
範例:查詢基礎模型
若要查詢服務端點的外部模型:
> 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-3-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
或者,您也可以將 ai_query() 的呼叫包裹在 UDF 中,以便於函式撥打,如下所示:
CREATE FUNCTION correct_grammar(text STRING)
RETURNS STRING
RETURN ai_query(
'databricks-meta-llama-3-3-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;
多模態輸入
ai_query 原生支援多模態影像輸入。 如需支援的 Databricks 裝載視覺模型,請參閱 基礎模型類型 。
以下是支援的輸入類型:
JPEGPNG
下列範例示範如何查詢 Databricks 基礎模型 API 支援的基礎模型,以取得多模式輸入。 在此範例中,參數 files => content 用於將影像檔案資料傳遞至 ai_query
-
files:模型預期的多模態輸入參數名稱 -
content:經由READ_FILES傳回的 DataFrame 中的某一欄,其包含影像檔案的二進位內容。
> SELECT *, ai_query(
'databricks-llama-4-maverick',
'what is this image about?', files => content)
as output FROM READ_FILES("/Volumes/main/multimodal/unstructured/image.jpeg");
若要查詢由 Databricks 基礎模型 API 所支援的基礎模型,以進行多模態輸入,並指定結構化的輸出:
> SELECT *, ai_query(
'databricks-llama-4-maverick', 'What is interesting or important about this image?',
responseFormat => ‘{
"type": "json_schema",
"json_schema": {
"name": "output",
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"num_people": {"type": "integer"},
"num_animals": {"type": "integer"},
"interesting_fact": {"type": "string"},
"possible_context": {"type": "string"}
}
},
"strict": true
}
}’,
files => content
)
as output FROM READ_FILES("/Volumes/main/user/volume1/image.jpeg");
範例:查詢傳統 ML 模型
若要查詢自訂模型或提供端點的傳統 ML 模型:
> 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
進階案例的範例
下列各節提供進階使用案例的範例,例如錯誤處理以及如何將 ai_query 整合至使用者定義的函式中。
傳遞一個訊息陣列
下列範例示範如何使用ai_query將訊息陣列傳遞至模型或代理程式應用程式。
> SELECT ai_query(
'custom-llama-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."]}
串連提示和推斷欄
串連提示和推斷數據行的方法有很多種,例如使用 ||、CONCAT()或 format_string():
SELECT
CONCAT('${prompt}', ${input_column_name}) AS concatenated_prompt
FROM ${input_table_name};
Alternatively:
SELECT
'${prompt}' || ${input_column_name} AS concatenated_prompt
FROM ${input_table_name};
或使用 format_string():
SELECT
format_string('%s%s', '${prompt}', ${input_column_name}) AS concatenated_prompt
FROM ${input_table_name};
傳遞模型參數來設定模型
傳遞特定參數,例如最大令牌和溫度,以自定義模型行為。 例如:
SELECT text, ai_query(
"databricks-meta-llama-3-3-70b-instruct",
"Please summarize the following article: " || text,
modelParameters => named_struct('max_tokens', 100, 'temperature', 0.7)
) AS summary
FROM uc_catalog.schema.table;
使用 failOnError 處理錯誤
使用 failOnError 的 ai_query 自變數來處理錯誤。 下列範例示範如何確定如果一個數據列發生錯誤,就不會停止整個查詢執行。 請參閱參數與回傳,以了解這個參數設定方式下的預期行為。
SELECT text, ai_query(
"databricks-meta-llama-3-3-70b-instruct",
"Summarize the given text comprehensively, covering key points and main ideas concisely while retaining relevant details and examples. Ensure clarity and accuracy without unnecessary repetition or omissions: " || text,
failOnError => false
) AS summary
FROM uc_catalog.schema.table;
使用結構化輸出強制執行輸出架構
請確保輸出符合特定的結構,以便使用responseFormat進行下游處理更為順利。 請參閱 Azure Databricks 上的結構化輸出。
下列範例會強制執行 DDL 樣式 JSON 字串架構:
SELECT ai_query(
"databricks-gpt-oss-20b",
"Extract research paper details from the following abstract: " || abstract,
responseFormat => 'STRUCT<research_paper_extraction:STRUCT<title:STRING, authors:ARRAY<STRING>, abstract:STRING, keywords:ARRAY<STRING>>>'
)
FROM research_papers;
或者,使用 JSON 架構回應格式:
SELECT ai_query(
"databricks-gpt-oss-20b",
"Extract research paper details from the following abstract: " || abstract,
responseFormat => '{
"type": "json_schema",
"json_schema": {
"name": "research_paper_extraction",
"schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"authors": {"type": "array", "items": {"type": "string"}},
"abstract": {"type": "string"},
"keywords": {"type": "array", "items": {"type": "string"}}
}
},
"strict": true
}
}'
)
FROM research_papers;
預期的輸出可能如下所示:
{ "title": "Understanding AI Functions in Databricks", "authors": ["Alice Smith", "Bob Jones"], "abstract": "This paper explains how AI functions can be integrated into data workflows.", "keywords": ["Databricks", "AI", "LLM"] }
在使用者定義函式中使用 ai_query
您可以將對 ai_query 的呼叫包裝在一個 UDF 中,這樣可以讓您輕鬆地在不同的工作流程中使用和共享這些函式。
CREATE FUNCTION correct_grammar(text STRING)
RETURNS STRING
RETURN ai_query(
'databricks-meta-llama-3-3-70b-instruct',
CONCAT('Correct this to standard English:\n', text));
GRANT EXECUTE ON correct_grammar TO ds;
SELECT
* EXCEPT text,
correct_grammar(text) AS text
FROM articles;