CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 3 · Lesson 20/45

    AI functions and ai_query for pipeline enrichment and classification

    Apply AI functions, including ai_query, to perform model inference within data pipelines for enrichment and classification tasks.

    19 min read
    3% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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?

    Sources12

    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.

    Enriching every row with a model answer: the instruction and the column are concatenated into one prompt stringsql
    > 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 10

    The 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 10

    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?

    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.

    A traditional ML classifier called with a feature STRUCT and an explicit return typesql
    > 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

    returnType 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.

    How the endpoint type changes the shape of an ai_query call
    Endpoint typerequestHow output type is setSetup needed
    Databricks-hosted foundation model (system.ai)STRING promptresponseFormat (chat models only)None; no endpoint provisioning
    External model endpointSTRING promptresponseFormat (chat models only)Create an external model serving endpoint
    Custom traditional ML / DL modelSingle column or STRUCT matching input feature namesreturnType, or inferred from the model schema on 15.2+Create a custom model serving endpoint
    Fine-tuned foundation modelSTRING promptresponseFormat (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?

    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)

    0 of 3 selected

    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.

    Forcing a chat model's answer into a fixed STRUCT with a DDL-style responseFormatsql
    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.

    One failing row no longer stops the querysql
    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?

    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?

    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.

    Chaining two task-specific functions: sentiment filters the rows, ai_classify explains the negativessql
    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.

    Extracting invoice fields into a keyed responsesql
    > 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"

    Sources45

    6.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.

    Where AI Function inference cost lands
    FunctionExtra inference costsystem.billing.usage product
    ai_query on a Databricks-hosted modelYes, billed like task-specific functionsMODEL_SERVING, BATCH_INFERENCE offering
    ai_query on a custom or provisioned throughput endpointBilled as that endpoint's dedicated serving computeBilled by that endpoint
    ai_summarize, ai_translate, ai_analyze_sentiment, ai_maskYes, serverless GPU via Model ServingMODEL_SERVING, BATCH_INFERENCE offering
    ai_classify, ai_extract, ai_parse_documentYesAI_FUNCTIONS
    ai_forecast, ai_predict_classNo; runs on the submitting computeNone 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?

    Sources21

    Sources

    (5)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 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. 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

    Spotted a mistake, or was something unclear? Tell us.