databricks-ai-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDatabricks AI Functions
Databricks AI Functions
Official Docs: https://docs.databricks.com/large-language-models/ai-functions Individual function reference: https://docs.databricks.com/sql/language-manual/functions/
Overview
概述
Databricks AI Functions are built-in SQL and PySpark functions that call Foundation Model APIs directly from your data pipelines — no model endpoint setup, no API keys, no boilerplate. They operate on table columns as naturally as or , and are optimized for batch inference at scale.
UPPER()LENGTH()Always prefer a task-specific function over . Reach for only when no task function fits (custom/external endpoints, multimodal, or JSON beyond 's limits). Every function below shares a baseline: DBR 15.1+ (notebooks) / 15.4 ML LTS (batch), not on SQL Warehouse Classic, and region must support AI Functions — the Prereqs column lists only what's additional.
ai_queryai_queryai_extractCost & speed — each call is an LLM inference (slow and billed per token). Run a function once per row and persist the result to a Delta table; never re-invoke it on every downstream query. In demos, avoid generating tables with millions of rows — sample the input when needed so the demo runs quickly. Materialize once, then query the cheap Delta output.
The Function column links to the in-repo deep reference (full options, schemas, examples); Docs links to the official page.
| Function | Task | Input | Output | Extra prereqs | Docs |
|---|---|---|---|---|---|
| Sentiment scoring | | | — | ↗ |
| Fixed-label routing | | | — | ↗ |
| Entity / field extraction | | | ≤256 fields, ≤12 nesting levels | ↗ |
| Grammar correction | | | — | ↗ |
| Free-form generation | | | — | ↗ |
| PII redaction | | | — | ↗ |
| Semantic similarity | | | — | ↗ |
| Summarization | | | Public Preview; English-tuned | ↗ |
| Translation | | | Langs: en, fr, de, hi, it, pt, es, th | ↗ |
| Parse PDF / Office / images | | | DBR 17.3+; ≤500 pages / 100 MB | ↗ |
| RAG chunking from parsed docs | | | DBR 18.2+ (serverless env v3+) | ↗ |
| Any serving endpoint (built-in foundation or custom), multimodal, complex JSON (last resort) | | Parsed response; with | Pro/Serverless warehouse; | ↗ |
| Time series forecasting (table-valued) | | Rows: time/group cols + per value | Pro/Serverless warehouse; Public Preview | ↗ |
Models run under Apache 2.0 or LLAMA 3.3 Community License — you are responsible for compliance.
Databricks AI Functions是内置的SQL和PySpark函数,可直接从数据流水线中调用Foundation Model API——无需设置模型端点、无需API密钥、无需冗余代码。它们像或一样自然地作用于表列,并且针对大规模批量推理进行了优化。
UPPER()LENGTH()优先使用特定任务函数而非。 仅当没有合适的任务函数时才使用(自定义/外部端点、多模态或超出限制的JSON)。以下所有函数都有基线要求:DBR 15.1+(笔记本)/ 15.4 ML LTS(批量),不支持SQL Warehouse Classic,且区域必须支持AI Functions——“额外 prerequisites”列仅列出额外要求。
ai_queryai_queryai_extract成本与速度——每次调用都是一次LLM推理(速度慢且按token计费)。 对每行数据仅运行一次函数,并将结果持久化到Delta表中;切勿在每个下游查询中重新调用。在演示中,避免生成包含数百万行的表——必要时对输入进行采样,以便演示快速运行。先物化结果,再查询低成本的Delta输出。
“Function”列链接到仓库内的详细参考(完整选项、模式、示例);“Docs”列链接到官方页面。
| 函数 | 任务 | 输入 | 输出 | 额外 prerequisites | 文档 |
|---|---|---|---|---|---|
| 情感评分 | | | — | ↗ |
| 固定标签路由 | | | — | ↗ |
| 实体/字段提取 | | | ≤256个字段,≤12层嵌套 | ↗ |
| 语法修正 | | | — | ↗ |
| 自由格式生成 | | | — | ↗ |
| PII脱敏 | | | — | ↗ |
| 语义相似度 | | | — | ↗ |
| 文本摘要 | | | 公开预览版;针对英文优化 | ↗ |
| 文本翻译 | | | 支持语言:en、fr、de、hi、it、pt、es、th | ↗ |
| PDF/Office/图片解析 | | | DBR 17.3+;≤500页/100 MB | ↗ |
| 解析文档的RAG分块 | | | DBR 18.2+(serverless环境v3+) | ↗ |
| 任意服务端点(内置基础模型或自定义模型)、多模态、复杂JSON(最后选择) | | 解析后的响应;当 | Pro/Serverless仓库;对端点拥有 | ↗ |
| 时间序列预测(表值函数) | | 行数据:时间/分组列 + 每个值对应的 | Pro/Serverless仓库;公开预览版 | ↗ |
模型基于Apache 2.0或LLAMA 3.3社区许可证运行——您需负责合规性。
Patterns
使用模式
Chain task functions to enrich a column in one pass. / return a VARIANT — read it with the colon operator ():
ai_classifyai_extract:responsesql
SELECT id,
ai_analyze_sentiment(content) AS sentiment,
ai_summarize(content, 30) AS summary,
ai_classify(content, '["technical","billing","other"]', map('version','2.0')):response[0]::STRING AS category,
ai_extract(content, '["product","error_code","date"]', map('version','2.0')):response:product::STRING AS product,
ai_fix_grammar(content) AS content_clean
FROM raw_feedback;In PySpark, call any of these inside : — and read VARIANT fields via .
expr(...)df.withColumn("category", expr("ai_classify(content, '[\"a\",\"b\"]', map('version','2.0')):response[0]::STRING"))selectExpr("col:response:field::STRING AS field")PII redaction before storage — returns text with entities → .
ai_mask(content, ARRAY(entity_types))[MASKED]sql
SELECT ai_mask(message, array('person','email','phone','address')) AS message_safe FROM raw_messages;Semantic matching / dedup — returns 0–1; self-join and threshold:
ai_similaritysql
SELECT a.id, b.id, ai_similarity(a.name, b.name) AS score
FROM companies a JOIN companies b ON a.id < b.id
WHERE ai_similarity(a.name, b.name) > 0.85;Forecasting — table-valued; one row per future period (+ per group). Full param/group/interval forms → 3-ai-forecast.md:
sql
SELECT * FROM ai_forecast(
observed => TABLE(SELECT date, sales FROM daily_sales),
horizon => '2026-12-31', time_col => 'date', value_col => 'sales');
-- Returns: date, sales_forecast, sales_upper, sales_lowerNested JSON via (last resort — only past 's limits) — parse the response with . Model names, multimodal , , SQL UDF → 2-ai-query.md:
ai_queryai_extractfrom_jsonfiles =>modelParameterssql
SELECT from_json(
ai_query('databricks-claude-sonnet-4',
concat('Extract invoice as JSON with nested line_items array: ', text_blocks),
responseFormat => '{"type":"json_object"}', failOnError => false).response,
'STRUCT<numero:STRING, total:DOUBLE, line_items:ARRAY<STRUCT<code:STRING, qty:DOUBLE>>>'
) AS invoice
FROM parsed_documents;Document parsing () and RAG chunking () get their own staged pipeline below.
ai_parse_documentai_prep_search链式调用任务函数,一次性丰富列数据。 /返回VARIANT类型——使用冒号运算符()读取:
ai_classifyai_extract:responsesql
SELECT id,
ai_analyze_sentiment(content) AS sentiment,
ai_summarize(content, 30) AS summary,
ai_classify(content, '["technical","billing","other"]', map('version','2.0')):response[0]::STRING AS category,
ai_extract(content, '["product","error_code","date"]', map('version','2.0')):response:product::STRING AS product,
ai_fix_grammar(content) AS content_clean
FROM raw_feedback;在PySpark中,可在内调用任意上述函数:——并通过读取VARIANT字段。
expr(...)df.withColumn("category", expr("ai_classify(content, '[\"a\",\"b\"]', map('version','2.0')):response[0]::STRING"))selectExpr("col:response:field::STRING AS field")存储前进行PII脱敏——返回实体替换为的文本。
ai_mask(content, ARRAY(entity_types))[MASKED]sql
SELECT ai_mask(message, array('person','email','phone','address')) AS message_safe FROM raw_messages;语义匹配/去重——返回0–1之间的值;自连接并设置阈值:
ai_similaritysql
SELECT a.id, b.id, ai_similarity(a.name, b.name) AS score
FROM companies a JOIN companies b ON a.id < b.id
WHERE ai_similarity(a.name, b.name) > 0.85;预测——表值函数;每个未来周期(+每个分组)对应一行数据。完整参数/分组/区间形式请查看→ 3-ai-forecast.md:
sql
SELECT * FROM ai_forecast(
observed => TABLE(SELECT date, sales FROM daily_sales),
horizon => '2026-12-31', time_col => 'date', value_col => 'sales');
-- 返回:date, sales_forecast, sales_upper, sales_lower通过处理嵌套JSON(最后选择——仅当超出限制时使用)——使用解析响应。模型名称、多模态、、SQL UDF请查看→ 2-ai-query.md:
ai_queryai_extractfrom_jsonfiles =>modelParameterssql
SELECT from_json(
ai_query('databricks-claude-sonnet-4',
concat('Extract invoice as JSON with nested line_items array: ', text_blocks),
responseFormat => '{"type":"json_object"}', failOnError => false).response,
'STRUCT<numero:STRING, total:DOUBLE, line_items:ARRAY<STRUCT<code:STRING, qty:DOUBLE>>>'
) AS invoice
FROM parsed_documents;文档解析()和RAG分块()的流水线将在下方单独介绍。
ai_parse_documentai_prep_searchDocument Processing Pipeline
文档处理流水线
Chain AI Functions stage-by-stage into Delta tables for batch document processing. The example is written as a Spark Declarative Pipeline (SDP / Lakeflow / DLT) — with sources. To run the same logic standalone in a notebook / SQL warehouse, swap each for and drop the wrappers. In SDP Python it's with .
CREATE OR REFRESH STREAMING TABLESTREAM(...)CREATE OR REFRESH STREAMING TABLE x ASCREATE OR REPLACE TABLE x ASSTREAM(...)@dp.tablefrom pyspark import pipelines as dpsql
-- Stage 1 — parse binary docs (any type), filter parse errors
CREATE OR REFRESH STREAMING TABLE raw_parsed AS
SELECT path,
concat_ws('\n', transform(parsed:document:elements, e -> e:content::STRING)) AS text_blocks,
parsed:error_status AS parse_error
FROM (
SELECT path, ai_parse_document(content, map('version','2.0')) AS parsed
FROM STREAM read_files('/Volumes/my_catalog/doc_processing/landing/', format => 'binaryFile')
)
WHERE parsed:error_status IS NULL;
-- Stage 2 — classify document type (cheap, no endpoint selection)
CREATE OR REFRESH STREAMING TABLE classified_docs AS
SELECT *,
ai_classify(text_blocks, '["invoice","purchase_order","receipt","contract","other"]', map('version','2.0')):response[0]::STRING AS doc_type
FROM STREAM raw_parsed;
-- Stage 3 — extract fields; ai_extract returns a VARIANT, read fields with `:`
CREATE OR REFRESH STREAMING TABLE extracted AS
SELECT path, doc_type,
result:response:invoice_number::STRING AS invoice_number,
result:response:vendor_name::STRING AS vendor_name,
result:response:total_amount::DOUBLE AS total_amount,
result:error_message::STRING AS extract_error
FROM (
SELECT *, ai_extract(text_blocks,
'{"invoice_number":{"type":"string"},"vendor_name":{"type":"string"},"total_amount":{"type":"number"}}',
map('version','2.0')) AS result
FROM STREAM classified_docs WHERE doc_type = 'invoice' AND text_blocks IS NOT NULL
);In a batch job, route the per-row error to a sidecar table instead of letting it crash the run: keep 's (VARIANT, colon-accessed, as above), and for pass and check (a STRUCT field, dot-accessed). See 2-ai-query.md.
ai_extractresult:error_messageai_queryfailOnError => falseai_response.errorMessage将AI Functions按阶段链式调用,构建Delta表以进行批量文档处理。示例以Spark声明式流水线(SDP / Lakeflow / DLT)编写——使用和源。要在笔记本/SQL仓库中单独运行相同逻辑,请将每个替换为并移除包装器。在SDP Python中则使用搭配。
CREATE OR REFRESH STREAMING TABLESTREAM(...)CREATE OR REFRESH STREAMING TABLE x ASCREATE OR REPLACE TABLE x ASSTREAM(...)@dp.tablefrom pyspark import pipelines as dpsql
-- 阶段1 — 解析二进制文档(任意类型),过滤解析错误
CREATE OR REFRESH STREAMING TABLE raw_parsed AS
SELECT path,
concat_ws('\n', transform(parsed:document:elements, e -> e:content::STRING)) AS text_blocks,
parsed:error_status AS parse_error
FROM (
SELECT path, ai_parse_document(content, map('version','2.0')) AS parsed
FROM STREAM read_files('/Volumes/my_catalog/doc_processing/landing/', format => 'binaryFile')
)
WHERE parsed:error_status IS NULL;
-- 阶段2 — 对文档类型进行分类(低成本,无需选择端点)
CREATE OR REFRESH STREAMING TABLE classified_docs AS
SELECT *,
ai_classify(text_blocks, '["invoice","purchase_order","receipt","contract","other"]', map('version','2.0')):response[0]::STRING AS doc_type
FROM STREAM raw_parsed;
-- 阶段3 — 提取字段;ai_extract返回VARIANT类型,使用`:`读取字段
CREATE OR REFRESH STREAMING TABLE extracted AS
SELECT path, doc_type,
result:response:invoice_number::STRING AS invoice_number,
result:response:vendor_name::STRING AS vendor_name,
result:response:total_amount::DOUBLE AS total_amount,
result:error_message::STRING AS extract_error
FROM (
SELECT *, ai_extract(text_blocks,
'{"invoice_number":{"type":"string"},"vendor_name":{"type":"string"},"total_amount":{"type":"number"}}',
map('version','2.0')) AS result
FROM STREAM classified_docs WHERE doc_type = 'invoice' AND text_blocks IS NOT NULL
);在批量作业中,将每行的错误路由到副表,而非让作业崩溃:保留的(VARIANT类型,通过冒号访问,如上所示),对于则传入并检查(STRUCT字段,通过点访问)。请查看2-ai-query.md。
ai_extractresult:error_messageai_queryfailOnError => falseai_response.errorMessageCustom RAG Pipeline — Parse → Prep → Index
自定义RAG流水线 — 解析→预处理→索引
For retrieval rather than field extraction: → (semantic chunking + context enrichment, DBR 18.2+) → Vector Search Delta Sync index. returns , , and (enriched with title/headers/page) — embed , return to the LLM. Shown standalone; in an SDP swap for + .
ai_parse_documentai_prep_searchai_prep_searchchunk_idchunk_to_retrievechunk_to_embedchunk_to_embedchunk_to_retrieveCREATE OR REPLACE TABLECREATE OR REFRESH STREAMING TABLESTREAM read_files(...)sql
CREATE OR REPLACE TABLE parsed_chunks AS
WITH prepped AS (
SELECT path AS source_path, ai_prep_search(ai_parse_document(content)) AS prep
FROM read_files('/Volumes/my_catalog/doc_processing/docs/', format => 'binaryFile')
)
SELECT
variant_get(chunk, '$.chunk_id', 'STRING') AS chunk_id,
variant_get(chunk, '$.chunk_to_retrieve', 'STRING') AS chunk_to_retrieve,
variant_get(chunk, '$.chunk_to_embed', 'STRING') AS chunk_to_embed,
source_path
FROM prepped LATERAL VIEW explode(variant_get(prep, '$.document.contents', 'ARRAY<VARIANT>')) c AS chunk;Then enable CDF () and use the databricks-vector-search skill to build a Delta Sync index: PK , embedding source , return .
ALTER TABLE parsed_chunks SET TBLPROPERTIES (delta.enableChangeDataFeed = true)chunk_idchunk_to_embedchunk_to_retrieveBeyond batch:
- Ask questions over the output — point a Genie Agent at the resulting Delta table for natural-language querying instead of hand-written SQL; see the databricks-genie-agents skill.
- Low-latency / serving — to expose this as a real-time, governed endpoint (e.g. register a model to Unity Catalog and serve it), use the databricks-model-serving skill.
- Production incremental ingestion — for a runnable end-to-end streaming job (checkpoints,
ai_parse_document), see databricks/bundle-examples · job_with_ai_parse_document.trigger(availableNow=True)
如果是用于检索而非字段提取: → (语义分块+上下文增强,DBR 18.2+)→ Vector Search Delta Sync索引。返回、和(包含标题/页眉/页码的增强内容)——对进行嵌入,将返回给LLM。以下为独立运行示例;在SDP中请将替换为 + 。
ai_parse_documentai_prep_searchai_prep_searchchunk_idchunk_to_retrievechunk_to_embedchunk_to_embedchunk_to_retrieveCREATE OR REPLACE TABLECREATE OR REFRESH STREAMING TABLESTREAM read_files(...)sql
CREATE OR REPLACE TABLE parsed_chunks AS
WITH prepped AS (
SELECT path AS source_path, ai_prep_search(ai_parse_document(content)) AS prep
FROM read_files('/Volumes/my_catalog/doc_processing/docs/', format => 'binaryFile')
)
SELECT
variant_get(chunk, '$.chunk_id', 'STRING') AS chunk_id,
variant_get(chunk, '$.chunk_to_retrieve', 'STRING') AS chunk_to_retrieve,
variant_get(chunk, '$.chunk_to_embed', 'STRING') AS chunk_to_embed,
source_path
FROM prepped LATERAL VIEW explode(variant_get(prep, '$.document.contents', 'ARRAY<VARIANT>')) c AS chunk;然后启用CDF(),并使用**databricks-vector-search**技能构建Delta Sync索引:主键,嵌入源,返回。
ALTER TABLE parsed_chunks SET TBLPROPERTIES (delta.enableChangeDataFeed = true)chunk_idchunk_to_embedchunk_to_retrieve超越批量处理:
- 对输出进行提问——将Genie Agent指向生成的Delta表,通过自然语言查询而非手写SQL;请查看**databricks-genie-agents**技能。
- 低延迟/服务化——要将其作为实时、受管控的端点暴露(例如将模型注册到Unity Catalog并提供服务),请使用**databricks-model-serving**技能。
- 生产级增量 ingestion——如需可运行的端到端流式作业(包含检查点、
ai_parse_document),请查看databricks/bundle-examples · job_with_ai_parse_document。trigger(availableNow=True)
Reference Files
参考文件
- 1-task-functions.md — Deep reference for every task-specific function: full options/schemas (e.g. v2.1 citations + confidence scores,
ai_extractmultilabel,ai_classifyoptions + output schema,ai_parse_documentchunk schema) and non-trivial examples. The Overview table above links to each function's section directly.ai_prep_search - 2-ai-query.md — complete reference: all parameters, structured output with
ai_query, multimodalresponseFormat, UDF patterns, and error handlingfiles => - 3-ai-forecast.md — parameters, single-metric, multi-group, multi-metric, and confidence interval patterns
ai_forecast
- 1-task-functions.md — 所有特定任务函数的详细参考:完整选项/模式(例如v2.1引用+置信度分数、
ai_extract多标签、ai_classify选项+输出模式、ai_parse_document分块模式)和非 trivial 示例。上方的概述表格直接链接到每个函数的章节。ai_prep_search - 2-ai-query.md — 完整参考:所有参数、使用
ai_query的结构化输出、多模态responseFormat、UDF模式和错误处理files => - 3-ai-forecast.md — 参数、单指标、多分组、多指标和置信区间模式
ai_forecast
Common Issues
常见问题
| Issue | Solution |
|---|---|
| Requires DBR 17.3+. Check cluster runtime. |
| Requires DBR 18.2+ (serverless env v3+). |
| |
| Embedding the wrong RAG column | Embed |
| Requires Pro or Serverless SQL warehouse — not available on Classic or Starter. |
| All functions return NULL | Input column is NULL. Filter with |
| Supported (8): English ( |
| Use clear, mutually exclusive label names. Fewer labels (2–5) produces more reliable results. |
| Add |
| Batch job runs slowly | Use DBR 15.4 ML LTS cluster (not serverless or interactive) for optimized batch inference throughput. |
| 问题 | 解决方案 |
|---|---|
| 需要DBR 17.3+。检查集群运行时版本。 |
| 需要DBR 18.2+(serverless环境v3+)。 |
| |
| 嵌入了错误的RAG列 | 对 |
| 需要Pro或Serverless SQL仓库——不支持Classic或Starter版本。 |
| 所有函数返回NULL | 输入列为NULL。调用前使用 |
| 支持8种语言:英语( |
| 使用清晰、互斥的标签名称。标签数量越少(2–5个),结果越可靠。 |
| 添加 |
| 批量作业运行缓慢 | 使用DBR 15.4 ML LTS集群(而非serverless或交互式集群)以优化批量推理吞吐量。 |