Loading...
Loading...
Use Databricks built-in AI Functions (ai_classify, ai_extract, ai_summarize, ai_mask, ai_translate, ai_fix_grammar, ai_gen, ai_analyze_sentiment, ai_similarity, ai_parse_document, ai_prep_search, ai_query, ai_forecast) to add AI capabilities directly to SQL and PySpark pipelines without managing model endpoints. Also covers document parsing and building custom RAG pipelines (parse → prep_search → index → query).
npx skill4agent add databricks/databricks-agent-skills databricks-ai-functionsOfficial Docs: https://docs.databricks.com/large-language-models/ai-functions Individual function reference: https://docs.databricks.com/sql/language-manual/functions/
UPPER()LENGTH()ai_queryai_queryai_extract| 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 | ↗ |
ai_classifyai_extract:responseSELECT 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;expr(...)df.withColumn("category", expr("ai_classify(content, '[\"a\",\"b\"]', map('version','2.0')):response[0]::STRING"))selectExpr("col:response:field::STRING AS field")ai_mask(content, ARRAY(entity_types))[MASKED]SELECT ai_mask(message, array('person','email','phone','address')) AS message_safe FROM raw_messages;ai_similaritySELECT 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;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_lowerai_queryai_extractfrom_jsonfiles =>modelParametersSELECT 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;ai_parse_documentai_prep_searchCREATE OR REFRESH STREAMING TABLESTREAM(...)CREATE OR REFRESH STREAMING TABLE x ASCREATE OR REPLACE TABLE x ASSTREAM(...)@dp.tablefrom pyspark import pipelines as dp-- 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
);ai_extractresult:error_messageai_queryfailOnError => falseai_response.errorMessageai_parse_documentai_prep_searchai_prep_searchchunk_idchunk_to_retrievechunk_to_embedchunk_to_embedchunk_to_retrieveCREATE OR REPLACE TABLECREATE OR REFRESH STREAMING TABLESTREAM read_files(...)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;ALTER TABLE parsed_chunks SET TBLPROPERTIES (delta.enableChangeDataFeed = true)chunk_idchunk_to_embedchunk_to_retrieveai_parse_documenttrigger(availableNow=True)ai_extractai_classifyai_parse_documentai_prep_searchai_queryresponseFormatfiles =>ai_forecast| 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. |