10 min readIntermediate§ Snowflake

AI_FILTER, AI_CLASSIFY and AI_AGG in Snowflake Pipelines

Use Snowflake AI functions in batch pipelines: filter before you classify, constrain the labels, summarize with AI_AGG, and keep the token bill visible.

By Dinesh ChandraSenior Data and AI Engineer · SnowPro certified
Illustrated overview of AI_FILTER, AI_CLASSIFY and AI_AGG in Snowflake Pipelines
Fig. 1 · Snowflake
  1. 1.AI_FILTER, AI_CLASSIFY, AI_AGG and AI_COMPLETE are generally available SQL functions. Use them as pipeline steps, not as a chat window.
  2. 2.Cheap SQL predicates first, AI_FILTER second, AI_CLASSIFY on what is left, AI_COMPLETE only for the rows that need extraction.
  3. 3.Every label description and example adds input tokens. AI_COUNT_TOKENS shows the cost before you run the batch.
  4. 4.Run AI functions on a warehouse no larger than MEDIUM. A bigger one does not make them faster.
  5. 5.USE AI FUNCTIONS and CORTEX_USER are granted to PUBLIC by default. Revoke them and grant to your pipeline roles.
Table of contents

Snowflake’s AI functions turn a language model into something you call like UPPER(). AI_FILTER returns a boolean, AI_CLASSIFY returns a label, AI_AGG summarizes a whole column across rows, and AI_COMPLETE returns JSON that matches a schema you supply. All four are generally available, and they run where your data already sits.

That makes it easy to write a query that sends a million support tickets through a model and costs more than the warehouse it ran on. This post is the pattern I use to keep these functions in the pipeline and out of the incident channel: narrow first, classify second, extract last, and persist every result so you pay for a row once.

If you have used the older SNOWFLAKE.CORTEX.COMPLETE and CLASSIFY_TEXT functions, the Cortex AI for data engineers post covers that ground. This one is about the newer AI_ family.

The problem

Most warehouses have a column nobody models: ticket bodies, review text, call notes, free-text reasons on a refund form. Analysts want counts by topic and a weekly summary. The data team gets asked to “run it through the LLM”.

The functions now exist to do that in SQL. Snowflake made the Cortex AI functions generally available in November 2025, and AI_FILTER and AI_AGG followed in January 2026. AI_CLASSIFY is the updated version of CLASSIFY_TEXT. The open question is not whether you can, but how to do it without paying model prices for rows a WHERE clause could have dropped.

The common wrong approach

The usual first attempt is one AI_COMPLETE call per row with a long free-form prompt (“Read this ticket, decide the category, extract the invoice number, and summarize it”), parsed afterwards with regular expressions, on whatever large warehouse the analyst had open.

Three things go wrong. Every row pays for the full prompt, including rows that had nothing to extract. The output is free text, so the parsing fails on the rows that matter. And the warehouse size does nothing for speed: Snowflake recommends a warehouse no larger than MEDIUM for AI functions, because a larger one adds cost without adding performance.

The approach that works

The examples use a bronze.support_tickets table with ticket_id, created_at, channel, product_line and a body text column.

Step 1: control who can call the functions

By default, the USE AI FUNCTIONS account privilege and the SNOWFLAKE.CORTEX_USER database role are both granted to PUBLIC, so every user can call every function. Scope that down before a pipeline depends on it:

use role accountadmin;

revoke use ai functions on account from role public;
grant use ai functions on account to role transformer;

revoke database role snowflake.cortex_user from role public;
grant database role snowflake.cortex_user to role transformer;

If a role should only call scalar functions, grant SNOWFLAKE.AI_FUNCTIONS_USER instead of CORTEX_USER; it excludes AI_AGG, AI_SUMMARIZE_AGG, Cortex Search, Analyst and Agents. You can also grant a single function, for example GRANT USE AI FUNCTION AI_COMPLETE ON ACCOUNT TO ROLE .... Test with a non-admin role, because ACCOUNTADMIN always sees every model.

Step 2: narrow with SQL, then with AI_FILTER

Normal predicates are free compared with tokens. Apply them first, then let AI_FILTER make the semantic cut. Use PROMPT() to template the question with the column:

create or replace temporary table billing_candidates as
select
  ticket_id,
  created_at,
  product_line,
  body
from bronze.support_tickets
where created_at >= dateadd('day', -1, current_date())
  and channel in ('email', 'web')
  and length(body) between 40 and 8000
  and ai_filter(
        prompt('Does this support ticket describe a billing, invoice or refund problem? Ticket: {0}', body)
      );

Phrase the predicate as a yes or no question in plain English. The docs describe an automatic optimization for AI_FILTER that can be 2 to 10 times faster with up to 60% lower token usage when the engine detects a suitable query pattern. It is not guaranteed for every query, so do not plan capacity around it.

Step 3: classify into a closed set of labels

AI_CLASSIFY takes the input, a list of categories, and an optional config object. Short label descriptions and a task description improve accuracy:

create or replace temporary table billing_classified as
select
  ticket_id,
  created_at,
  product_line,
  body,
  ai_classify(
    body,
    [
      {'label': 'refund_request', 'description': 'customer asks for money back'},
      {'label': 'double_charge', 'description': 'customer was charged twice'},
      {'label': 'invoice_error', 'description': 'wrong amount, tax or details on an invoice'},
      {'label': 'payment_failed', 'description': 'card or bank payment did not go through'},
      {'label': 'other_billing'}
    ],
    {'task_description': 'Classify the billing issue in a customer support ticket'}
  ):labels[0]::string as billing_issue
from billing_candidates;

The function returns an object with a labels array; single-label mode returns one element. Keep the list short: the docs note that more than twenty categories may reduce accuracy.

Descriptions are not free. The AI_COUNT_TOKENS reference shows the same AI_CLASSIFY input counted at 187 tokens with labels only, 254 with descriptions and a task description, and 298 with an example added. Check your own prompt before a large batch:

select
  avg(ai_count_tokens('ai_classify', body)) as avg_input_tokens,
  count(*) as rows_to_classify
from billing_candidates;

This call counts the ticket text as input to AI_CLASSIFY; the reference shows how to pass your categories in the options argument so they are counted too. AI_COUNT_TOKENS incurs compute cost only, not token charges, and it counts input tokens only.

Step 4: extract structured fields only where needed

For refund requests you want the invoice number and amount as typed columns. AI_COMPLETE with response_format returns JSON that follows your schema, which removes the regex step:

create or replace temporary table refund_details as
select
  ticket_id,
  ai_complete(
    model => 'llama3.3-70b',
    prompt => 'Extract the invoice number and the disputed amount from this support ticket. Ticket: ' || body,
    model_parameters => {'temperature': 0, 'max_tokens': 200},
    response_format => {
      'type': 'json',
      'schema': {
        'type': 'object',
        'properties': {
          'invoice_number': {'type': 'string'},
          'disputed_amount': {'type': 'number'}
        },
        'required': ['invoice_number', 'disputed_amount']
      }
    }
  ) as extracted
from billing_classified
where billing_issue = 'refund_request';

The documentation describes the result as a JSON object that follows your schema, but it does not spell out the SQL type. Run select typeof(extracted) from refund_details limit 1 once: if it returns OBJECT, read fields with extracted:invoice_number::string; if it returns VARCHAR, wrap it as parse_json(extracted):invoice_number::string.

Model availability varies by region, so confirm the model on the regional availability page before you hard-code it. Set temperature to 0 for extraction and cap max_tokens; output tokens are billed too.

Step 5: persist once, then aggregate

Write results to a table keyed by ticket_id and skip rows you already processed. The incremental hash pattern from the earlier Cortex post applies unchanged.

insert into silver.ticket_billing_ai (
  ticket_id, created_at, product_line, billing_issue,
  invoice_number, disputed_amount, processed_at
)
select
  c.ticket_id,
  c.created_at,
  c.product_line,
  c.billing_issue,
  r.extracted:invoice_number::string,
  r.extracted:disputed_amount::number(12, 2),
  current_timestamp()
from billing_classified c
left join refund_details r on r.ticket_id = c.ticket_id
where not exists (
  select 1 from silver.ticket_billing_ai t where t.ticket_id = c.ticket_id
);

Now AI_AGG produces the weekly narrative per group. It is an aggregate function and is not limited by the model’s context window:

select
  t.product_line,
  t.billing_issue,
  count(*) as tickets,
  ai_agg(
    s.body,
    'These are customer support tickets about one billing issue. Summarize the three most common root causes in plain language for a weekly product review.'
  ) as weekly_summary
from silver.ticket_billing_ai t
join bronze.support_tickets s on s.ticket_id = t.ticket_id
where t.created_at >= dateadd('day', -7, current_date())
group by t.product_line, t.billing_issue;

Write the instruction as a declarative task that describes the text and the use case; the docs recommend that over a question. Snowflake’s GA note says AI_AGG delivers up to twice the throughput of AI_COMPLETE for this kind of large aggregation, based on its internal testing.

Step 6: watch the spend

AI function credits are reported under the AI_SERVICES service type:

select
  usage_date,
  sum(credits_used) as ai_credits
from snowflake.account_usage.metering_daily_history
where service_type = 'AI_SERVICES'
  and usage_date >= dateadd('day', -30, current_date())
group by usage_date
order by usage_date;

For per-call tokens and credits, query SNOWFLAKE.ACCOUNT_USAGE.CORTEX_FUNCTIONS_USAGE_HISTORY filtered by the QUERY_ID of your pipeline run.

Edge cases and changes

  • Errors return NULL. A failed row returns NULL and the query keeps going. Pass TRUE as the return_error_details argument to get an object with value and error fields, and route errors to a quarantine table.
  • NULL and odd input. The AI_FILTER docs advise avoiding NULL inputs and using plain English. The AI_CLASSIFY docs advise against classifying code, logs or non-English text.
  • Files and images. AI_FILTER and AI_CLASSIFY accept files via TO_FILE, but not from user stages, table stages, client-side encrypted external stages, SNOWFLAKE_FULL encrypted internal stages, or stages with double-quoted names. Document classification in AI_CLASSIFY is still in preview.
  • Dynamic Tables. Since September 2025, AI functions are supported in incremental Dynamic Table refresh, which is a cleaner home for steps 2 to 4 than a scheduled script.
  • Model allowlist. The CORTEX_MODELS_ALLOWLIST parameter is being deprecated in favor of model access through RBAC. Plan grants with the SNOWFLAKE.MODELS application roles.

Trade-offs

AI functions keep text processing inside Snowflake’s governance: same roles, same masking, no data copied out to a separate service. You give up some control over the model and prompt plumbing, and the cost lands as AI credits that are easy to miss in a warehouse-centric cost review.

They are also batch tools. Snowflake positions them for throughput over large tables and points latency-sensitive use cases to the REST API. If a product feature needs a classification in under a second, this is the wrong interface.

Pitfalls

  • AI on rows SQL could drop. Fix: apply date, channel and length predicates before any AI function.
  • Open-ended labels. Fix: a closed list of fewer than twenty categories with short descriptions and an other bucket.
  • Reprocessing the same rows daily. Fix: persist by key and skip processed rows, or hash the input.
  • An X-Large warehouse for AI calls. Fix: MEDIUM or smaller; size does not speed up the model.
  • PUBLIC can call everything. Fix: revoke USE AI FUNCTIONS and CORTEX_USER from PUBLIC and grant to named roles.

FAQ

Which function should I reach for first?

AI_FILTER when the question is yes or no, AI_CLASSIFY when the answer is one of a known set, and AI_COMPLETE with a schema only when you need extracted values. AI_AGG when the output is one summary per group, not one per row.

Does AI_AGG fail on very large groups?

The docs state it supports datasets larger than the model’s context window, unlike AI_COMPLETE and AI_SUMMARIZE. It may report that the data lacks the answer if your instruction is vague, so be specific.

How are these functions billed?

By tokens. For text-generating functions, including AI_CLASSIFY, AI_FILTER and AI_AGG, both input and output tokens are billable. The warehouse that runs the query is billed separately as usual.

Are results deterministic?

Not guaranteed. Set temperature to 0 for extraction, keep label sets fixed, and store results instead of recomputing them in every query.

Do I still need the old SNOWFLAKE.CORTEX functions?

For new work, no. AI_CLASSIFY replaces CLASSIFY_TEXT, and AI_COMPLETE is the current completion function. Migrate existing pipelines when you next touch them.

What this means for your pipelines

Treat AI functions as expensive transforms with a cheap pre-filter. Put SQL predicates first, then AI_FILTER, then AI_CLASSIFY, then AI_COMPLETE for the narrow slice that needs extraction. Persist every result once, aggregate with AI_AGG at the reporting grain, and add the AI_SERVICES line to the same dashboard as your warehouse credits.

Lock down the default grants on day one. The functions are GA; the governance around them is still your job.

Sources: Cortex AI Functions overview, AI_FILTER, AI_CLASSIFY, AI_AGG, AI_COMPLETE, AI_COUNT_TOKENS, Cost considerations, Privileges and model access, Cortex AI Functions GA, AI_FILTER GA, AI_AGG GA.

Free toolSnowflake cost calculatorEstimate your monthly bill with editable prices.
Share this post:X / TwitterLinkedInRedditWhatsApp
D

Dinesh Chandra

Senior Data & AI Engineer · SnowPro Core & Gen AI Certified

4+ years building production data platforms on Snowflake, Databricks, AWS, and Azure. I write from hands-on experience with Medallion architectures, dbt, Airflow, PySpark, and Snowflake Cortex AI. Every tutorial on this blog reflects real pipeline decisions, not documentation rewrites.

Read more about the author →
RE

Related entries

§ SnowflakeIntermediate
Illustrated overview of Snowflake Semantic Views: Metrics as Database Objects

· 9 min

Snowflake Semantic Views: Metrics as Database Objects

Define metrics once in a Snowflake semantic view, query them with plain SQL or Cortex Analyst, and add materializations without forking definitions.

  • #snowflake
  • #semantic-layer
  • #sql

Search DataLane

↑↓ navigatealt ↑↓ jump group↵ openesc close