+1 (415) 997-4269

Evaluating Cortex AI Apps: Snowflake AI Observability, TruLens Tracing, and LLM-as-Judge Metrics

Every Snowflake account that has shipped a Cortex Analyst semantic layer, a Cortex Search RAG assistant, or a Cortex Agent eventually hits the same wall: the demo was impressive, and now nobody can say whether the thing is actually right. Stakeholders ask "how accurate is it?" and the honest answer is a shrug and a Slack thread of screenshots.

Classic observability does not answer this. Snowflake Trail will tell you an agent call took 4.2 seconds and consumed 1,800 tokens. It will not tell you the answer hallucinated a discount policy that does not exist.

This tutorial covers the evaluation layer: Snowflake Cortex AI Observability, built on the open-source TruLens framework, which runs LLM-as-a-judge metrics over traced AI application runs and stores the results in your own account. We build an evaluation harness for a RAG app, run it against a curated dataset, read the scores, and wire the whole thing into CI so a prompt change cannot quietly regress quality.

What AI Observability actually gives you

Three things, and it helps to keep them separate:

  1. Tracing — structured spans for each step of an AI app (retrieval, prompt construction, LLM call, tool call), recorded via OpenTelemetry into an event table. Same plumbing as Snowflake Trail.
  2. Evaluation runs — you execute your app over a dataset of test inputs and record every trace.
  3. Metrics — LLM-as-a-judge scorers applied to those traces, producing numeric scores per record, persisted and comparable across runs.

The output lives in Snowsight under AI & ML -> Evaluations, but everything underneath is queryable SQL, which is the part that matters for a consulting engagement: you can put it on a dashboard and into a release gate.

Prerequisites

  • A database/schema for the app, and an event table enabled at account or database level.
  • SNOWFLAKE.CORTEX_USER database role granted to the app role.
  • Python 3.9+ with trulens-core, trulens-connectors-snowflake, and snowflake-snowpark-python. In a Snowflake Notebook on the container runtime, pip install into the notebook; locally, a virtualenv is fine.
CREATE DATABASE IF NOT EXISTS ai_eval;
CREATE SCHEMA IF NOT EXISTS ai_eval.rag;

CREATE EVENT TABLE IF NOT EXISTS ai_eval.rag.app_events;
ALTER DATABASE ai_eval SET EVENT_TABLE = ai_eval.rag.app_events;

-- traces and logs from the app, not just errors
ALTER DATABASE ai_eval SET LOG_LEVEL = 'INFO';
ALTER DATABASE ai_eval SET TRACE_LEVEL = 'ALWAYS';

GRANT DATABASE ROLE SNOWFLAKE.CORTEX_USER TO ROLE ai_app_rw;

Step 1: the application under test

Keep it ordinary. A Cortex Search retrieval, a prompt, a COMPLETE call:

from snowflake.snowpark.context import get_active_session
from snowflake.core import Root
from snowflake.cortex import complete

session = get_active_session()
root = Root(session)

SEARCH_SERVICE = (
    root.databases["ai_eval"].schemas["rag"].cortex_search_services["policy_search"]
)

class PolicyRAG:
    def retrieve(self, query: str) -> list[str]:
        resp = SEARCH_SERVICE.search(
            query=query, columns=["chunk", "doc_title"], limit=5
        )
        return [r["chunk"] for r in resp.results]

    def generate(self, query: str, context: list[str]) -> str:
        joined = "\n\n---\n\n".join(context)
        prompt = (
            "You answer questions about internal policy using ONLY the context.\n"
            "If the context does not contain the answer, say you do not know.\n\n"
            f"Context:\n{joined}\n\nQuestion: {query}\nAnswer:"
        )
        return complete("claude-4-sonnet", prompt, session=session)

    def answer(self, query: str) -> str:
        return self.generate(query, self.retrieve(query))

Step 2: instrument it

TruLens needs to know which method is retrieval and which is generation, so the judges can see the right arguments. That is what @instrument does — the span_type and attribute mapping are the whole trick.

from trulens.core.otel.instrument import instrument
from trulens.otel.semconv.trace import SpanAttributes

class PolicyRAG:
    @instrument(
        span_type=SpanAttributes.SpanType.RETRIEVAL,
        attributes={
            SpanAttributes.RETRIEVAL.QUERY_TEXT: "query",
            SpanAttributes.RETRIEVAL.RETRIEVED_CONTEXTS: "return",
        },
    )
    def retrieve(self, query: str) -> list[str]: ...

    @instrument(
        span_type=SpanAttributes.SpanType.GENERATION,
        attributes={SpanAttributes.CALL.KWARGS: {"query": "query"}},
    )
    def generate(self, query, context): ...

    @instrument(
        span_type=SpanAttributes.SpanType.RECORD_ROOT,
        attributes={
            SpanAttributes.RECORD_ROOT.INPUT: "query",
            SpanAttributes.RECORD_ROOT.OUTPUT: "return",
        },
    )
    def answer(self, query: str) -> str: ...

Register the app against a Snowflake connector so runs land in your account:

from trulens.core import TruSession
from trulens.connectors.snowflake import SnowflakeConnector
from trulens.apps.app import TruApp

connector = SnowflakeConnector(snowpark_session=session)
session_tl = TruSession(connector=connector)

rag = PolicyRAG()
tru_app = TruApp(
    rag,
    app_name="policy_rag",
    app_version="v3_stricter_prompt",
    connector=connector,
    main_method=rag.answer,
)

app_version is not decoration. Every comparison you will ever make — prompt v2 vs v3, claude-4-sonnet vs mistral-large2, top-5 vs top-10 retrieval — is a version-to-version diff. Name versions meaningfully from day one.

Step 3: a dataset worth evaluating against

The single biggest determinant of whether this exercise is useful. Twenty-five to a hundred questions drawn from real user logs beats a thousand synthetic ones. Include:

  • questions the app should answer well (happy path),
  • questions whose answer is genuinely absent from the corpus (the app must say "I don't know"),
  • near-miss questions where two policy documents disagree,
  • adversarial phrasing and prompt-injection attempts.

Store it as a table so it is version-controlled and shareable:

CREATE OR REPLACE TABLE ai_eval.rag.golden_set (
  id            NUMBER AUTOINCREMENT,
  query         STRING,
  ground_truth  STRING,       -- nullable: only for questions with a known answer
  category      STRING        -- happy_path | unanswerable | conflicting | adversarial
);

Step 4: run the evaluation

import pandas as pd

golden = session.table("ai_eval.rag.golden_set").to_pandas()

run_config = {
    "run_name": "policy_rag_v3_2026_02",
    "dataset_name": "ai_eval.rag.golden_set",
    "dataset_spec": {
        "RECORD_ROOT.INPUT": "QUERY",
        "RECORD_ROOT.GROUND_TRUTH_OUTPUT": "GROUND_TRUTH",
    },
    "description": "v3 prompt, top-5 retrieval, claude-4-sonnet",
}

run = tru_app.add_run(run_config=run_config)
run.start()                       # invokes the app over every row, capturing traces
run.compute_metrics([
    "answer_relevance",
    "context_relevance",
    "groundedness",
    "correctness",
])

Metrics are computed asynchronously by a Cortex judge model; run.get_status() tells you when they have landed.

Step 5: read the scores like an engineer, not a marketer

The three RAG-triad metrics decompose failure, which is why you want all of them:

MetricQuestion it answersWhat a low score means
Context relevanceDid retrieval return chunks related to the question?Fix chunking, embeddings, search service filters — not the prompt
GroundednessIs every claim in the answer supported by the retrieved context?The model is hallucinating; tighten the prompt, lower temperature, add citation requirements
Answer relevanceDoes the answer address the question asked?Prompt or output-format problem
CorrectnessDoes it match ground truth?End-to-end regression signal; only meaningful where ground truth exists

The diagnostic pattern: high context relevance + low groundedness = a generation problem. Low context relevance = a retrieval problem. Teams that only track a single "accuracy" number spend weeks tuning prompts when the real fault was a 400-token chunk size slicing tables in half.

Scores are rows, so query them:

SELECT
  category,
  COUNT(*)                                        AS n,
  AVG(groundedness)                               AS avg_groundedness,
  AVG(context_relevance)                          AS avg_context_rel,
  SUM(IFF(groundedness < 0.6, 1, 0))              AS ungrounded_answers
FROM ai_eval.rag.eval_results          -- your materialised view over the run output
WHERE run_name = 'policy_rag_v3_2026_02'
GROUP BY category
ORDER BY avg_groundedness;

Always slice by category. An app that scores 0.88 overall but 0.31 on unanswerable is an app that confidently invents policy — the single most expensive failure mode in a regulated client.

Step 6: gate releases on it

An evaluation that runs when someone remembers is not an evaluation. Put it in the pipeline that already deploys your Snowflake objects:

  1. CI job builds the app version from the Git branch and registers it with app_version = <branch>-<sha>.
  2. It runs the golden set.
  3. It compares aggregate metrics to the current production version.
  4. It fails the build if groundedness drops more than 3 points, or if any unanswerable row produces a confident answer.
baseline = metrics_for("v2_prod")
candidate = metrics_for(f"{branch}-{sha}")

if candidate["groundedness"] < baseline["groundedness"] - 0.03:
    raise SystemExit("Regression in groundedness — blocking deploy")
if candidate["unanswerable_answered"] > 0:
    raise SystemExit("Model answered an unanswerable question — blocking deploy")

Pair it with the Git integration and EXECUTE IMMEDIATE FROM deployment pattern you already use for schema changes, and AI quality becomes just another test suite.

Cost and practical notes

  • Judges cost tokens. Four metrics over 100 records is 400+ LLM calls per run. Keep the golden set small and sharp; run the full set nightly and a 20-row smoke set per commit.
  • Judges are not oracles. Spot-check 10% of judge verdicts by hand the first few runs. If the judge disagrees with your domain expert, fix the metric definition or add a custom one before trusting the dashboard.
  • Trace volume adds storage. Event tables retain spans; set a retention policy on the event table rather than discovering the cost in month three.
  • Separate eval compute. Run evaluations on their own warehouse so judge spend is attributable in WAREHOUSE_METERING_HISTORY and does not distort the app's cost baseline.
  • Human review still belongs in the loop for anything customer-facing. Automated metrics catch regressions; they do not establish acceptability.

Where this fits in a delivery plan

On client engagements we treat AI observability as a day-one deliverable, not a post-launch add-on, and the sequencing is consistent: instrument the app before tuning it, build the golden set with the business owner in the room, and publish the metric dashboard to the same stakeholders who asked "how accurate is it?". The conversation shifts from anecdotes to a trend line — and the team gains permission to iterate on prompts and models because regressions now surface in CI instead of in production.

If you are standing up Cortex Analyst, Cortex Search, or Cortex Agents and have no evaluation harness behind them, that is the gap worth closing first. Get in touch and we can walk through what an evaluation layer would look like on your account.