Skip to main content
This cookbook demonstrates how to use the AI_COMPLETE function to enrich records with AI-generated structured attributes directly within NQL. The entire inference pipeline runs inside your Snowflake data plane—your data never leaves your infrastructure.
AI_COMPLETE is available on Snowflake data planes only.

What you will build

A materialized view that takes raw customer support tickets and enriches each record with:
  • A standardized issue category
  • A priority level
  • A sentiment score
  • Extracted product mentions
The same pattern applies to any enrichment task: product classification, lead scoring, content tagging, entity extraction, and more.

Prerequisites

One-time Snowflake setup

AI_COMPLETE runs through Snowflake Cortex, so the customer Snowflake account must grant Cortex access to the Narrative application and allow cross-region model invocation. A Snowflake account admin runs these statements once:
Replace <narrative_application_name> with the name of the Narrative Snowflake Native App installed in the account (for example, NARRATIVE_DATA_COLLABORATION_HMI).
The GRANT DATABASE ROLE ... TO APPLICATION statement is a temporary workaround required by current Snowflake Native App permissioning. Snowflake may change how Native Apps access Cortex in the future, at which point this setup step may change. Contact Narrative support if AI_COMPLETE queries begin failing with permission errors.
CORTEX_ENABLED_CROSS_REGION = 'ANY_REGION' lets Cortex invoke models that are hosted outside the account’s home region. Narrative recommends ANY_REGION because model availability varies by region. If your compliance posture requires region pinning, consult Snowflake’s cross-region inference documentation for the available alternatives.
To confirm the grant succeeded, run a minimal query with a literal prompt:
If this query fails with a privileges error, re-run the grant statements above.

Step 1: Define the output schema

Before writing NQL, design the JSON Schema that describes the structured attributes you want the model to produce. This schema constrains the model’s output, guaranteeing predictable, typed results.
Key schema design decisions:
Keep schemas focused on the fields your downstream queries will actually use. Every additional field increases token usage and inference cost.

Step 2: Build prompt strings in a CTE

AI_COMPLETE requires its prompt parameter to be a column reference, not a string literal. Use a Common Table Expression (CTE) to assemble prompts from your source columns.
Tips for building effective prompts:
  • Prefix each field with a label (e.g., ' Ticket subject: ') so the model can distinguish between data elements
  • Filter rows before calling AI_COMPLETE to avoid unnecessary inference costs
  • Use COALESCE to handle nulls: COALESCE(company_data."support_tickets".subject, 'No subject')

Step 3: Call AI_COMPLETE

Pass the prompt column to AI_COMPLETE along with your schema. The response is a JSON string that you parse in the next step.
Parameter choices:

Step 4: Parse the response into columns

Use PARSE_JSON and path notation to extract individual fields from the AI response into typed columns.
The path ['structured_output'][0]['raw_message'] navigates to the model’s schema-validated output. Each field within raw_message corresponds to a property in your response_format schema.

Complete example

Here is the full query wrapped as a materialized view that refreshes weekly:

Adapting this pattern

The CTE → AI_COMPLETE → PARSE_JSON pattern works for any enrichment task. Here are variations for common scenarios.

Product classification

Classify products into a taxonomy from their name and description:

Entity extraction

Extract structured entities from free-text fields:

Best practices

Prompt design:
  • Label each data element clearly (e.g., ' Brand: ', ' Description: ')
  • Include a brief instruction at the start of the prompt describing the task
  • Use COALESCE to handle nullable columns and avoid sending nulls to the model
Schema design:
  • Use enum to constrain categorical outputs to known values
  • Set additionalProperties: false to prevent unexpected fields
  • Add description to each property to guide the model
  • Use number types for scores you want to filter or aggregate
Performance and cost:
  • Filter rows with WHERE before the AI_COMPLETE call to reduce inference volume
  • Use FETCH NEXT N ROWS ONLY to limit batch sizes during development and testing
  • Set temperature to 0 for deterministic, reproducible results
  • Keep schemas focused—fewer fields means fewer tokens per response

AI_COMPLETE Reference

Function syntax and parameter details

Model Inference

How AI inference works within your data plane

Structured Output

Designing JSON schemas for AI responses

Creating Materialized Views

Automating queries with scheduled materialized views