Tutorial: Analyze Snowflake data with Cortex AI in a sandbox

This tutorial shows how to combine a live Snowflake data query with a Cortex AI analysis, all running inside a single isolated sandbox. The sandbox uses your injected session identity to query data and call SNOWFLAKE.CORTEX.COMPLETE via SQL — no credentials are configured or forwarded.

The pattern scales to any data-plus-AI workflow: summarize operational metrics, classify query results, flag anomalies, or generate natural-language reports over Snowflake data.

Time to complete: about 15 minutes.

Prerequisites

  • The snowflake-sandbox-python SDK installed and a Snowflake connection configured on your local machine. See Cortex Sandboxes quickstart.
  • Run main.py from a local terminal, not from a Snowflake Workspace. When the driver runs inside a Workspace, the inner sandbox does not inherit the credentials needed for snowflake.connector to connect back to Snowflake.
  • Your role must have access to SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY and USAGE on the Cortex COMPLETE function. If you do not have ACCOUNT_USAGE access, substitute any table with numeric data you do have access to.

Step 1: Write the analyst script

The following script runs inside the sandbox. It queries WAREHOUSE_METERING_HISTORY for the last seven days, formats the data, passes it to SNOWFLAKE.CORTEX.COMPLETE for analysis, and prints the result.

# analyst.py  — runs inside the sandbox
import json

from snowflake.sandbox import get_snowflake_connection

conn = get_snowflake_connection()
cur = conn.cursor()

# Step 1: query warehouse credit usage for the last 7 days
cur.execute("""
    SELECT warehouse_name,
           ROUND(SUM(credits_used), 2)  AS total_credits,
           COUNT(*)                     AS billing_periods
    FROM   snowflake.account_usage.warehouse_metering_history
    WHERE  start_time >= DATEADD('day', -7, CURRENT_TIMESTAMP())
    GROUP  BY 1
    ORDER  BY total_credits DESC
    LIMIT  5
""")
rows = cur.fetchall()
usage_data = [
    {
        "warehouse": str(r[0]),
        "credits": float(r[1]),
        "periods": int(r[2]),
    }
    for r in rows
]

# Step 2: pass the query results to Cortex for a plain-English summary
prompt = (
    "You are a Snowflake cost analyst. "
    "Here is 7-day warehouse credit usage: "
    + json.dumps(usage_data)
    + " Write a 2-sentence plain-English summary that identifies the top consumer "
    "and any notable usage patterns. Be specific with numbers."
)
cur.execute("SELECT SNOWFLAKE.CORTEX.COMPLETE('llama3.1-8b', %s)", (prompt,))
analysis = (cur.fetchone() or ["No response."])[0].strip()

conn.close()

print("=== Warehouse usage (last 7 days) ===")
for row in usage_data:
    print(f"  {row['warehouse']}: {row['credits']} credits ({row['periods']} billing periods)")

print("\n=== Cortex analysis ===")
print(analysis)

Replace llama3.1-8b with any Cortex model your role has access to. See COMPLETE (SNOWFLAKE.CORTEX) for the full model list.

Step 2: Write the driver and run it

The driver creates one sandbox, writes analyst.py into it, and runs it. Save this as main.py in the same directory as analyst.py.

# main.py  — runs on your machine (the driver)
from pathlib import Path
from snowflake.sandbox import Sandbox

ANALYST = Path("analyst.py").read_text()

print("Creating sandbox...")
with Sandbox.create() as sb:
    print(f"Sandbox ready: {sb.id}")
    # Write analyst.py into the sandbox at a known path, then run it.
    sb.write_text("/tmp/analyst.py", ANALYST)
    result = sb.exec(
        ["python", "/tmp/analyst.py"],
        timeout=120.0,
    )
    print(result.stdout)

How to run this example

Save analyst.py and main.py in the same directory and run:

python main.py

Expected output:

Creating sandbox...
Sandbox ready: cntr_...
=== Warehouse usage (last 7 days) ===
  COMPUTE_WH: 142.3 credits (504 billing periods)
  ANALYTICS_WH: 38.1 credits (168 billing periods)
  ...

=== Cortex analysis ===
COMPUTE_WH was the top consumer over the 7-day period, accounting for 142.3
credits across 504 billing periods. Usage was consistent throughout the week with
no unusual spikes, though COMPUTE_WH used roughly four times more credits than
the next highest warehouse, ANALYTICS_WH.

The exact output depends on your account’s warehouse activity.

What this demonstrates

  • No credentials are configured. The sandbox authenticates with the session token the platform provides, which get_snowflake_connection() locates for you. Your PAT is not passed to the container.
  • Data and AI in the same isolated environment. The sandbox queries your live Snowflake data and calls Cortex AI in the same execution context, fully contained within your Snowflake account.
  • Cortex runs in-warehouse. SNOWFLAKE.CORTEX.COMPLETE is a Snowflake SQL function. The LLM inference runs on Snowflake compute and your data does not leave the platform.
  • Your governance policies apply. Because the sandbox runs as your session, row-level security and column masking policies apply to every query — including the queries the AI analysis is based on. See Tutorial: Governance enforcement in a sandbox.

Going further

This tutorial shows a single-sandbox, single-query analysis. For larger workloads:

  • Fan out across multiple sandboxes to process different tables or time windows in parallel, as shown in Tutorial: Run Cortex batch inference over a Snowflake table.
  • Pass the analyst’s output back to the driver and write it to a Snowflake table for downstream use.
  • Extend the analyst.py script with multiple queries, conditional logic, or a loop over Cortex calls to build a more complete agentic workflow.