> ## Documentation Index
> Fetch the complete documentation index at: https://docs.narrative.io/llms.txt
> Use this file to discover all available pages before exploring further.

# AI & ML Functions

> LLM inference and custom model predictions: AI_COMPLETE, CALL_MODEL_FUNCTION

## AI and ML functions

These functions run AI and machine learning operations directly within your query, enabling LLM inference, custom model predictions, and AI-powered data enrichment at scale.

<Note>
  AI and ML functions are currently available on **Snowflake data planes only**. They are not supported on AWS-hosted data planes.
</Note>

### AI\_COMPLETE

Sends a prompt to a large language model and returns the response as a JSON string. Use `AI_COMPLETE` to enrich, classify, or extract structured data from text columns without leaving NQL.

**Syntax:**

```sql theme={null}
AI_COMPLETE(model, prompt, model_parameters, response_format, show_details)
```

**Parameters:**

| Parameter          | Type             | Description                                                                                                                                  |
| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`            | STRING           | The model identifier to use (e.g., `'openai-gpt-5'`). Available models depend on your Snowflake Cortex configuration.                        |
| `prompt`           | column reference | A column containing the prompt text. Must be a column reference—string literals are not supported. Build prompts in a CTE or subquery first. |
| `model_parameters` | STRING           | A JSON string of model configuration options. Use `'{}'` for defaults. Supports keys like `temperature` and `max_tokens`.                    |
| `response_format`  | STRING           | A JSON string defining the expected output structure. Contains a `type` field and a `schema` field with a standard JSON Schema definition.   |
| `show_details`     | BOOLEAN          | When `TRUE`, the response includes a `structured_output` array with the full typed response. When `FALSE`, returns a plain string response.  |

**Returns:** STRING — A JSON string containing the model's response.

When `show_details` is `TRUE`, the returned JSON has this structure:

```json theme={null}
{
  "structured_output": [
    {
      "raw_message": {
        // Fields matching your response_format schema
      },
      "type": "json"
    }
  ]
}
```

**Examples:**

Classify a text column using structured output:

```sql theme={null}
SELECT
  AI_COMPLETE(
    'openai-gpt-5',
    company_data."my_dataset".prompt_text,
    '{}',
    '{"type": "json", "schema": {"type": "object", "properties": {"category": {"type": "string"}, "confidence": {"type": "number"}}, "required": ["category", "confidence"], "additionalProperties": false}}',
    TRUE
  ) AS result
FROM company_data."my_dataset"
```

Parse the structured output into individual columns:

```sql theme={null}
SELECT
  CAST(
    PARSE_JSON(result)['structured_output'][0]['raw_message']['category'] AS STRING
  ) AS category,
  CAST(
    PARSE_JSON(result)['structured_output'][0]['raw_message']['confidence'] AS DOUBLE
  ) AS confidence
FROM company_data."enriched_results"
```

Use model parameters to control response behavior:

```sql theme={null}
SELECT
  AI_COMPLETE(
    'openai-gpt-5',
    company_data."my_dataset".prompt_text,
    '{"temperature": 0, "max_tokens": 4096}',
    '{"type": "json", "schema": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": ["summary"], "additionalProperties": false}}',
    TRUE
  ) AS result
FROM company_data."my_dataset"
```

<Tip>
  The `prompt` parameter must be a column reference. To build dynamic prompts from multiple columns, use a CTE to concatenate values into a single prompt column, then pass that column to `AI_COMPLETE`. See the [data enrichment cookbook](/cookbooks/nql/ai-enrichment) for a complete example.
</Tip>

<Note>
  Because `AI_COMPLETE` runs within your Snowflake data plane, your data never leaves your infrastructure. No external API calls are made to model providers. See [Data Privacy in Model Inference](/concepts/model-inference/data-privacy) for details.
</Note>

**Setup requirements:**

Before `AI_COMPLETE` can run, the customer's Snowflake account must grant the Cortex role to the Narrative application and enable cross-region model access. See the [data enrichment cookbook](/cookbooks/nql/ai-enrichment#prerequisites) for the exact `GRANT` statements.

**Common errors:**

| Error                                                               | Cause                                                                   | Resolution                                                                                                                          |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Insufficient privileges to operate on database role 'CORTEX_USER'` | The Narrative application has not been granted `snowflake.cortex_user`. | Run the grant from the [cookbook setup](/cookbooks/nql/ai-enrichment#prerequisites).                                                |
| `Function AI_COMPLETE does not exist`                               | Query was run against a non-Snowflake data plane.                       | `AI_COMPLETE` is Snowflake-only. Use a [Model Inference job](/guides/sdk/running-model-inference) on other data planes.             |
| `Model '<id>' not available in this region`                         | Cross-region Cortex access is not enabled.                              | Set `CORTEX_ENABLED_CROSS_REGION = 'ANY_REGION'` on the account (see [cookbook setup](/cookbooks/nql/ai-enrichment#prerequisites)). |

**When to use `AI_COMPLETE` vs a Model Inference job:**

| Use `AI_COMPLETE` when...                                   | Use a [Model Inference job](/concepts/model-inference/overview) when... |
| ----------------------------------------------------------- | ----------------------------------------------------------------------- |
| You need row-level inference inline in NQL                  | You are calling inference from the SDK or API, not a query              |
| Your data plane is Snowflake                                | You need to run on a non-Snowflake data plane                           |
| You want to materialize enriched results as a view or table | You need a single on-demand completion (not a batch)                    |

**Related:** [Model Inference Overview](/concepts/model-inference/overview), [Structured Output](/concepts/model-inference/structured-output), [Data Enrichment Cookbook](/cookbooks/nql/ai-enrichment)

### CALL\_MODEL\_FUNCTION

Invokes a function on a custom model registered in the Snowflake ML Model Registry. Use `CALL_MODEL_FUNCTION` to run predictions, embeddings, or other operations from your own trained models directly within NQL.

**Syntax:**

```sql theme={null}
CALL_MODEL_FUNCTION(model_name, model_version, model_function [, arg0, arg1, ...])
```

**Parameters:**

| Parameter         | Type           | Description                                                                                                                                                                               |
| ----------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model_name`      | STRING         | The model identifier, optionally schema-qualified. Use `'schema.model_name'` or `'"schema"."model_name"'` to specify a schema. If no schema is provided, defaults to the `MODELS` schema. |
| `model_version`   | STRING or NULL | The model version to invoke. Pass `NULL` to use the default version.                                                                                                                      |
| `model_function`  | STRING         | The name of the function to call on the model (e.g., `'PREDICT'`).                                                                                                                        |
| `arg0, arg1, ...` | any            | Zero or more arguments passed to the model function. Typically column references containing the input data.                                                                               |

**Returns:** STRING — A JSON string containing the model function's output.

The return format depends on the model's function signature. Custom models typically return JSON objects:

```json theme={null}
{"OUTPUT": "predicted_value"}
```

**Examples:**

Call a custom model's predict function with a single input column:

```sql theme={null}
SELECT
  CALL_MODEL_FUNCTION(
    'my_schema.product_classifier',
    'v2',
    'PREDICT',
    company_data."products".product_name
  ) AS prediction
FROM company_data."products"
```

Use the default model version by passing `NULL`:

```sql theme={null}
SELECT
  CALL_MODEL_FUNCTION(
    'sentiment_model',
    NULL,
    'PREDICT',
    company_data."reviews".review_text
  ) AS sentiment
FROM company_data."reviews"
```

Parse the model output into typed columns:

```sql theme={null}
WITH predictions AS (
  SELECT
    company_data."products".product_id,
    CALL_MODEL_FUNCTION(
      'my_schema.product_classifier',
      'v2',
      'PREDICT',
      company_data."products".product_name
    ) AS raw_prediction
  FROM company_data."products"
)
SELECT
  predictions.product_id,
  CAST(PARSE_JSON(predictions.raw_prediction)['OUTPUT'] AS STRING) AS predicted_category
FROM predictions
```

Compare outputs across model versions:

```sql theme={null}
SELECT
  company_data."products".product_id,
  CALL_MODEL_FUNCTION(
    'my_schema.classifier',
    'v1',
    'PREDICT',
    company_data."products".product_name
  ) AS v1_prediction,
  CALL_MODEL_FUNCTION(
    'my_schema.classifier',
    'v2',
    'PREDICT',
    company_data."products".product_name
  ) AS v2_prediction
FROM company_data."products"
```

<Tip>
  When no schema is specified in the model name, the function defaults to the `MODELS` schema. To reference a model in a different schema, use dot notation: `'my_schema.model_name'` or quoted identifiers: `'"MY_SCHEMA"."MODEL_NAME"'`.
</Tip>

**Related:** [AI\_COMPLETE](#ai_complete), [Model Inference Overview](/concepts/model-inference/overview)

***

## Related content

<CardGroup cols={2}>
  <Card title="Data Enrichment with AI" icon="wand-magic-sparkles" href="/cookbooks/nql/ai-enrichment">
    Complete cookbook for enriching data using AI\_COMPLETE
  </Card>

  <Card title="Model Inference" icon="microchip" href="/concepts/model-inference/overview">
    How AI inference works within your data plane
  </Card>

  <Card title="Structured Output" icon="brackets-curly" href="/concepts/model-inference/structured-output">
    JSON Schema for predictable AI responses
  </Card>

  <Card title="All Functions" icon="function" href="/nql/functions/index">
    Browse all function categories
  </Card>
</CardGroup>
