How it works
The general Cortex AI functions are the foundation that every other inference call in the platform reduces to.
AI_COMPLETE is the one-shot text-completion function, accepting a model name and either a single prompt or a messages array, and returning a generated string or, when configured, a JSON object validated against a schema.
COMPLETE Structured Outputs is not a separate function: it is the response-shape mode of AI_COMPLETE selected by passing response_format in the options object.
Reasoning about every other AI function starts here, because task functions like AI_SENTIMENT or AI_CLASSIFY are tuned wrappers over the same underlying inference engine, and every governance, cost, and routing rule that applies to AI_COMPLETE applies transitively to the task family. The function signature has two forms.
- The single-prompt form is
AI_COMPLETE(model, prompt), returning a VARCHAR. - The full form is
AI_COMPLETE(model, prompt_or_messages, options, show_details), whereoptionsis an OBJECT carrying inference parameters andshow_detailsis a BOOLEAN that toggles a detailed JSON response.
The model argument is a string literal naming a hosted model from the Cortex catalog. Common values include claude-3-5-sonnet, claude-4-sonnet, llama3.1-405b, llama3.1-70b, llama3.3-70b, mistral-large2, snowflake-arctic, and snowflake-llama-3.1-405b.
The catalog is region-specific. A model that is GA in one region may be available only through cross-region inference in another, which is precisely why the CORTEX_ENABLED_CROSS_REGION parameter introduced in the previous chapter governs whether calls can hop across regions to find a backing model.
- The
optionsobject controls inference shape. temperatureis a FLOAT between 0 and 1 that biases sampling.max_tokenscaps the response length.top_pcontrols nucleus sampling.guardrailstoggles Cortex Guard, the content-safety layer that filters unsafe outputs and adds a groundedness metric.response_formatis the structured-output mode: passing a JSON Schema in this field flips AI_COMPLETE into a path where the model emits a validated JSON object matching the schema, and the function returns that object typed as VARIANT.
Structured outputs are the single most important behavior to internalize for the exam, because they replace fragile regex post-processing with a contract-enforced shape and make AI_COMPLETE a viable substitute for several hand-rolled extraction pipelines.
Structured outputs change the failure mode of the function. Without response_format, AI_COMPLETE happily returns a string that does not parse. With response_format, the call either returns valid JSON conforming to the schema or it fails. That binary outcome is the basis for an entire class of pipelines where AI_COMPLETE feeds downstream SQL transformations directly.
The schema you pass follows JSON Schema draft semantics, supporting: type
properties
required
enum
items
additionalProperties
nested objects
Snowflake validates the response against the schema before returning it, so a downstream value:field::string cast is safe.
Setting up the Snowflake environment with required privileges
Key points
Cortex AI functions are gated by an application role named CORTEX_USER.
The role lives in the SNOWFLAKE database and is granted to other roles using GRANT APPLICATION ROLE.
A new account does not automatically grant CORTEX_USER to PUBLIC.
Allowing every user to call AI functions requires a deliberate grant, which is the central principle of governance in this stack.
A typical bootstrap path is USE ROLE ACCOUNTADMIN; GRANT APPLICATION ROLE SNOWFLAKE.CORTEX_USER TO ROLE AI_ENGINEER;.
To restrict which models are callable, the account-level parameter CORTEX_MODELS_ALLOWLIST accepts a comma-separated list of model names or the literal value 'All'.
Setting it to 'claude-3-5-sonnet,llama3.1-70b' blocks every other model at the engine layer regardless of grants.
This pairing of role-based access and allowlist parameter is the layered control that the certification tests under the governance domain.
Beyond CORTEX_USER, related application roles exist for specific surfaces:
- CORTEX_ANALYST_USER governs Cortex Analyst.
- CORTEX_AGENT_USER governs Cortex Agents.
- CORTEX_EMBED_USER governs embedding services that participate in cross-account sharing.
Granting CORTEX_USER does not grant the others. A team that needs to call both AI_COMPLETE and a Cortex Analyst semantic model must hold both application roles. Forgetting this is the single most common cause of permission errors the first time a Streamlit app is deployed.
USE ROLE ACCOUNTADMIN;
CREATE ROLE IF NOT EXISTS AI_ENGINEER;
GRANT APPLICATION ROLE SNOWFLAKE.CORTEX_USER TO ROLE AI_ENGINEER;
GRANT APPLICATION ROLE SNOWFLAKE.CORTEX_ANALYST_USER TO ROLE AI_ENGINEER;
GRANT USAGE ON WAREHOUSE AI_WH TO ROLE AI_ENGINEER;
GRANT USAGE ON DATABASE AI_DB TO ROLE AI_ENGINEER;
GRANT USAGE ON SCHEMA AI_DB.AI_LAB TO ROLE AI_ENGINEER;
GRANT ROLE AI_ENGINEER TO USER ANALYST_PRIMARY;
ALTER ACCOUNT SET CORTEX_MODELS_ALLOWLIST = 'claude-3-5-sonnet,llama3.1-70b,snowflake-arctic';
ALTER ACCOUNT SET CORTEX_ENABLED_CROSS_REGION = 'AWS_US';
The cross-region parameter accepts values such as DISABLED, ANY_REGION, AWS_US, AWS_EU, or AZURE_US.
Setting it scopes the geographies into which Cortex may route a request when the model is not available locally.
The choice has data-residency implications because the request payload, including the prompt and any retrieved context, transits to the chosen region for inference.
Compliance reviews almost always pin this parameter to a single regulatory boundary.
A baseline AI_COMPLETE call demonstrates both signatures and structured output.
SELECT AI_COMPLETE(
'claude-3-5-sonnet',
'Summarize the following ticket in one sentence: ' || ticket_body
) AS summary
FROM AI_DB.AI_LAB.SUPPORT_TICKETS
WHERE ticket_id = 4711;
SELECT AI_COMPLETE(
model => 'claude-3-5-sonnet',
prompt => 'Classify the priority and extract any product name from: ' || ticket_body,
model_parameters => OBJECT_CONSTRUCT('temperature', 0, 'max_tokens', 200),
response_format => OBJECT_CONSTRUCT(
'type', 'json_schema',
'json_schema', OBJECT_CONSTRUCT(
'schema', PARSE_JSON('{
"type": "object",
"properties": {
"priority": {"type": "string", "enum": ["LOW","MEDIUM","HIGH","CRITICAL"]},
"product": {"type": "string"}
},
"required": ["priority"]
}')
)
)
) AS structured
FROM AI_DB.AI_LAB.SUPPORT_TICKETS
WHERE ticket_id = 4711;
The structured call returns a VARIANT that downstream queries can address as structured:priority::string and structured:product::string. The temperature => 0 setting makes the model nearly deterministic, which matters whenever the result feeds a hash join or a downstream join key.
💡 Exam Trap: AI_COMPLETE and the legacy
SNOWFLAKE.CORTEX.COMPLETEare aliases at the SQL surface. Both accept the same arguments and route to the same inference engine. The exam can quote either form and you should treat them as equivalent. The bare difference is namespace: the fully qualified form is required only in scripts where a session-default schema would otherwise resolve a same-named local function.
💡 Exam Trap: Granting
USAGE ON DATABASE SNOWFLAKEto a custom role does NOT grant CORTEX_USER. Cortex functions are gated by an application role, not a schema privilege. A query that errors withInsufficient privileges to operate on cortexusually means CORTEX_USER was missed, not that the schema grant was wrong.
📊 Limit: AI_COMPLETE has a per-call input token cap that varies by model. For most hosted models the soft cap is in the 8K to 32K input token range, and large-context models like
claude-3-5-sonnetextend to 200K input tokens. Exceeding the per-model context window raises an error at request time, not a truncated response.
⚠️ Anti-Pattern: Calling AI_COMPLETE without an
optionsobject on rows where you intend to join the result downstream. The default temperature is non-zero, which means re-running the same row may return a different value, and any downstream equality join becomes flaky. For row-level extraction pipelines always pintemperature => 0.
🎯 Scenario: A team is migrating a Python script that calls AI_COMPLETE against
claude-3-5-sonnetto extractinvoice_numberandtotal_amountfrom email bodies. The script uses a regex to find the JSON in the model response and fails ~3% of the time on malformed JSON. The fix: passresponse_formatwith a JSON Schema that declares both fields as required. AI_COMPLETE then either returns a validated object or raises an error, eliminating the regex layer and the 3% silent-corruption tail.
Decision Anchor. Choose AI_COMPLETE with response_format when you need a typed object out of a generative model and you cannot tolerate parse failures. Choose plain AI_COMPLETE when the answer is naturally free text such as a summary or rewrite, and the consumer accepts string output.
Choose a task-specific function such as AI_CLASSIFY or AI_EXTRACT when the operation maps to one of the canonical task signatures, because those functions are cheaper per token and ship with provider-tuned prompts. ---
