What you will be able to do
- Choose between a task-specific AI Function and ai_query for an enrichment or classification step
- Write a correct ai_query call for a Databricks-hosted foundation model and for a custom model serving endpoint
- Use responseFormat, returnType and failOnError to shape output and keep a large batch running when single rows fail
- Classify and extract fields with ai_classify and ai_extract, and read their VARIANT output
- Size batch inference for throughput and attribute its cost in system.billing.usage
Key concept
ai_query — A SQL function that sends each row's request to an existing Model Serving endpoint and returns the parsed response as a column. The endpoint type decides how you build the request (a prompt STRING or a feature STRUCT) and how you set the output type (responseFormat or returnType).
1.Two kinds of AI Functions, and where they run
AI Functions are built-in SQL functions that run a model over every row of a query. With them, a pipeline step can label a support ticket, pull an invoice number out of free text, or summarise a review, and you never leave SQL or set up a separate serving client. They run from Databricks SQL, notebooks, Lakeflow pipelines and Workflows. For large batches, Databricks also supports them inside Structured Streaming, so an enrichment column can sit in the same streaming table definition you would build with Lakeflow Declarative Pipelines and Auto Loader.
There are two families. Task-specific functions such as ai_classify, ai_extract, ai_analyze_sentiment, ai_summarize and ai_translate each do one job, run on Databricks-managed models and need no prompt engineering. The general-purpose function, ai_query, lets you choose the model, write the prompt, set the parameters and define the output format. Databricks recommends starting with a task-specific function whenever one fits the job. Reach for ai_query when you need tighter control of the prompt or output format, when you need to call a custom, fine-tuned or external model, or when you need room to tune for throughput or quality.
Two limits apply to both families. AI Functions are not available on Classic SQL warehouses, and they need Databricks Runtime 15.4 LTS or above. Databricks recommends 18.2 or above for performance. A job that works in a serverless SQL warehouse can fail on a classic warehouse for this reason alone.
Checkpoint 1 of 9· Check yourself
A pipeline step must label each incoming support ticket with one of the team's own categories (billing, defect, account). No particular model is required, and the team wants the simplest option that needs no prompt engineering. Which approach fits best?
Classifying against your own labels is a fixed task, and a task-specific function covers it. It runs on a Databricks-managed model and needs no prompt. Choose ai_query only when you need control of the model, prompt or output format, or need a custom or external model.
“Databricks recommends starting with a task-specific AI Function when one matches your objective.”Source: docs.databricks.com
2.Calling a hosted foundation model with ai_query
When the endpoint is a chat foundation model, the request is a single STRING, and that string is the whole prompt. The function signature is just ai_query(endpoint, request). The endpoint is a string literal that names the model service. Databricks-hosted models are exposed as system.ai services, for example system.ai.meta-llama-3-3-70b-instruct, and they need no endpoint provisioning. The request must be a STRING for Foundation Model APIs endpoints and external model endpoints.
> SELECT *,
ai_query(
'system.ai.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 10The model only ever receives that string, so the task itself has to be written into it. To get a sentiment label out of a ticket column, prepend an instruction such as "Classify sentiment as positive, negative, or neutral: " and append the column with ||, CONCAT() or format_string(). Passing the bare column sends text with no task attached. Wrapping the column in named_struct is the request shape for custom model endpoints, not for chat models. There are no arguments called model_input or output_type. The named arguments are endpoint, request, returnType, failOnError, modelParameters, responseFormat and files.
modelParameters takes a struct such as named_struct('max_tokens', 100, 'temperature', 0.7). The values must be constants, not values that depend on the row's data. To reuse one prompt across teams, wrap the call in a SQL function and grant EXECUTE on it. The mechanics of that are covered under Unity Catalog SQL functions.
Checkpoint 2 of 9· Fill the gap
This query adds a model answer to every taxi trip by calling a Databricks-hosted chat model. Which token goes in the blank so that the endpoint gets a valid request?
> SELECT *,
ai_query(
'system.ai.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 10A Foundation Model APIs endpoint takes one STRING request, so || joins the instruction and the column into a single prompt. A comma would pass pickup_zip as a separate argument, which would not reach the model as part of the prompt. + and AND are numeric and boolean operators, not string concatenation.
Checkpoint 3 of 9· Exam question
A data engineer needs to enrich a Delta table of customer support tickets with a sentiment label generated by a Databricks-hosted foundation model, calling the model directly from a Spark SQL query inside a nightly batch job. The ticket_text column holds free-form text. Which SQL expression correctly returns a sentiment label using ai_query against the pay-per-token system.ai/llama-4-70b endpoint?
Correct answer: A — ai_query('system.ai/llama-4-70b', 'Classify sentiment as positive, negative, or neutral: ' || ticket_text) AS sentiment
- A. Foundation model endpoints take a single STRING request; concatenating an explicit instruction with the column value produces a prompt the model can act on to return a sentiment label.
- B. A named_struct request is the pattern for custom model-serving endpoints that expose named input features; pay-per-token foundation model endpoints expect a plain STRING prompt, so this call would not classify correctly.
- C. Passing the raw column value with no instruction text gives the model nothing to classify against, so even though the returnType and failOnError syntax is valid, the model has no directive to produce a sentiment label.
- D.
model_inputis not a recognized ai_query parameter name; ai_query's parameters areendpointandrequest, so this call raises an error rather than running.
Sources3
3.Calling custom and traditional ML endpoints
A custom model serving endpoint expects features, not a prompt. Here the request can be a single column or a STRUCT, and the STRUCT's field names must match the input feature names the endpoint expects. A model logged with the inputs ticket_text and queue_name is called with named_struct('ticket_text', ticket_text, 'queue_name', queue_name). You write the endpoint's bare name, because it has to be an endpoint in the same workspace. You don't add a URL.
> 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 10returnType works like the schema argument of from_json. On Databricks Runtime 15.2 and above it is optional for endpoints that carry a logged model schema, because ai_query infers the return type from that schema. On 15.1 and below you must supply it to query a custom endpoint. For each call, the definer needs CAN QUERY permission on the endpoint. In a scheduled pipeline, that is whichever identity owns the query. Querying custom and external endpoints is enabled by default in supported regions, so a permission error against one usually means the endpoint grant is missing or an admin has disabled the feature.
| Endpoint type | request | How output type is set | Setup needed |
|---|---|---|---|
| Databricks-hosted foundation model (system.ai) | STRING prompt | responseFormat (chat models only) | None; no endpoint provisioning |
| External model endpoint | STRING prompt | responseFormat (chat models only) | Create an external model serving endpoint |
| Custom traditional ML / DL model | Single column or STRUCT matching input feature names | returnType, or inferred from the model schema on 15.2+ | Create a custom model serving endpoint |
| Fine-tuned foundation model | STRING prompt | responseFormat (chat models only) | Create a provisioned throughput endpoint |
Checkpoint 4 of 9· Check yourself
Your churn model is served from a custom model serving endpoint named 'churn-model' in the same workspace. It was logged with the input features tenure and plan. The source table's columns are tenure_months and plan_type. Which request argument correctly calls this endpoint from ai_query?
A custom endpoint expects features, not a prompt. The STRUCT's field names must match the model's input feature names (tenure, plan), not the table's column names. The endpoint is given by its bare name in the same workspace, not by a URL. A concatenated prompt string is the request shape for foundation model and external endpoints.
“The STRUCT field names should match the input feature names expected by the endpoint.”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A team deployed a custom fine-tuned classification model to a Databricks model-serving endpoint named ticket_priority_classifier, whose logged model signature expects two input features, ticket_text and queue_name. They want to call it from ai_query inside a Lakeflow pipeline to enrich an incoming streaming table. Which of the following are true about calling this endpoint correctly with ai_query?(Select 3)
Correct answers: A, B, C — The request argument must be a STRUCT such as named_struct('ticket_text', ticket_text, 'queue_name', queue_name), with field names matching the endpoint's logged input features.; The calling user or service principal must hold CAN QUERY permission on the ticket_priority_classifier endpoint, or the call is rejected at the permissions layer.; On a sufficiently recent Databricks Runtime, ai_query can infer the returnType from the endpoint's logged model schema, making explicit returnType optional rather than mandatory.
- A. Custom endpoints backed by a model with named input features expect a STRUCT request whose field names line up with those features, exactly as named_struct produces here.
- B. ai_query enforces standard model-serving permissions, so the caller needs CAN QUERY on the target endpoint before the SQL call is allowed to reach it.
- C. On newer runtimes ai_query reads the endpoint's logged model schema to infer the return type automatically, which is why returnType became optional rather than required in every case.
- D. Flattening every request into a STRING is the foundation and external-model pattern; custom endpoints with named features specifically require the STRUCT form so field names map correctly.
- E. ai_query is precisely the mechanism for reaching model-serving endpoints, including custom ones, from SQL and DataFrame code without going through the REST API directly.
- F. ai_query takes the bare endpoint name registered in the same workspace, not a fully qualified URL; prefixing it with a workspace address is not valid syntax.
Sources3
4.Structured output and row-level failure handling
A free-text answer is hard to put in a column, so for chat models responseFormat constrains what the model returns. It accepts a DDL-style string or a JSON string of type text, json_object or json_schema. It works only with chat foundation models. For custom endpoints, returnType does that job instead.
SELECT ai_query(
"system.ai.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;failOnError defaults to true. With that default, one row that the endpoint rejects, such as a payload that violates the input schema, fails the whole statement and the job with it. Setting failOnError => false changes the return type. Each row then gets a STRUCT holding the parsed response and an error message. On success the error message is null. When the endpoint fails, the response is null and the message says why. The bad rows stay in the output, where you can count them, filter them or route them aside, and the successful million rows are kept.
SELECT text, ai_query(
"system.ai.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;This protection covers only model endpoint errors. If a row fails for any other reason, the whole query still fails. Other fixes don't help either. A LIMIT lowers the odds of hitting a bad row without handling it. More provisioned throughput makes calls faster but cannot make an invalid payload valid. A Python try/except sits outside the SQL engine's model call and never sees the error.
Checkpoint 6 of 9· Check yourself
A nightly job uses ai_query to add a summary to two million rows. It keeps failing because the endpoint rejects one row whose payload violates the input schema. Which change lets the job finish while keeping a record of the bad rows?
With failOnError => false, endpoint errors no longer fail the query. The return type changes to a STRUCT holding the parsed response and an error message, so you can count, filter or route the failed rows. More throughput cannot make an invalid payload valid. A Python try/except sits outside the SQL engine's model call and never sees the row-level error.
“If failOnError => false, the function returns a STRUCT object that contains the parsed response and the error message string.”Source: docs.databricks.com
Checkpoint 7 of 9· Exam question
A nightly job calls ai_query against a custom sentiment-classification model endpoint for one million support tickets. On some rows the payload violates the endpoint's input schema, and the current default configuration makes the whole SQL statement — and the job — fail as soon as one bad row is hit. Which change lets the job finish, capturing failures per row without aborting the whole batch?
Correct answer: A — Set failOnError => false in the ai_query call so it returns a STRUCT with response and errorMessage fields, letting failed rows surface a null result instead of aborting.
- A.
failOnError => falseis exactly for this situation: it makes ai_query return a STRUCT with a response and an errorMessage instead of raising, so the query completes and individual failures are captured for later inspection. - B. ai_query runs as a SQL built-in evaluated inside the query engine, not inside a Python UDF, so wrapping unrelated Python code in try/except does not intercept the SQL-level model invocation errors.
- C. Provisioned throughput controls request capacity and latency, not schema validation, so faster serving does not stop rows with malformed payloads from erroring out.
- D. Limiting the batch size changes how many rows are processed per run but does not remove malformed rows from the data, so the same schema violation still aborts the statement whenever it is reached.
Sources3
5.Classification and extraction with ai_classify and ai_extract
ai_classify(content, labels [, options]) assigns labels you define without any prompt writing. Labels are passed as a STRING. That can be a JSON array such as '["urgent", "not_urgent"]', or a JSON object that maps each label to a description. The descriptions improve accuracy for cases such as support routing. The labels string can also come from a column, so the label set can live in a Delta table. Version 2.x allows 2 to 500 labels, compared with 20 in version 1.0. It also accepts VARIANT input from upstream functions such as ai_parse_document.
SELECT
review,
ai_classify(
review,
'["Arrives too late", "Wrong size", "Wrong color", "Dislike the style"]'
) AS reason
FROM
product_reviews
WHERE
ai_analyze_sentiment(review) = "negative"The options map controls behaviour. Keys include version, instructions (a global description of the task and domain), multilabel ("true" returns every label that applies), and the version 2.1 flags enableConfidenceScores and enableRationales. Pin the version with options => map('version', '2.1'). When nothing is pinned, the default depends on the input types and falls back to 1.0, which returns a plain STRING.
Version 2.x returns a VARIANT that holds a response array, a metadata object and an error_message. Under 2.1, each element of the response array is an object with a value key, not a bare label string. A query written for 2.0 output therefore breaks on 2.1, even when no new options are turned on. The function returns NULL when the content is NULL or cannot be classified, so a pipeline should expect nulls in the label column. Reading fields out of that VARIANT uses the techniques for querying VARIANT data.
ai_extract pulls structured fields out of text against a schema you define. Pass a JSON array of field names, or an object that gives each field a type and description, and every field comes back keyed by name.
> SELECT ai_extract(
'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
'["invoice_id", "vendor_name", "total_amount", "invoice_date"]',
options => map('version', '2.1')
);Checkpoint 8 of 9· Fill the gap
Only negative product reviews should get a reason label from the team's own list of causes. Which function belongs in the WHERE clause so that ai_classify runs only on those rows?
SELECT
review,
ai_classify(
review,
'["Arrives too late", "Wrong size", "Wrong color", "Dislike the style"]'
) AS reason
FROM
product_reviews
WHERE
? (review) = "negative"This query chains two task-specific functions. ai_analyze_sentiment returns a sentiment label for each review, so it can filter the rows down to the negative ones, and ai_classify then assigns a reason from the custom labels. ai_classify needs a labels argument, ai_extract needs a schema, and ai_summarize returns free text, so none of them returns a plain "negative" to compare against.
Source: docs.databricks.com6.Throughput and cost of batch inference
AI Functions handle parallelization, retries and scaling themselves, so throughput comes from giving them the whole dataset. Submit the full table in a single query. Splitting it into small manual batches can reduce throughput. Choose a model on the batch-optimized list, such as system.ai.gpt-5-mini or system.ai.meta-llama-3-3-70b-instruct. Other hosted models work, but they are meant for real-time pay-per-token use and finish large jobs more slowly. For long runs, also set failOnError => false so a few bad rows don't force you to reprocess everything.
For batch work, Databricks recommends system.ai model services over provisioned throughput endpoints, because the services are fully managed and scale without any configuration. Scaling and billing are separate questions for a provisioned throughput endpoint: AI Functions decides how batch inference scales instead of drawing on the compute provisioned to that endpoint, yet ai_query is still billed for the Model Serving endpoint you name, and provisioned throughput endpoints are billed as dedicated serving compute. Calls from ai_query to system.ai services pass through Unity Gateway. That gives usage tracking, budget integration with hard spend caps, and permission checks. It doesn't give guardrails, inference tables, rate limits or fallbacks.
Two bills accrue. The compute that runs the query, whether a SQL warehouse, job cluster or pipeline, is always billed. Most functions add a model inference charge on top of it.
| Function | Extra inference cost | system.billing.usage product |
|---|---|---|
| ai_query on a Databricks-hosted model | Yes, billed like task-specific functions | MODEL_SERVING, BATCH_INFERENCE offering |
| ai_query on a custom or provisioned throughput endpoint | Billed as that endpoint's dedicated serving compute | Billed by that endpoint |
| ai_summarize, ai_translate, ai_analyze_sentiment, ai_mask | Yes, serverless GPU via Model Serving | MODEL_SERVING, BATCH_INFERENCE offering |
| ai_classify, ai_extract, ai_parse_document | Yes | AI_FUNCTIONS |
| ai_forecast, ai_predict_class | No; runs on the submitting compute | None separate |
Because of this split, a cost review that filters only on the MODEL_SERVING product misses ai_classify and ai_extract spend. The filtering itself belongs to billing system tables. Progress is visible while a run is going. In the query profile, the AI Query entry shows how many inferences completed and how many failed, and the total time taken. That is the quickest way to tell a slow model from a failing one.
Checkpoint 9 of 9· Check yourself
An engineer needs 30 million product descriptions enriched with ai_query. To speed things up, they split the table into 300 slices of 100,000 rows and run one ai_query statement per slice. Which change best raises throughput?
AI Functions handle parallelization, retries and scaling themselves, so throughput comes from giving them the full dataset in one query. Splitting it manually can lower throughput. For batch inference, AI Functions doesn't use an endpoint's provisioned compute, and system.ai model services are the recommended choice. failOnError => false protects successful rows from a few bad ones, but it does not speed anything up.
“Submit your full dataset in a single query. AI Functions automatically handle parallelization, retries, and scaling. Manually splitting data into small batches can reduce throughput.”Source: docs.databricks.com
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“They can be run from Databricks SQL, notebooks, Lakeflow pipelines, and Workflows.”
↩︎ Two kinds of AI Functions, and where they run“you can integrate task-specific AI Functions, or the general-purpose function ai_query into your production workflows, like Lakeflow pipelines, Databricks workflows and Structured Streaming.”
↩︎ Two kinds of AI Functions, and where they run“ai_query is billed for the Model Serving endpoint you specify.”
↩︎ Throughput and cost of batch inference“The compute that runs your query is always billed, for example a SQL warehouse or job cluster.”
↩︎ Throughput and cost of batch inference“Click AI Query to see metrics for that particular query including the number of completed and failed inferences”
↩︎ Throughput and cost of batch inference - 2.
“Databricks recommends starting with a task-specific AI Function when one matches your objective.”
↩︎ Two kinds of AI Functions, and where they run“Manually splitting data into small batches can reduce throughput.”
↩︎ Throughput and cost of batch inference“AI Functions fully manages the scaling used for batch inference.”
↩︎ Throughput and cost of batch inference“Supported: usage tracking, budget integration (including hard spend caps), and permission checks on the model service.”
↩︎ Throughput and cost of batch inference“Manually splitting data into small batches can reduce throughput.”
↩︎ Exam trap 3“AI Functions does not use the compute provisioned to the endpoint.”
↩︎ Prediction“Submit your full dataset in a single query. AI Functions automatically handle parallelization, retries, and scaling. Manually splitting data into small batches can reduce throughput.”
↩︎ Checkpoint - 3.
“If the endpoint is an external model serving endpoint or Databricks Foundation Model APIs endpoint, the request must be a STRING.”
↩︎ Calling a hosted foundation model with ai_query“The STRUCT field names should match the input feature names expected by the endpoint.”
↩︎ Calling custom and traditional ML endpoints“The definer must have CAN QUERY permission on the endpoint.”
↩︎ Calling custom and traditional ML endpoints“If it is not provided, ai_query() automatically infers the return type from the model schema of the custom model serving endpoint.”
↩︎ Calling custom and traditional ML endpoints“If failOnError => false, the function returns a STRUCT object that contains the parsed response and the error message string.”
↩︎ Structured output and row-level failure handling“Only available for querying chat foundation models.”
↩︎ Structured output and row-level failure handling“Invokes an existing Databricks Model Serving endpoint and parses and returns its response.”
↩︎ Key concept“If the endpoint is an external model serving endpoint or Databricks Foundation Model APIs endpoint, the request must be a STRING.”
↩︎ Exam trap 1“If the inference of the row fails due to other errors, the whole query fails.”
↩︎ Exam trap 2“With the exception of temperature which has a default value of 0.0”
↩︎ Prediction - 4.
“Up to 500 labels, compared to 20 in version 1.0”
↩︎ Classification and extraction with ai_classify and ai_extract“Returns NULL if content is NULL or if the content cannot be classified.”
↩︎ Classification and extraction with ai_classify and ai_extract“Moving from version 2.0 to 2.1 is not output-compatible.”
↩︎ Exam trap 4 - 5.
“Field names and types match the schema definition”
↩︎ Classification and extraction with ai_classify and ai_extract