<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kaitlyn Wells on Medium]]></title>
        <description><![CDATA[Stories by Kaitlyn Wells on Medium]]></description>
        <link>https://medium.com/@kaitlyn.wells?source=rss-32b2ac27f8b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y6NKZWHJJlakK7-C9kctDw.jpeg</url>
            <title>Stories by Kaitlyn Wells on Medium</title>
            <link>https://medium.com/@kaitlyn.wells?source=rss-32b2ac27f8b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:47:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaitlyn.wells/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling Semantic Layer Rollout with Snowflake Cortex Code Agent SDK]]></title>
            <link>https://medium.com/snowflake/scaling-semantic-layer-rollout-with-snowflake-cortex-code-agent-sdk-40b21e5d8eda?source=rss-32b2ac27f8b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b21e5d8eda</guid>
            <category><![CDATA[agents-sdk]]></category>
            <category><![CDATA[cortex-code]]></category>
            <category><![CDATA[semantic-layer]]></category>
            <category><![CDATA[semantic-view]]></category>
            <category><![CDATA[cortex]]></category>
            <dc:creator><![CDATA[Kaitlyn Wells]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 19:01:01 GMT</pubDate>
            <atom:updated>2026-04-30T19:17:49.393Z</atom:updated>
            <content:encoded><![CDATA[<p>As frontier models continue to improve, enterprises face an exponential increase in demand to scale and maintain their semantic layer for structured data. Over the past year, we’ve seen business groups rapidly adopt Snowflake’s Semantic View generator to automatically create metadata on tables and columns to build the business context that powers text-to-SQL at 90%+ accuracy.</p><p>Snowflake leads the charge with <a href="https://docs.snowflake.com/en/user-guide/views-semantic/autopilot">Semantic View Autopilot</a>, which lets data owners leverage existing context (SQL query history, Tableau data sources) to automatically generate metadata, infer relationships, and bootstrap a truth set from account usage views. Data owners can go from zero to a working semantic layer in minutes, not weeks.</p><p>When you have <strong>hundreds of tables</strong> across multiple domains and want to automate this at a platform level, you need a programmatic approach to scale the creation of semantic views.</p><p>A month ago, a large bank tasked me with creating semantic views for 700 tables. Using metadata and historical queries, I generated 35 semantic views, QA’d and validated them in 12 hours with a mix of prompting Cortex Code CLI, manual review, and testing the accuracy.</p><p><a href="https://github.com/sfc-gh-kwells/snow-fsi-demos/tree/main/sv_automation">Using</a> Snowflake’s new <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/cortex-code-agent-sdk">Cortex Code Agent SDK </a>and my learnings, I decomposed my workflow into 8<a href="https://github.com/sfc-gh-kwells/snow-fsi-demos/tree/main/sv_automation"> fully automated, generalizable steps</a> that can be leveraged to create semantic views across an account or refresh semantic views when your schemas change. Cortex Code Agent SDK is Snowflake’s agentic coding tool that is now exposed as a Python package to automate workflows.</p><h3>What are the workflows</h3><p>There are two pipeline modes:</p><p><strong>1. Semantic View Creation</strong></p><p>Starting from a database or schema, the pipeline mines your Snowflake account for rich contextual signals, groups tables into semantic domains, generates and validates semantic view definitions, evaluates accuracy against auto-generated question sets, and provisions Cortex Search services with optional human-in-the-loop checkpoints.</p><p><strong>2. Refresh pipeline — DDL change detection and propagation</strong></p><p>When underlying tables change (columns added, renamed, dropped), the refresh workflow detects the delta, classifies the change as breaking or non-breaking, updates affected semantic views, and re-evaluates accuracy with an optional human-in-the-loop checkpoint before deploying breaking changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YYW8W422r4ZS6X33dSZVg.png" /></figure><h3>Cortex Code Agent SDK Makes This Possible</h3><p>The entire pipeline is built on the <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/cortex-code-agent-sdk">cortex_code_agent_sdk </a>Python package. The core primitive is <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/python-reference#query">query()</a>, an async streaming function that takes a prompt and a <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/cortex-code-agent-sdk#multi-turn-sessions">CortexCodeAgentOptions</a> object and returns a live stream of <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/python-reference#assistantmessage">AssistantMessage</a> and <a href="https://docs.snowflake.com/en/user-guide/cortex-code-agent-sdk/python-reference#resultmessage">ResultMessage</a> events. Every agent invocation in the pipeline — mining, clustering, lineage mapping, semantic view creation, evaluation is a single query() call:</p><pre>from cortex_code_agent_sdk import query, CortexCodeAgentOptions, AssistantMessage, ResultMessage<br>  <br>  options = CortexCodeAgentOptions(<br>      cwd=str(agent_dir),          # directory containing agent.md system prompt<br>      connection=&quot;MY_DEMO&quot;,        # Snowflake connection name<br>      model=&quot;auto&quot;,<br>      mcp_servers={&quot;sv-tools&quot;: mcp_server},   # domain-specific SQL tools<br>      setting_sources=[],          # isolated — no user settings inherited<br>  )<br>  <br>  async for msg in query(prompt=task_prompt, options=options):<br>      if isinstance(msg, AssistantMessage):<br>          # stream reasoning and tool calls in real time<br>          ...<br>      elif isinstance(msg, ResultMessage):<br>          break  # final result ready</pre><p>Each specialized agent (query history miner, clusterer, lineage mapper, SV creator, evaluator, Cortex Search provisioner) is defined by an agent.md file in its own directory. CortexCodeAgentOptions.cwd points the SDK to that directory, automatically loading the agent’s system prompt and tool access rules. The mcp_servers parameter attaches a local MCP server that exposes domain-specific SQL tools: get_join_frequency, fast_generate_semantic_view, run_cortex_reflect, call_cortex_analyst, and others so each agent only sees the tools it needs.</p><p>Parallelism comes from running multiple query() calls concurrently under asyncio, bounded by a configurable limit on the number of agents that can be spawned. Phase 1 shards the table list and mines all shards simultaneously. Phase 2 looks at all of the Snowflake account context retrieved as part of Phase 1 to propose how the tables should be grouped into different semantic views or “clusters.” Phases 3, 4, 5, 6 and 7 fan out one agent per cluster or per Semantic View.</p><p>This architecture means the pipeline is as easy to extend as it is to run: adding a new phase is as simple as adding a new agent.md and wiring a query() call into the orchestrator.</p><h3>Context Already in your Snowflake Account</h3><p>The biggest architectural question which can heavily vary by enterprise is what context already exists in your Snowflake account that can accelerate how you architect and evaluate your semantic layer?</p><p>Most enterprises have far richer metadata than they realize, but the value can vary based on your account’s nuances:</p><ul><li>Query tags track distinct workflows which tables belong together in a business process maps directly to which tables belong in a semantic view</li><li>Warehouse affinity reveals which tables are always queried together, a strong signal for relationship inference</li><li>User and role affinity identifies your main data consumers per domain — and surfaces whether you have multiple use cases per domain that warrant separate agents and different business context</li><li>Join co-occurrence across query history tells you the actual relationships between tables, not just the foreign keys defined in your schema</li></ul><p>In my implementation, these signals feed directly into the clustering and relationship inference phases. I’ve made specific assumptions about how to weigh them but this is an area I expect to evolve significantly based on how different enterprises organize their data.</p><h3>Architectural Considerations</h3><p>A few design decisions worth calling out:</p><ul><li><strong>Query-history-based table filtering. </strong>Tables with no recent access history are flagged and excluded before Phase 1 runs. This prevents the pipeline from wasting cycles on staging tables, backup clones, and internal system tables that will never be queried through an agent.</li><li><strong>Human-in-the-loop checkpoints. </strong>The pipeline supports an hitl mode that pauses at two decision points — after the cluster plan and after evaluation — and waits for explicit approval before proceeding. This lets enterprises run fully automated in dev and gated in higher environments.</li><li><strong>Structured observability. </strong>Every pipeline run produces a JSONL event stream and a rendered HTML report covering phase timings, per-SV accuracy scores with pass/partial/fail breakdowns, agent call timeline, and a quarantine log. This makes it straightforward to diagnose failures and track quality trends across runs.</li></ul><h3>What’s Next: Going Beyond Snowflake</h3><p>If I were incorporating this at a platform level, I’d be asking:</p><ul><li>What additional MCP servers can enrich the context? dbt project metadata, data catalog APIs, and BI layer semantic models all contain relationship signals that would sharpen clustering and relationship inference.</li><li>What lives in your BI layer? Tableau calculated fields, Looker LookML dimensions, and Power BI measures encode business logic that belongs in your semantic layer — not re-invented by an LLM.</li><li>Can your data catalog feed Snowflake column comments? If your catalog already has curated descriptions, flowing them into Snowflake as column comments gives the SV creator agent high-quality input it can use directly rather than inferring from column names alone.</li><li>Is there internal documentation worth mining? Confluence pages, runbooks, and analytics team wikis often contain the business context that separates a good semantic view from a great one.</li></ul><p>Check out the pipeline: <a href="https://github.com/sfc-gh-kwells/snow-fsi-demos/tree/main/sv_automation">https://github.com/sfc-gh-kwells/snow-fsi-demos/tree/main/sv_automation</a> . I’d love to hear how others are thinking about the data mining problem and what signals have been most valuable in your own Snowflake implementations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b21e5d8eda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/scaling-semantic-layer-rollout-with-snowflake-cortex-code-agent-sdk-40b21e5d8eda">Scaling Semantic Layer Rollout with Snowflake Cortex Code Agent SDK</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying R Models in Snowflake’s Model Registry]]></title>
            <link>https://medium.com/snowflake/deploying-r-models-in-snowflakes-model-registry-effcf04dd85c?source=rss-32b2ac27f8b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/effcf04dd85c</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[model-training]]></category>
            <dc:creator><![CDATA[Kaitlyn Wells]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 20:03:03 GMT</pubDate>
            <atom:updated>2026-01-13T20:03:03.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Historically, <a href="https://docs.snowflake.com/en/developer-guide/snowflake-ml/model-registry/overview">Snowflake’s Model Registry</a> was limited to Python-based machine learning models using warehouse runtime. With model serving on <a href="https://docs.snowflake.com/en/developer-guide/snowflake-ml/model-registry/container">Snowpark Container Services</a> (SPCS), customers are no longer limited to Python. In this blog, I will show a robust solution for deploying custom R models to Snowflake’s Model Registry using a Python wrapper approach.</p><p>This method leverages SPCS to provide a production-ready environment where your R models can run seamlessly alongside your Snowflake data workflows.</p><h3>The Problem</h3><p>Organizations face several challenges when trying to deploy R models in Snowflake:</p><p>1. <strong>Native Support Limitation</strong>: Snowflake Model Registry only natively supports Python models</p><p>2. <strong>Deployment Complexity</strong>: Setting up the right runtime environment with both R and Python dependencies can be tricky especially when relying on specific packages as bridges</p><p>3. <strong>Inference at Scale</strong>: Running R models efficiently on large datasets requires proper containerization</p><h3>The Solution: Python Wrapper + SPCS</h3><p>Our solution involves three key components:</p><ol><li><strong>Python Wrapper Class</strong>: A `CustomModel` subclass that handles data serialization and calls R via subprocess</li><li><strong>R Prediction Script</strong>: A standalone R script that loads the model and generates predictions</li><li><strong>SPCS Deployment</strong>: Using Model Registry’s integration with Snowpark Container Services to provide a runtime environment with both R and Python</li></ol><p>This architecture allows you to:</p><ul><li>Keep your R model training workflow unchanged</li><li>Deploy models through Snowflake’s standard Model Registry interface</li><li>Run predictions at scale using SQL, Python, or REST APIs</li><li>Maintain full model lineage and versioning</li></ul><h3>Implementation Guide</h3><p><strong>Step 1: Train Your R Model</strong></p><p>First, train your R model as you normally would. Here’s an example using an ARIMAX time series model:</p><pre>library(forecast)<br><br>set.seed(42)<br><br># Generate synthetic time series data<br>n &lt;- 100<br>time_index &lt;- 1:n<br>trend &lt;- 0.5 * time_index<br>seasonal &lt;- 10 * sin(2 * pi * time_index / 12)<br>noise &lt;- rnorm(n, mean = 0, sd = 2)<br><br># Exogenous variables<br>exog_var1 &lt;- rnorm(n, mean = 5, sd = 1)<br>exog_var2 &lt;- rnorm(n, mean = 10, sd = 2)<br><br># Target variable<br>y &lt;- 50 + trend + seasonal + 2 * exog_var1 + 1.5 * exog_var2 + noise<br><br># Train ARIMAX model<br>xreg &lt;- cbind(exog_var1, exog_var2)<br>arimax_model &lt;- auto.arima(y, xreg = xreg, seasonal = TRUE)<br><br># Save model<br>saveRDS(arimax_model, file = &quot;arimax_model_artifact.rds&quot;)</pre><p><strong>Step 2: Create an R Prediction Script</strong></p><p>Create a standalone R script that can be called from Python to generate predictions:</p><pre>args &lt;- commandArgs(trailingOnly = TRUE)<br><br>if (length(args) != 3) {<br>  stop(&quot;Usage: Rscript predict_arimax.R &lt;model_path&gt; &lt;input_csv&gt; &lt;output_csv&gt;&quot;)<br>}<br><br>model_path &lt;- args[1]<br>input_csv &lt;- args[2]<br>output_csv &lt;- args[3]<br><br>library(forecast)<br><br># Load model<br>model &lt;- readRDS(model_path)<br><br># Load input data<br>input_data &lt;- read.csv(input_csv)<br><br>if (!all(c(&quot;exog_var1&quot;, &quot;exog_var2&quot;) %in% colnames(input_data))) {<br>  stop(&quot;Input data must contain columns: exog_var1, exog_var2&quot;)<br>}<br><br># Prepare exogenous variables<br>xreg_new &lt;- as.matrix(input_data[, c(&quot;exog_var1&quot;, &quot;exog_var2&quot;)])<br>n_ahead &lt;- nrow(input_data)<br><br># Generate predictions<br>predictions &lt;- forecast(model, xreg = xreg_new, h = n_ahead)<br><br># Format output<br>output_data &lt;- data.frame(<br>  forecast = as.numeric(predictions$mean),<br>  lower_80 = as.numeric(predictions$lower[, 1]),<br>  upper_80 = as.numeric(predictions$upper[, 1]),<br>  lower_95 = as.numeric(predictions$lower[, 2]),<br>  upper_95 = as.numeric(predictions$upper[, 2])<br>)<br><br># Save results<br>write.csv(output_data, output_csv, row.names = FALSE)<br>cat(&quot;Predictions saved to&quot;, output_csv, &quot;\n&quot;)</pre><p><strong>Step 3: Build the Python Wrapper</strong></p><p>Create a Python wrapper class that inherits from `CustomModel`:</p><pre>import subprocess<br>import tempfile<br>import os<br>import pandas as pd<br>from snowflake.ml.model import custom_model<br><br>class ARIMAXModelWrapper(custom_model.CustomModel):<br>    &quot;&quot;&quot;<br>    Python wrapper for R ARIMAX model to enable logging to Snowflake Model Registry.<br>    <br>    This wrapper handles:<br>    - Data serialization between Python and R (via CSV)<br>    - Subprocess execution of R prediction script<br>    - Error handling and validation<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, context: custom_model.ModelContext):<br>        &quot;&quot;&quot;<br>        Initialize the ARIMAX model wrapper.<br>        <br>        Args:<br>            context: ModelContext containing &#39;model_rds&#39; and &#39;predict_script&#39; artifacts<br>        &quot;&quot;&quot;<br>        super().__init__(context)<br>        <br>        # Load model bytes from context<br>        with open(self.context[&#39;model_rds&#39;], &#39;rb&#39;) as f:<br>            self.model_bytes = f.read()<br>        <br>        # Load prediction script from context<br>        with open(self.context[&#39;predict_script&#39;], &#39;r&#39;) as f:<br>            self.predict_script = f.read()<br>    <br>    def _write_temp_files(self) -&gt; tuple:<br>        &quot;&quot;&quot;Write model and script to temporary files for execution.&quot;&quot;&quot;<br>        temp_dir = tempfile.mkdtemp()<br>        <br>        model_path = os.path.join(temp_dir, &quot;model.rds&quot;)<br>        with open(model_path, &#39;wb&#39;) as f:<br>            f.write(self.model_bytes)<br>        <br>        script_path = os.path.join(temp_dir, &quot;predict.R&quot;)<br>        with open(script_path, &#39;w&#39;) as f:<br>            f.write(self.predict_script)<br>        <br>        return temp_dir, model_path, script_path<br>    <br>    @custom_model.inference_api<br>    def predict(self, X: pd.DataFrame) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;<br>        Make predictions using the R ARIMAX model.<br>        <br>        Args:<br>            X: DataFrame with exogenous variables<br>        <br>        Returns:<br>            DataFrame with forecast and confidence intervals<br>        &quot;&quot;&quot;<br>        required_cols = [&#39;exog_var1&#39;, &#39;exog_var2&#39;]<br>        if not all(col in X.columns for col in required_cols):<br>            raise ValueError(f&quot;Input DataFrame must contain columns: {required_cols}&quot;)<br>        <br>        temp_dir, model_path, script_path = self._write_temp_files()<br>        <br>        try:<br>            input_csv = os.path.join(temp_dir, &quot;input.csv&quot;)<br>            output_csv = os.path.join(temp_dir, &quot;output.csv&quot;)<br>            <br>            # Write input data<br>            X[required_cols].to_csv(input_csv, index=False)<br>            <br>            # Call R script<br>            cmd = [&quot;Rscript&quot;, script_path, model_path, input_csv, output_csv]<br>            <br>            result = subprocess.run(<br>                cmd,<br>                capture_output=True,<br>                text=True,<br>                check=True,<br>                timeout=300<br>            )<br>            <br>            if not os.path.exists(output_csv):<br>                raise RuntimeError(f&quot;R script did not produce output file.&quot;)<br>            <br>            # Read predictions<br>            predictions = pd.read_csv(output_csv)<br>            return predictions<br>            <br>        except subprocess.CalledProcessError as e:<br>            raise RuntimeError(<br>                f&quot;R prediction script failed.\n&quot;<br>                f&quot;Return code: {e.returncode}\n&quot;<br>                f&quot;stdout: {e.stdout}\n&quot;<br>                f&quot;stderr: {e.stderr}&quot;<br>            )<br>        except subprocess.TimeoutExpired:<br>            raise RuntimeError(&quot;R prediction script timed out after 300 seconds&quot;)<br>        finally:<br>            import shutil<br>            if os.path.exists(temp_dir):<br>                shutil.rmtree(temp_dir)</pre><p><strong>Step 4: Upload Artifacts to Snowflake Stage</strong></p><p>Upload your R model and prediction script to a Snowflake stage:</p><pre>from snowflake.snowpark import Session<br><br># Create connection<br>session = Session.builder.configs({<br>    &quot;connection_name&quot;: &quot;your_connection&quot;<br>}).create()<br><br># Create stage if needed<br>session.sql(&quot;&quot;&quot;<br>CREATE STAGE IF NOT EXISTS ML_ARTIFACTS_STAGE<br>    DIRECTORY = (ENABLE = TRUE)<br>    COMMENT = &#39;Stage for ML artifacts&#39;<br>&quot;&quot;&quot;).collect()<br><br># Upload files<br>session.sql(&quot;&quot;&quot;<br>PUT file:///path/to/arimax_model_artifact.rds <br>@ML_ARTIFACTS_STAGE/r_models/ <br>AUTO_COMPRESS=FALSE OVERWRITE=TRUE<br>&quot;&quot;&quot;).collect()<br><br>session.sql(&quot;&quot;&quot;<br>PUT file:///path/to/predict_arimax.R<br>@ML_ARTIFACTS_STAGE/r_models/<br>AUTO_COMPRESS=FALSE OVERWRITE=TRUE<br>&quot;&quot;&quot;).collect()<br><br>session.sql(&quot;&quot;&quot;<br>PUT file:///path/to/r_model_wrapper.py<br>@ML_ARTIFACTS_STAGE/r_models/<br>AUTO_COMPRESS=FALSE OVERWRITE=TRUE<br>&quot;&quot;&quot;).collect()</pre><p><strong>Step 5: Register the Model</strong></p><p>Now you can register your R model in Snowflake’s Model Registry:</p><pre>from snowflake.ml.registry import Registry<br>from snowflake.ml.model import custom_model<br>from snowflake.ml.model.model_signature import ModelSignature, FeatureSpec, DataType<br>import pandas as pd<br><br># Download artifacts from stage<br>session.file.get(&quot;@ML_ARTIFACTS_STAGE/r_models/arimax_model_artifact.rds&quot;, &quot;/tmp/&quot;)<br>session.file.get(&quot;@ML_ARTIFACTS_STAGE/r_models/predict_arimax.R&quot;, &quot;/tmp/&quot;)<br>session.file.get(&quot;@ML_ARTIFACTS_STAGE/r_models/r_model_wrapper.py&quot;, &quot;/tmp/&quot;)<br><br># Import wrapper<br>import sys<br>sys.path.insert(0, &quot;/tmp&quot;)<br>from r_model_wrapper import ARIMAXModelWrapper<br><br># Create ModelContext<br>model_context = custom_model.ModelContext(<br>    model_rds=&#39;/tmp/arimax_model_artifact.rds&#39;,<br>    predict_script=&#39;/tmp/predict_arimax.R&#39;<br>)<br><br># Instantiate wrapper<br>my_model = ARIMAXModelWrapper(model_context)<br><br># Define model signature (avoids local execution which would fail without R)<br>predict_signature = ModelSignature(<br>    inputs=[<br>        FeatureSpec(name=&quot;exog_var1&quot;, dtype=DataType.DOUBLE),<br>        FeatureSpec(name=&quot;exog_var2&quot;, dtype=DataType.DOUBLE)<br>    ],<br>    outputs=[<br>        FeatureSpec(name=&quot;forecast&quot;, dtype=DataType.DOUBLE),<br>        FeatureSpec(name=&quot;lower_80&quot;, dtype=DataType.DOUBLE),<br>        FeatureSpec(name=&quot;upper_80&quot;, dtype=DataType.DOUBLE),<br>        FeatureSpec(name=&quot;lower_95&quot;, dtype=DataType.DOUBLE),<br>        FeatureSpec(name=&quot;upper_95&quot;, dtype=DataType.DOUBLE)<br>    ]<br>)<br><br># Initialize Registry<br>reg = Registry(<br>    session=session,<br>    database_name=&#39;MY_DB&#39;,<br>    schema_name=&#39;MY_SCHEMA&#39;<br>)<br><br># Log model to registry<br>model_version = reg.log_model(<br>    my_model,<br>    model_name=&quot;ARIMAX_R_MODEL&quot;,<br>    version_name=&quot;V1&quot;,<br>    target_platforms=[&quot;SNOWPARK_CONTAINER_SERVICES&quot;],<br>    conda_dependencies=[<br>        &quot;r-base&gt;=4.1&quot;,<br>        &quot;r-forecast&quot;<br>    ],<br>    signatures={&quot;predict&quot;: predict_signature},<br>    comment=&quot;R ARIMAX model wrapped in Python for Snowflake Model Registry&quot;<br>)<br><br>print(f&quot;✓ Model logged successfully!&quot;)</pre><p><strong>Step 6: Create SPCS Resources</strong></p><p>Create a compute pool and image repository for deployment:</p><pre>session.sql(&quot;&quot;&quot;<br>CREATE COMPUTE POOL IF NOT EXISTS R_MODEL_POOL<br>    MIN_NODES = 1<br>    MAX_NODES = 2<br>    INSTANCE_FAMILY = &#39;CPU_X64_M&#39;<br>    AUTO_RESUME = TRUE<br>    COMMENT = &#39;Compute pool for R model inference&#39;<br>&quot;&quot;&quot;).collect()<br><br># Create image repository<br>session.sql(&quot;&quot;&quot;<br>CREATE IMAGE REPOSITORY IF NOT EXISTS R_MODEL_IMAGE_REPO<br>    COMMENT = &#39;Repository for R model container images&#39;<br>&quot;&quot;&quot;).collect()<br><br>print(&quot;✓ SPCS resources created&quot;)</pre><p><strong>Step 7: Deploy to SPCS</strong></p><p>Deploy your model to Snowpark Container Services:</p><pre># Deploy model<br>model_version.create_service(<br>    service_name=&quot;arimax_deployment&quot;,<br>    service_compute_pool=&quot;R_MODEL_POOL&quot;,<br>    image_repo=&quot;R_MODEL_IMAGE_REPO&quot;,<br>    ingress_enabled=True,<br>    max_instances=1<br>)<br><br>print(&quot;✓ Model deployed to SPCS&quot;)<br>print(&quot;Building container image... (5-10 minutes for first deployment)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lq6cHpS1gcKv6P_OjP7nFA.png" /></figure><p><strong>Step 8: Run Predictions</strong></p><p>Once deployed, you can call your model either using the Python API or HTTP Endpoint.</p><p><strong>Python API</strong></p><pre># Prepare test data<br>test_data = pd.DataFrame({<br>    &#39;exog_var1&#39;: [5.0, 5.5, 4.8],<br>    &#39;exog_var2&#39;: [10.0, 11.0, 9.5]<br>})<br><br># Run prediction<br>predictions = model_version.run(<br>    session.create_dataframe(test_data),<br>    function_name=&quot;predict&quot;,<br>    service_name=&quot;arimax_deployment&quot;<br>)<br><br>predictions.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBW5wc365exdkdirog4hLQ.png" /></figure><p><strong>HTTP Endpoint</strong></p><pre>import requests<br>import os<br><br># Get endpoint URL<br>endpoints = model_version.show_endpoints(service_name=&quot;arimax_deployment&quot;)<br>endpoint_url = endpoints[&#39;ingress_url&#39;][0] + &quot;/predict&quot;<br><br># Prepare request<br>data = {<br>    &quot;data&quot;: [<br>        [0, 5.0, 10.0],  # [row_number, exog_var1, exog_var2]<br>        [1, 5.5, 11.0],<br>        [2, 4.8, 9.5]<br>    ]<br>}<br><br># Call endpoint with PAT token<br>headers = {<br>    &quot;Authorization&quot;: f&#39;Bearer Token=&quot;{os.getenv(&quot;SNOWFLAKE_PAT&quot;)}&quot;&#39;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>}<br><br>response = requests.post(endpoint_url, json=data, headers=headers)<br>print(response.json())</pre><h4>Summary</h4><p>Deploying custom R models in Snowflake doesn’t have to be complicated. By combining a Python wrapper with Snowpark Container Services, you can leverage Snowflake’s Model Registry infrastructure while keeping your R modeling workflows intact.</p><p>This approach is:</p><ul><li><strong>Production-ready</strong>: Proper error handling, monitoring, and scaling</li><li><strong>Maintainable</strong>: Clean separation between R and Python code</li><li><strong>Flexible</strong>: Works with any R model that can be serialized with `saveRDS()`</li><li><strong>Scalable</strong>: Leverages SPCS for distributed inference</li></ul><p>The same pattern can be extended to other non-Python models (Julia, Stan, etc.) by adapting the wrapper to call the appropriate runtime via subprocess.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=effcf04dd85c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/deploying-r-models-in-snowflakes-model-registry-effcf04dd85c">Deploying R Models in Snowflake’s Model Registry</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Costs for Batch LLM Classification with Snowflake Cortex Search]]></title>
            <link>https://medium.com/snowflake/improving-costs-for-batch-llm-classification-with-snowflake-cortex-search-5f73be5868d4?source=rss-32b2ac27f8b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f73be5868d4</guid>
            <category><![CDATA[cortex]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cortex-search]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Kaitlyn Wells]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 13:06:56 GMT</pubDate>
            <atom:updated>2025-01-27T13:06:56.252Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>We used Cortex Search with Cortex Complete to achieve 51x costs saving for a text classification use case</blockquote><p>Imagine you have to map a dataset of over a 1 million records to your company’s hierarchy that includes 1,000 categories. Today, this mapping process can span several weeks and involves 100+ hours of human validation even when combined with traditional Natural Language Processing (NLP) techniques. With Large Language Models (LLMs), this mapping process can be expedited to under a week because LLMs have a higher accuracy at classifying text compared to traditional NLP techniques as discussed by Wang et al. in their <a href="https://arxiv.org/html/2405.10523v1">whitepaper</a><em>.</em></p><h4>Enterprise Examples</h4><p><strong>Healthcare:</strong> Health insurance companies regularly need to categorize each provider’s location across different types of locations and specialities to power their consumer facing provider directories. For instance, they require the use of location names and associated metadata to categorize a location as a hospital, and further sub-classify individual buildings by specialty departments( e.g. radiology, orthopedics).</p><p><strong>Retailers</strong>: Another example is for retailers, where each of their product SKUs are mapped to one or multiple categories. This mapping structure can be used to associate advertising keywords to each product, power their user interface and glue third party datasets for enhanced analytics (e.g. competitor consumer trends).</p><h4>What is the problem?</h4><p>Consider my customer’s use case of mapping over a 1 million records to their company’s hierarchy of 1,000 categories. For each record, the classification prompt would ask the LLM to categorize the record as one of the 1,000 categories. This approach would be very costly because each LLM call is priced per token.</p><h4>Solution</h4><p>In this blog, I’m sharing an approach that we used that leverages Cortex Search to decrease costs by 51x by reducing the number of categories in each LLM call without sacrificing accuracy. <a href="https://docs.snowflake.com/user-guide/snowflake-cortex/cortex-search/cortex-search-overview?utm_cta=website-resources-vhol">Snowflake’s Cortex Search</a> is a vector database that manages embeddings, indexing and retrieval. Cortex Search uses a hybrid approach to retrieving and reranking results which combines vector search, keyword search and semantic reranking to <a href="https://www.snowflake.com/engineering-blog/cortex-search-and-retrieval-enterprise-ai/">achieve high search quality out of the box</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxz1JrlHOOH-2trwaz7n-w.png" /></figure><h4>How does it work?</h4><p>In this example, I have a dataset of 1,000 product categories that you can find at a discount department store or grocery such as “Household Supplies” or “Personal Care”. I need to classify each product (1 million SKUs) as one of the 1,000 categories. For the product “FreshGuard All-Purpose Cleaning Spray — Lemon Breeze”, I want it to be classified as “Household Supplies”. Instead of including all 1,000 categories in the LLM prompt, Cortex Search can scan all categories and identify the top <em>N</em> most relevant categories for “FreshGuard All-Purpose Cleaning Spray — Lemon Breeze”.</p><ol><li><strong>Cortex Search Service: </strong>I create a Cortex Search Service on 1,000 product categories. With a target lag of 1 day, each day the Cortex Search Service will check whether the underlying table data changes and update the corresponding vector embeddings.</li><li><strong>Retrieve:</strong> For each product, I retrieve the 10 most relevant categories from my Cortex Search Service mapping_search_service.</li><li><strong>Inference</strong>: I use Cortex Complete with Mistral Large LLM to classify the product as one of the 10 categories.</li></ol><pre>CREATE OR REPLACE CORTEX SEARCH SERVICE mapping_search_service<br>  ON product_category<br>  WAREHOUSE = cortex_search_wh<br>  TARGET_LAG = &#39;1 day&#39;<br>  AS (<br>    SELECT<br>        distinct product_category<br>    FROM  RETAILERS.PUBLIC.RETAIL_CATEGORIES<br>);</pre><pre>from snowflake.cortex import Complete<br>from snowflake.core import Root<br>#Use the product input to 1) query Cortex Search service and 2) call Cortex Complete to generate a category<br>def classify(session,product_input):<br>    root = Root(session)<br>    mapping_search_service = (root<br>      .databases[&quot;RETAILERS&quot;]<br>      .schemas[&quot;PUBLIC&quot;]<br>      .cortex_search_services[&quot;mapping_search_service&quot;]<br>    )<br>    resp = mapping_search_service.search(<br>      query=product_input,<br>      columns=[ &quot;product_category&quot;],<br>      limit=10<br>    )<br>    results, request_id = resp<br>  <br>    label, product_list = results<br>    product_categories_results = [item[&#39;product_category&#39;] for item in product_list]<br>    string_product_categories = &quot;,&quot;.join(product_categories_results)<br>    prompt_part1 = &#39;Please categorize each retail grocery store item as one of the following categories:&#39;<br>    prompt_part2 = &#39;Only include JSON in the output and not other output. Use this Grocery Item: &#39;<br>    <br>    #Concatenating a string to pass to the LLM which includes the Cortex Search results and product string as variables<br>    complete_prompt = prompt_part1 + string_product_categories +  prompt_part2 + product_input<br>    action = Complete(&#39;mistral-large&#39;, complete_prompt)<br>    return action<br><br>test = classify(session,&#39;FreshGuard All-Purpose Cleaning Spray - Lemon Breeze&#39;)</pre><h4>Results</h4><p>In the chart, it’s clear how each Cortex Complete call is <strong>51x more expensive</strong> when all 1,000 categories are included (7,673 tokens) vs the top 10 returned by the Cortex Search Service (149 tokens). This can yield significant cost savings at scale and expedites the process from weeks to days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INpRTAtb_xu_f8gBTwJXDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQbQCdOmyYtW9GvSSBxpgQ.png" /></figure><h4>Lessons Learned</h4><ul><li><strong>Latency</strong>: There’s some added latency to perform each Cortex Search call before Cortex Complete.</li><li><strong>Accuracy: </strong>There’s a risk that the “correct” category isn’t in the top 10 results from Cortex Search but that will highly depend on how similar your data is.</li></ul><h4>Latency</h4><p>Each Cortex Search call is quite fast (300ms on average). However, Cortex Search is a transactional system designed for interactive workloads. From my own testing, I was able to execute 20 search queries per second before throttling occurred. The Snowflake product team is working on updates to make usage more seamless for batch and offline search jobs to remove any bottlenecks at scale. We have an example on how to call Cortex Search concurrently in <a href="https://github.com/Snowflake-Labs/cortex-search/blob/main/examples/python_sdk/concurrent-example.py">this github repo</a>.</p><h4>Accuracy</h4><p>One of my customers tested this technique and found that 85% of the time the “correct” category was within the top 4 results returned by the Cortex Search Service. The quality of the search results is going to vary based on how distinct your categories are. To mitigate this risk, add metadata to help with the retrieval accuracy and/or increase the number of results returned.</p><h4>What else can you do with this?</h4><p>In addition to using Cortex Search to return the top 10 categories, you can add more data to each category to improve the LLM prompting, such as several historical examples for few shot learning.</p><p>You can also test the accuracy of only using Cortex Search to classify text and remove the use of Cortex Complete (LLM Inference) for both cost and performance improvements.</p><h4>Key Takeaways</h4><p>Cortex Search can be used with Cortex Complete for batch classification use cases:</p><ul><li>Lower LLM costs</li><li>Improve accuracy with each LLM prompt customized based on the input</li><li>Expedite the time to value for mapping use cases with automation</li></ul><p><strong><em>Disclaimer</em></strong><em>: The opinions expressed in this post are my own and not necessarily those of my employer (Snowflake).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f73be5868d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/improving-costs-for-batch-llm-classification-with-snowflake-cortex-search-5f73be5868d4">Improving Costs for Batch LLM Classification with Snowflake Cortex Search</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>