---
title: Use ai_query
description: Learn how to use ai\_query, the general-purpose AI Function that queries any supported model directly from SQL or Python on Databricks.
canonical_url: https://docs.databricks.com/gcp/en/large-language-models/ai-query
---

# Use `ai_query`

`ai_query` is a general-purpose [AI Function](https://docs.databricks.com/gcp/en/large-language-models/ai-functions.md) that lets you query any supported AI model directly from SQL or Python. Unlike task-specific AI Functions, which are purpose-built and optimized for a single task, `ai_query` gives you full control over the model, prompt, and parameters.

For full syntax and parameter reference, see [`ai_query` function](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md).

## Requirements

* This function is not available on Classic SQL warehouses.
* Databricks Runtime 15.4 LTS or above is required. For an upcoming change to this requirement, see [AI Functions require Databricks Runtime 17.3 LTS or above](https://docs.databricks.com/gcp/en/release-notes/whats-coming.md#ai-functions-runtime-support). Databricks Runtime 18.2 or above is recommended for the best performance and access to the latest features.

## <a id="when-to-use" /> When to use `ai_query`

Databricks recommends starting with a [task-specific AI Function](https://docs.databricks.com/gcp/en/large-language-models/ai-functions.md) when one matches your objective. Use `ai_query` when a task-specific function doesn't meet your needs. For example, when you need to:

* Control the prompt, model parameters, or output format more precisely
* Query a custom, fine-tuned, or external model
* Need flexibility to further optimize for throughput or quality

![Decision tree for task-specific AI functions and ai\_query](https://docs.databricks.com/gcp/en/images/generative-ai/ai-function-decision-tree.svg)

## Best practices

* **Use Databricks-hosted models.** Use `system.ai` model services instead of provisioned throughput endpoints. These model services are fully managed and scale automatically without provisioning or configuration.
* **Select a model optimized for batch inference.** Databricks optimizes specific models for high-throughput batch workloads. Using a non-optimized model can result in reduced throughput and longer job completion times. See [ Supported models](https://docs.databricks.com/gcp/en/large-language-models/ai-query.md#supported-models) for the full list of batch-optimized models.
* **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.
* **Set `failOnError` to `false` for large workloads.** This allows the job to complete and return error messages for failed rows, so you retain successful results without reprocessing the entire dataset.

## Unity Gateway governance

`ai_query` requests to `system.ai` model services (for example, `system.ai.gpt-5-4`) are automatically routed through [Unity Gateway](https://docs.databricks.com/gcp/en/ai-gateway/index.md). Model services that you create in Unity Gateway are not yet supported. Only a subset of Unity Gateway features applies to routed requests:

* **Supported**: [usage tracking](https://docs.databricks.com/gcp/en/ai-gateway/usage-tracking.md), [budget](https://docs.databricks.com/gcp/en/ai-gateway/budgets.md) integration (including hard spend caps), and permission checks on the model service.
* **Not supported**: guardrails (service policies), inference tables, tracing tables, rate limits, fallbacks, and external model providers.

See [Query endpoints with `ai_query`](https://docs.databricks.com/gcp/en/ai-gateway/query-model-services.md#ai-query) for details.

## <a id="supported-models" /> Supported models

`ai_query` supports Databricks-hosted models, provisioned throughput models, custom models, and external models.

The following table summarizes the supported model types, the associated models, and model serving endpoint configuration requirements for each.

| Type                              | Description                                                                                                                                                                                                                                                                                                                        | Supported models                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Requirements                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Databricks-hosted models          | Databricks hosts these foundation models and offers `system.ai` model services that you can query using `ai_query`. See [Model availability by region](https://docs.databricks.com/gcp/en/unity-gateway/model-region-availability.md) for which models are supported for each Model Serving feature and their region availability. | See [Databricks-hosted inference](https://docs.databricks.com/gcp/en/machine-learning/model-serving/foundation-model-overview.md) for the full list of supported foundation models on Model Serving. These models are supported and optimized for getting started with batch inference and production workflows:<br /><ul><li>`system.ai.gpt-5-2`</li><li>`system.ai.gpt-5-1`</li><li>`system.ai.gpt-5`</li><li>`system.ai.gpt-5-mini`</li><li>`system.ai.gpt-5-nano`</li><li>`system.ai.gpt-5-5`</li><li>`system.ai.gpt-5-4-mini`</li><li>`system.ai.gpt-5-4-nano`</li><li>`system.ai.gemini-3-1-pro`</li><li>`system.ai.gemini-3-flash`</li><li>`system.ai.gemini-3-5-flash`</li><li>`system.ai.gemini-3-1-flash-lite`</li><li>`system.ai.gpt-6-2-astra`</li><li>`system.ai.gpt-6-2-sol`</li><li>`system.ai.databricks-gpt-6-1-sol`</li><li>`system.ai.databricks-gpt-6-sol`</li><li>`system.ai.databricks-gpt-6-luna`</li><li>`system.ai.databricks-gpt-6-astra`</li><li>`system.ai.databricks-gpt-5-6-sol`</li><li>`system.ai.databricks-gpt-5-6-terra`</li><li>`system.ai.databricks-gpt-5-4`</li><li>`system.ai.databricks-gemini-3-8-flash`</li><li>`system.ai.databricks-gemini-3-7-flash`</li><li>`system.ai.databricks-gemini-3-5-flash-lite`</li><li>`system.ai.databricks-claude-fable-5-2`</li><li>`system.ai.databricks-claude-fable-5-1`</li><li>`system.ai.databricks-claude-fable-5`</li><li>`system.ai.databricks-claude-opus-5-5`</li><li>`system.ai.databricks-claude-opus-5`</li><li>`system.ai.databricks-claude-sonnet-5-5`</li><li>`system.ai.databricks-claude-sonnet-5`</li><li>`system.ai.databricks-claude-haiku-5-5`</li><li>`system.ai.databricks-grok-4-6`</li><li>`system.ai.qwen35-122b-a10b`</li><li>`system.ai.qwen3-next-80b-a3b-instruct`</li><li>`system.ai.claude-opus-4-8`</li><li>`system.ai.claude-opus-4-7`</li><li>`system.ai.claude-opus-4-6`</li><li>`system.ai.claude-sonnet-4-6`</li><li>`system.ai.gpt-oss-20b`</li><li>`system.ai.gpt-oss-120b`</li><li>`system.ai.gemma-3-12b`</li><li>`system.ai.llama-4-maverick`</li><li>`system.ai.meta-llama-3-3-70b-instruct`</li><li>`system.ai.meta-llama-3-1-8b-instruct`</li><li>`system.ai.qwen3-embedding-0-6b`</li><li>`system.ai.gte-large-en`</li></ul><br />Other Databricks-hosted models are available for use with AI Functions, but are not recommended for batch inference production workflows at scale. These other models are made available for real-time inference using [Foundation Model APIs pay-per-token](https://docs.databricks.com/gcp/en/machine-learning/foundation-model-apis/index.md#). | Databricks Runtime 15.4 LTS or above is required to use this functionality. For an upcoming change to this requirement, see [AI Functions require Databricks Runtime 17.3 LTS or above](https://docs.databricks.com/gcp/en/release-notes/whats-coming.md#ai-functions-runtime-support). Requires no endpoint provisioning or configuration. Your use of these models is subject to the [Applicable model terms](https://docs.databricks.com/gcp/en/machine-learning/model-serving/acceptable-use-models.md) and AI Functions [region availability](https://docs.databricks.com/gcp/en/resources/feature-region-support.md). |
| Provisioned throughput models     | AI Functions works with provisioned throughput models deployed on Model Serving.                                                                                                                                                                                                                                                   | <ul><li>Fine-tuned foundation models deployed on Model Serving</li><li>Provisioned throughput models deployed on Model Serving</li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | <ul><li>For fine-tuned foundation models, you must [create a provisioned throughput endpoint](https://docs.databricks.com/gcp/en/machine-learning/foundation-model-apis/deploy-prov-throughput-foundation-model-apis.md) in Model Serving. See [ Use `ai_query` with foundation models](https://docs.databricks.com/gcp/en/large-language-models/ai-query.md#foundation-model) for notebook examples.</li><li>AI Functions does not use the compute provisioned to the endpoint. AI Functions fully manages the scaling used for batch inference.</li></ul>                                                                 |
| Custom models and external models | You can bring your own custom or external models and query them using AI Functions. AI Functions offers flexibility so you can query models for real-time inference or batch inference scenarios.                                                                                                                                  | <ul><li>Foundation models hosted outside of Databricks. These models are made available using [external models](https://docs.databricks.com/gcp/en/machine-learning/foundation-models/external-models/index.md). See [Access foundation models hosted outside of Databricks](https://docs.databricks.com/gcp/en/machine-learning/model-serving/foundation-model-endpoints-legacy.md#external-model) for a list of supported external models.</li><li>Custom traditional ML and DL models</li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | <ul><li>For external models, you must [create an external model serving endpoint](https://docs.databricks.com/gcp/en/machine-learning/model-serving/create-foundation-model-endpoints.md#ext-model-endpoint).</li><li>For custom traditional ML and DL models, you must [create a custom model serving endpoint](https://docs.databricks.com/gcp/en/machine-learning/model-serving/create-manage-serving-endpoints.md). See [ Use `ai_query` with traditional ML models](https://docs.databricks.com/gcp/en/large-language-models/ai-query.md#custom-model) for a notebook example.</li></ul>                               |

## <a id="foundation-model" /> Use `ai_query` with foundation models

The following example demonstrates how to use `ai_query` with a foundation model hosted by Databricks.

* See [`ai_query` function](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md) for syntax details and parameters.
* See [ Multimodal inputs](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md#multimodal) for multimodal input query examples.
* See [ Examples for advanced scenarios](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md#advanced) for guidance on how to configure parameters for advanced use cases such as:
  * [Handle errors using `failOnError`](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md#errors)
  * [Structured outputs on Databricks](https://docs.databricks.com/gcp/en/machine-learning/model-serving/structured-outputs.md) for how to specify structured output for your query responses.

### SQL

```sql
SELECT text, ai_query(
    "system.ai.gpt-oss-120b",
    "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
) AS summary
FROM uc_catalog.schema.table;
```

### Python

```python
df_out = df.selectExpr(
  "ai_query('system.ai.gpt-oss-120b', CONCAT('Please provide a summary of the following text: ', text), modelParameters => named_struct('max_tokens', 100, 'temperature', 0.7)) as summary"
)
df_out.write.mode("overwrite").saveAsTable('output_table')
```

### Example notebook: Batch inference and structured data extraction

The following example notebook demonstrates how to perform basic structured data extraction using `ai_query` to transform raw, unstructured data into organized, usable information through automated extraction techniques. This notebook also shows how to leverage Agent Evaluation to evaluate the accuracy using ground truth data.

#### Batch inference and structured data extraction notebook

[Get notebook](https://docs.databricks.com/notebooks/source/generative-ai/simple_structured_data_extraction_ai_query.html)

## <a id="custom-model" /> Use `ai_query` with traditional ML models

`ai_query` supports traditional ML models, including fully custom ones. These models must be deployed on Model Serving endpoints. For syntax details and parameters, see [`ai_query` function](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query.md).

```sql
SELECT text, ai_query(
  endpoint => "spam-classification",
  request => named_struct(
    "timestamp", timestamp,
    "sender", from_number,
    "text", text),
  returnType => "BOOLEAN") AS is_spam
FROM catalog.schema.inbox_messages
LIMIT 10
```

### Example notebook: Batch inference using BERT for named entity recognition

The following notebook shows a traditional ML model batch inference example using BERT.

#### Batch inference using BERT for named entity recognition notebook

[Get notebook](https://docs.databricks.com/notebooks/source/machine-learning/bert-batch-inference-ai-query.html)
