**Databricks 組み込みAI機能** SQL と PySpark パイプライン(処理工程)に直接 AI 機能を追加できます。モデル(学習済みの予測システム)の実行環境を自分で管理することなく、以下の機能が利用可能です: - **分類・抽出・要約**: ai_classify(分類)、ai_extract(抽出)、ai_summarize(要約) - **データ処理**: ai_mask(マスキング/見えないようにする)、ai_translate(翻訳)、ai_fix_grammar(文法修正)、ai_gen(生成) - **分析**: ai_analyze_sentiment(感情分析)、ai_similarity(類似度判定) - **その他**: ai_forecast(予測) さらに、ドキュメント解析と、カスタム RAG パイプライン(検索可能な独自ナレッジベースの構築)にも対応しています。 次のような場合に使用: SQL や PySpark を使った既存のデータ処理フローに、複雑な AI 処理を簡単に組み込みたいとき
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).
公式ドキュメント: https://docs.databricks.com/large-language-models/ai-functions 関数リファレンス: https://docs.databricks.com/sql/language-manual/functions/
Databricks AI Functions は、データパイプライン内から直接、基盤モデル(汎用性の高い大規模言語モデル)の API を呼び出せる組み込み SQL・PySpark 関数です。モデルの構築、API キーの設定、定型コードの記述が不要です。UPPER() や LENGTH() と同じ感覚でテーブルの列に対して操作でき、大規模なバッチ処理に最適化されています。
3つのカテゴリがあります:
| カテゴリ | 関数 | 使用場面 |
|---|---|---|
| 目的別 | ai_analyze_sentiment、ai_classify、ai_extract、ai_fix_grammar、ai_gen、ai_mask、ai_similarity、ai_summarize、ai_translate、ai_parse_document |
タスクが明確に定義されている場合—常にこれを選ぶ |
| 汎用 | ai_query |
複雑にネストされた JSON、カスタムエンドポイント、複数形式の入出力—最後の手段のみ |
| テーブル値 | ai_forecast |
時系列予測 |
関数選択ルール—常に目的別関数を ai_query より優先する:
| タスク | これを使う | ai_query にフォールバックする場合 |
|---|---|---|
| 感情スコア算出 | ai_analyze_sentiment |
なし |
| 選択肢が固定の分類 | ai_classify(2~500個のラベル;精度向上に説明を追加) |
なし |
| 情報抽出 | ai_extract |
なし |
| 要約 | ai_summarize |
なし—無制限にする場合は max_words=0 |
| 文法修正 | ai_fix_grammar |
なし |
| 翻訳 | ai_translate |
対象言語が対応リストにない場合 |
| 個人識別情報の非表示化 | ai_mask |
なし |
| 自由形式の生成 | ai_gen |
構造化 JSON 出力が必要な場合 |
| 意味的類似度判定 | ai_similarity |
なし |
| PDF・文書解析 | ai_parse_document |
画像レベルの推論が必要な場合 |
| 複雑な JSON・推論処理 | — | ai_query の本来の用途 |
ai_parse_document には DBR 17.1 以上が必須ai_forecast には Pro または Serverless SQL ウェアハウスが必須テキスト列から分類、情報抽出、感情スコア算出を 1 クエリで実行:
SELECT
ticket_id,
ticket_text,
ai_classify(ticket_text, ARRAY('urgent', 'not urgent', 'spam')) AS priority,
ai_extract(ticket_text, '["product", "error_code", "date"]') AS entities,
ai_analyze_sentiment(ticket_text) AS sentiment
FROM support_tickets;
from pyspark.sql.functions import expr
df = spark.table("support_tickets")
df = (
df.withColumn("priority", expr("ai_classify(ticket_text, array('urgent', 'not urgent', 'spam'))"))
.withColumn("entities", expr("ai_extract(ticket_text, '[\"product\", \"error_code\", \"date\"]')"))
.withColumn("sentiment", expr("ai_analyze_sentiment(ticket_text)"))
)
# ai_extract は VARIANT 型(:response 配下にフィールドがある)を返す。コロン(:)記法を使い、ドットはVARIANT では NULL を返す
df.selectExpr("ticket_id", "priority", "sentiment",
"entities:response:product::string AS product",
"entities:response:error_code::string AS error_code",
"entities:response:date::string AS date").display()
複数の目的別関数を連結して、テキスト列を 1 回で拡張:
SELECT
id,
content,
ai_analyze_sentiment(content) AS sentiment,
ai_summarize(content, 30) AS summary,
ai_classify(content,
ARRAY('technical', 'billing', 'other')) AS category,
ai_fix_grammar(content) AS content_clean
FROM raw_feedback;
from pyspark.sql.functions import expr
df_clean = (
spark.table("raw_messages")
.withColumn(
"message_safe",
expr("ai_mask(message, array('person', 'email', 'phone', 'address'))")
)
)
df_clean.write.format("delta").mode("append").saveAsTable("catalog.schema.messages_safe")
PDF・Office 文書を解析し、目的別関数で拡張:
from pyspark.sql.functions import expr
df = (
spark.read.format("binaryFile")
.load("/Volumes/catalog/schema/landing/documents/")
.withColumn("parsed", expr("ai_parse_document(content)"))
# ai_parse_document は VARIANT を返す。コロン(:)で移動し、ドットは使わない
# 構造: { "document": { "pages": [...], "elements": [...] }, "error_status": ..., "metadata": ... }
.selectExpr("path",
"concat_ws('\n', transform(parsed:document:elements, e -> e:content::STRING)) AS text_blocks",
"parsed:error_status AS parse_error")
.filter("parse_error IS NULL")
.withColumn("summary", expr("ai_summarize(text_blocks, 50)"))
.withColumn("entities", expr("ai_extract(text_blocks, '[\"date\", \"amount\", \"vendor\"]')"))
)
-- 似た企業名を検出
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;
ai_query による複雑な JSON 抽出(最後の手段)目的別関数では対応できない、ネストされた配列や複数ステップの推論が必要な出力スキーマの場合のみ使用:
from pyspark.sql.functions import expr, from_json, col
df = (
spark.table("parsed_documents")
.withColumn("ai_response", expr("""
ai_query(
'databricks-claude-sonnet-4',
concat('Extract invoice as JSON with nested itens array: ', text_blocks),
responseFormat => '{"type":"json_object"}',
failOnError => false
)
"""))
.withColumn("invoice", from_json(
col("ai_response.response"),
"STRUCT<numero:STRING, total:DOUBLE, "
"itens:ARRAY<STRUCT<codigo:STRING, descricao:STRING, qtde:DOUBLE, vlrUnit:DOUBLE>>>"
))
)
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
ai_analyze_sentiment、ai_classify、ai_extract、ai_fix_grammar、ai_gen、ai_mask、ai_similarity、ai_summarize、ai_translate)と ai_parse_document の完全な文法、パラメータ、SQL・PySpark サンプルai_query 完全リファレンス:全パラメータ、構造化出力(responseFormat)、複数形式対応(files =>)、UDF パターン、エラー処理ai_forecast パラメータ、単一指標、複数グループ、複数指標、信頼区間パターンconfig.yml 一元管理、関数選択ロジック、カスタム RAG パイプライン(解析→分割→Vector Search)、準リアルタイム版向けの DSPy・LangChain ガイダンス| 問題 | 解決方法 |
|---|---|
ai_parse_document が見つからない |
DBR 17.1 以上が必須。クラスター実行時を確認してください |
ai_forecast が失敗 |
Pro または Serverless SQL ウェアハウスが必須—クラシック版や Starter では使えません |
| すべての関数が NULL を返す | 入力列が NULL です。呼び出す前に WHERE col IS NOT NULL で フィルタリングしてください |
ai_translate が特定の言語で失敗 |
対応言語(8 言語):英語(en)、フランス語(fr)、ドイツ語(de)、ヒンディー語(hi)、イタリア語(it)、ポルトガル語(pt)、スペイン語(es)、タイ語(th)—to_lang はコードまたは言語名を指定(詳細は references/1-task-functions.md を参照)。その他の言語には多言語モデルで ai_query を使用してください |
ai_classify が予期しないラベルを返す |
ラベル名をより明確で相互排他的にしてください。ラベルを少なく(2~5 個)すると精度が向上します |
バッチジョブ中に ai_query が一部行で エラーを発生 |
failOnError => false を追加—.response と .errorMessage を持つ STRUCT を返すようになります(エラー発生ではなく) |
| バッチジョブが遅い | DBR 15.4 ML LTS クラスターを使用してください(サーバーレスや対話型ではなく)—バッチ推論スループットが最適化されます |
| パイプラインコードを編集せずモデルを切り替えたい | すべてのモデル名とプロンプトを config.yml に格納—パターンは references/4-document-processing-pipeline.md を参照してください |
Official Docs: https://docs.databricks.com/large-language-models/ai-functions Individual function reference: https://docs.databricks.com/sql/language-manual/functions/
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 UPPER() or LENGTH(), and are optimized for batch inference at scale.
Always prefer a task-specific function over ai_query. Reach for ai_query only when no task function fits (custom/external endpoints, multimodal, or JSON beyond ai_extract'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.
Cost & 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 |
|---|---|---|---|---|---|
ai_analyze_sentiment |
Sentiment scoring | content STRING |
STRING — positive/negative/neutral/mixed, or NULL |
— | ↗ |
ai_classify |
Fixed-label routing | content STRING|VARIANT, labels (2–500), [options MAP] |
VARIANT — {response:[label], error_message} |
— | ↗ |
ai_extract |
Entity / field extraction | content STRING|VARIANT, schema STRING (JSON), [options MAP] |
VARIANT — {response:{…}, error_message, metadata} |
≤256 fields, ≤12 nesting levels | ↗ |
ai_fix_grammar |
Grammar correction | content STRING |
STRING (corrected) |
— | ↗ |
ai_gen |
Free-form generation | prompt STRING |
STRING |
— | ↗ |
ai_mask |
PII redaction | content STRING, labels ARRAY<STRING> |
STRING (entities → [MASKED]) |
— | ↗ |
ai_similarity |
Semantic similarity | expr1 STRING, expr2 STRING |
FLOAT (0.0–1.0) |
— | ↗ |
ai_summarize |
Summarization | content STRING, [max_words INT] (0 = uncapped) |
STRING |
Public Preview; English-tuned | ↗ |
ai_translate |
Translation | content STRING, to_lang STRING |
STRING |
Langs: en, fr, de, hi, it, pt, es, th | ↗ |
ai_parse_document |
Parse PDF / Office / images | content BINARY, [Map('version','2.0', …)] |
VARIANT — pages, elements, error_status |
DBR 17.3+; ≤500 pages / 100 MB | ↗ |
ai_prep_search |
RAG chunking from parsed docs | parsed VARIANT, [options MAP] |
VARIANT — {document:{contents, pages, source_uri}, error_status} |
DBR 18.2+ (serverless env v3+) | ↗ |
ai_query |
Any serving endpoint (built-in foundation or custom), multimodal, complex JSON (last resort) | endpoint STRING, request STRING|STRUCT, [returnType], [failOnError BOOL], [modelParameters STRUCT], [responseFormat STRING], [files] |
Parsed response; with failOnError => false a STRUCT{response, errorMessage} |
Pro/Serverless warehouse; CAN QUERY on endpoint |
↗ |
ai_forecast |
Time series forecasting (table-valued) | observed TABLE, horizon, time_col, value_col, [group_col], [prediction_interval_width], [frequency], [seed], [parameters] |
Rows: time/group cols + per value {v}_forecast, {v}_upper, {v}_lower (DOUBLE) |
Pro/Serverless warehouse; Public Preview | ↗ |
Models run under Apache 2.0 or LLAMA 3.3 Community License — you are responsible for compliance.
Chain task functions to enrich a column in one pass. ai_classify/ai_extract return a VARIANT — read it with the colon operator (:response):
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 expr(...): df.withColumn("category", expr("ai_classify(content, '[\"a\",\"b\"]', map('version','2.0')):response[0]::STRING")) — and read VARIANT fields via selectExpr("col:response:field::STRING AS field").
PII redaction before storage — ai_mask(content, ARRAY(entity_types)) returns text with entities → [MASKED].
SELECT ai_mask(message, array('person','email','phone','address')) AS message_safe FROM raw_messages;
Semantic matching / dedup — ai_similarity returns 0–1; self-join and threshold:
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:
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_lower
Nested JSON via ai_query (last resort — only past ai_extract's limits) — parse the response with from_json. Model names, multimodal files =>, modelParameters, SQL UDF → 2-ai-query.md:
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 (ai_parse_document) and RAG chunking (ai_prep_search) get their own staged pipeline below.
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) — CREATE OR REFRESH STREAMING TABLE with STREAM(...) sources. To run the same logic standalone in a notebook / SQL warehouse, swap each CREATE OR REFRESH STREAMING TABLE x AS for CREATE OR REPLACE TABLE x AS and drop the STREAM(...) wrappers. In SDP Python it's @dp.table with from 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
);
In a batch job, route the per-row error to a sidecar table instead of letting it crash the run: keep ai_extract's result:error_message (VARIANT, colon-accessed, as above), and for ai_query pass failOnError => false and check ai_response.errorMessage (a STRUCT field, dot-accessed). See 2-ai-query.md.
For retrieval rather than field extraction: ai_parse_document → ai_prep_search (semantic chunking + context enrichment, DBR 18.2+) → Vector Search Delta Sync index. ai_prep_search returns chunk_id, chunk_to_retrieve, and chunk_to_embed (enriched with title/headers/page) — embed chunk_to_embed, return chunk_to_retrieve to the LLM. Shown standalone; in an SDP swap CREATE OR REPLACE TABLE for CREATE OR REFRESH STREAMING TABLE + STREAM 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;
Then enable CDF (ALTER TABLE parsed_chunks SET TBLPROPERTIES (delta.enableChangeDataFeed = true)) and use the databricks-vector-search skill to build a Delta Sync index: PK chunk_id, embedding source chunk_to_embed, return chunk_to_retrieve.
Beyond batch:
ai_parse_document job (checkpoints, trigger(availableNow=True)), see databricks/bundle-examples · job_with_ai_parse_document.ai_extract v2.1 citations + confidence scores, ai_classify multilabel, ai_parse_document options + output schema, ai_prep_search chunk schema) and non-trivial examples. The Overview table above links to each function's section directly.ai_query complete reference: all parameters, structured output with responseFormat, multimodal files =>, UDF patterns, and error handlingai_forecast parameters, single-metric, multi-group, multi-metric, and confidence interval patterns| Issue | Solution |
|---|---|
ai_parse_document not found |
Requires DBR 17.3+. Check cluster runtime. |
ai_prep_search not found |
Requires DBR 18.2+ (serverless env v3+). |
explode() fails on a VARIANT |
explode needs ARRAY — cast first: explode(variant_get(prep, '$.document.contents', 'ARRAY<VARIANT>')). |
| Embedding the wrong RAG column | Embed chunk_to_embed (context-enriched); return chunk_to_retrieve to the LLM. |
ai_forecast fails |
Requires Pro or Serverless SQL warehouse — not available on Classic or Starter. |
| All functions return NULL | Input column is NULL. Filter with WHERE col IS NOT NULL before calling. |
ai_translate fails for a language |
Supported (8): English (en), French (fr), German (de), Hindi (hi), Italian (it), Portuguese (pt), Spanish (es), Thai (th) — to_lang takes the code or the full name (see references/1-task-functions.md). Use ai_query with a multilingual model for others. |
ai_classify returns unexpected labels |
Use clear, mutually exclusive label names. Fewer labels (2–5) produces more reliable results. |
ai_query raises on some rows in a batch job |
Add failOnError => false — returns a STRUCT with .response and .errorMessage (dot-accessed) instead of raising. |
| Batch job runs slowly | Use DBR 15.4 ML LTS cluster (not serverless or interactive) for optimized batch inference throughput. |
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。