<?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 Payam Mokhtarian on Medium]]></title>
        <description><![CDATA[Stories by Payam Mokhtarian on Medium]]></description>
        <link>https://medium.com/@payam.mokhtarian?source=rss-8c0af3aba6db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aNa51BV4RVo9YeebqCqjQg.jpeg</url>
            <title>Stories by Payam Mokhtarian on Medium</title>
            <link>https://medium.com/@payam.mokhtarian?source=rss-8c0af3aba6db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:48:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@payam.mokhtarian/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[Building Programmable AI Agents on Snowflake: A Deep Dive into the Cortex Code Agent SDK]]></title>
            <link>https://medium.com/snowflake/building-programmable-ai-agents-on-snowflake-a-deep-dive-into-the-cortex-code-agent-sdk-811be94b004e?source=rss-8c0af3aba6db------2</link>
            <guid isPermaLink="false">https://medium.com/p/811be94b004e</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cortex-code]]></category>
            <dc:creator><![CDATA[Payam Mokhtarian]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-04-24T17:01:01.763Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Turn Cortex Code from an interactive CLI into a programmable engine for autonomous AI workflows running locally on your machine or server-side inside Snowflake.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMZMTCehpG89_Ch1AKQrrg.png" /><figcaption>From local scripts to autonomous AI workflows in the AI Data Cloud</figcaption></figure><p>The jump from “it works in chat” to “it works in production” is usually where things fall apart. Chat is fine for one-off snippets, but it’s not an automation strategy. Once you need to orchestrate complex tasks, like running agents inside server-side workflows or to run agents inside CI/CD, you need a programmable engine, not a text box.</p><p>The <strong>Cortex Code Agent SDK</strong> (or the “CoCo” SDK) is Snowflake’s answer to this. It takes the same agentic engine used in the CLI and wraps it in a programmable interface. Instead of you driving the agent, your code does. If you’ve ever wanted to spawn an AI assistant that can actually do things inside your server-side workflows, this is the toolkit you’ve been looking for.</p><h3>What are we actually talking about?</h3><p>If you’ve been using Snowflake lately, you’ve likely seen <strong>Cortex Code</strong>. It’s their CLI agent that doesn’t just “suggest” code — it actually reasons through a task, reads your local files, runs SQL, and iterates until it hits the goal.</p><p>Under the hood, it’s tapping into high-end models like Claude Sonnet 4.6 or OpenAI GPT-5.x. The SDK just gives you a way to hook into that loop programmatically.</p><h3>CLI vs. SDK: The Real Difference</h3><ul><li><strong>The CLI</strong> is for you, sitting at your desk, watching the terminal loop in real-time.</li><li><strong>The SDK</strong> is for your “headless” tasks. It’s for the Python script running at 2 AM that needs to inspect 100 tables, optimise a view, and generate a report without you babysitting it.</li></ul><h3>Why bother with the SDK?</h3><p>Automation is the obvious answer, but the actual “why” comes down to control:</p><ul><li><strong>Repeatability:</strong> Running the same agentic audit across a massive codebase without getting carpal tunnel.</li><li><strong>Conditional Logic:</strong> Your Python code can “gate” the agent. For example: <em>If the security scan finds a high-risk bug, call the agent to fix it. If not, just move on.</em></li><li><strong>Structured Output:</strong> Instead of the agent giving you a chatty paragraph, you can force it to return <strong>typed JSON</strong> so your downstream code can actually use the data.</li><li><strong>Custom Tools (MCP):</strong> You can plug the agent into your internal APIs (like Jira or Slack) using the Model Context Protocol.</li></ul><p>The SDK transforms Cortex Code from a human-in-the-loop assistant into a <strong>programmable agentic engine</strong> that your Python or TypeScript code orchestrates.</p><h3>Use Cases</h3><p>Here are concrete scenarios where the SDK shines:</p><ul><li><strong>Automated code review</strong>: Scan every PR for bugs, security issues, or style violations and return structured findings.</li><li><strong>Data pipeline validation</strong>: After an ETL run, have an agent inspect table schemas, validate data quality, and generate a report.</li><li><strong>Semantic view optimisation</strong>: Multi-turn pipeline that inspects Snowflake tables, optimises a semantic view, creates search services, and integrates them all autonomously.</li><li><strong>Codebase migration</strong>: Analyse files for deprecated patterns and apply fixes across an entire repository.</li><li><strong>Feature engineering in ML</strong>: Agentically explore a dataset, generate candidate features, evaluate them, and select the best subset for a model.</li><li><strong>Incident response automation</strong>: When an alert fires, have an agent read logs, trace the issue, and propose a fix.</li></ul><h3>Setting the Foundation</h3><h4>Install the CLI and SDK</h4><p>You’ll need the CLI and the SDK package. Install Cortex Code CLI:</p><pre>curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh</pre><p>Install the SDK from PyPI (Python ≥ 3.10):</p><pre>pip install cortex-code-agent-sdk</pre><h4>Establishing a Snowflake Connection</h4><p>The SDK piggybacks off your existing ~/.snowflake/connections.toml. This is a huge win because you don&#39;t have to manage a new set of credentials.</p><p><strong>Step 1: Configure your connection file<br></strong>Create or edit ~/.snowflake/connections.toml:</p><pre>[dev-connection]<br>account = &quot;myorg-dev&quot;<br>user = &quot;dev_user&quot;<br>authenticator = &quot;externalbrowser&quot; # Keeps things simple with SSO<br>role = &quot;ENGINEER_ROLE&quot;<br>warehouse = &quot;COMPUTE_WH&quot;</pre><p><strong>Step 2: Verify your connection works</strong></p><pre>cortex --connection my-connection --print &quot;G&#39;day!&quot;</pre><p><strong>Step 3: Pass the connection to the SDK</strong></p><pre>from cortex_code_agent_sdk import query, CortexCodeAgentOptions<br><br># Explicit connection name<br>options = CortexCodeAgentOptions(<br>    connection=&quot;my-connection&quot;,<br>    cwd=&quot;.&quot;,<br>)<br><br># Or omit &#39;connection&#39; to use default_connection_name from the toml file<br>options = CortexCodeAgentOptions(cwd=&quot;.&quot;)</pre><p>The connection option maps directly to the CLI&#39;s --connection flag. The SDK spawns the CLI subprocess, which authenticates using the specified (or default) connection profile.</p><h4>Minimal Working Example</h4><pre>import asyncio<br>import json<br><br>async def main():<br>    proc = await asyncio.create_subprocess_exec(<br>        &quot;cortex&quot;,<br>        &quot;-p&quot;, &quot;What files are in this directory?&quot;,<br>        &quot;--output-format&quot;, &quot;stream-json&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Read&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Glob&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Grep&quot;,<br>        stdout=asyncio.subprocess.PIPE,<br>        stderr=asyncio.subprocess.PIPE,<br>    )<br>    while True:<br>        line = await proc.stdout.readline()<br>        if not line:<br>            break<br>        text = line.decode().strip()<br>        if not text:<br>            continue<br>        try:<br>            msg = json.loads(text)<br>        except json.JSONDecodeError:<br>            continue<br>        if msg.get(&quot;type&quot;) == &quot;assistant&quot;:<br>            for block in msg.get(&quot;message&quot;, {}).get(&quot;content&quot;, []):<br>                if block.get(&quot;type&quot;) == &quot;text&quot;:<br>                    print(block[&quot;text&quot;], end=&quot;&quot;)<br>        elif msg.get(&quot;type&quot;) == &quot;result&quot;:<br>            print(f&quot;\nDone: {msg.get(&#39;subtype&#39;, &#39;unknown&#39;)}&quot;)<br>    await proc.wait()<br>asyncio.run(main())</pre><h4>Two API Patterns at a Glance</h4><p>Before diving into architecture and examples, here’s a quick look at the two main ways to use the SDK:</p><p><strong>Single-Turn — </strong>Send a prompt, consume the NDJSON (newline-delimited JSON) stream, done.</p><pre>proc = await asyncio.create_subprocess_exec(<br>    &quot;cortex&quot;,<br>    &quot;-p&quot;, &quot;Review utils.py for bugs. Fix any issues you find.&quot;,<br>    &quot;--output-format&quot;, &quot;stream-json&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Read&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Edit&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Glob&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Grep&quot;,<br>    stdout=asyncio.subprocess.PIPE,<br>    stderr=asyncio.subprocess.PIPE,<br>)<br># ... parse NDJSON lines from proc.stdout</pre><p><strong>Multi-Turn</strong> — Chain multiple prompts by spawning sequential CLI invocations, or use the SDK client for persistent sessions.</p><pre>## Turn 1<br>proc1 = await asyncio.create_subprocess_exec(<br>    &quot;cortex&quot;,<br>    &quot;-p&quot;, &quot;Inspect the schema and optimise the semantic view&quot;,<br>    &quot;--output-format&quot;, &quot;stream-json&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Read&quot;, &quot;--allowed-tools&quot;, &quot;Glob&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Grep&quot;, &quot;--allowed-tools&quot;, &quot;Edit&quot;,<br>    stdout=asyncio.subprocess.PIPE,<br>    stderr=asyncio.subprocess.PIPE,<br>)<br># ... parse NDJSON lines from proc1.stdout<br>await proc1.wait()<br><br>## Turn 2: Launch another agent that builds on the file changes from Turn 1<br>proc2 = await asyncio.create_subprocess_exec(<br>    &quot;cortex&quot;,<br>    &quot;-p&quot;, &quot;Now create search services for text columns&quot;,<br>    &quot;--output-format&quot;, &quot;stream-json&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Read&quot;, &quot;--allowed-tools&quot;, &quot;Write&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Glob&quot;, &quot;--allowed-tools&quot;, &quot;Grep&quot;,<br>    stdout=asyncio.subprocess.PIPE,<br>    stderr=asyncio.subprocess.PIPE,<br>)<br># ... parse NDJSON lines from proc2.stdout<br>await proc2.wait()</pre><h3>Where does this actually live?</h3><p>A key architectural point is the Cortex Code Agent SDK runs in <strong>two environments</strong>, giving you flexibility in how you deploy your agentic workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_04DBkYYIThHPCJV6Qi1Q.png" /><figcaption>Agentic workflow</figcaption></figure><h4>Client-Side (Outside Snowflake)</h4><p>This is any environment you control that isn’t Snowflake itself — your laptop, an virtual machine, a GitHub Actions runner, a Docker container. Your Python or TypeScript script runs there, the SDK spawns the Cortex CLI as a <strong>subprocess</strong>, communicates via stdin/stdout using an NDJSON stream, and the CLI handles the full agent loop including LLM calls through Snowflake Cortex.</p><p><strong>When to use</strong>: Development workflows, CI/CD pipelines, local automation scripts, any scenario where you need filesystem access to a project directory.</p><h4>Server-Side (Inside Snowflake)</h4><p>The SDK can also run <strong>inside Snowflake</strong> itself. For example, within a Snowpark Container Services (SPCS) container, a Snowflake Notebook, or a Stored Procedure. In this mode, the agent operates on server-side resources (e.g., Snowflake stages, internal tables, and Snowflake-hosted files).</p><p><strong>When to use</strong>: Data-centric workflows where the agent needs to operate on Snowflake-native resources, governance-sensitive environments where data shouldn’t leave Snowflake, or scheduled jobs that run entirely within the platform.</p><h3>SDK Architecture</h3><p>Understanding the architecture helps you reason about what happens when your code calls query() or creates a CortexCodeSDKClient. Here&#39;s the full picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6ci2DlctCVJqhargifYJA.png" /><figcaption>Cortex Code SDK Architecture</figcaption></figure><h3>Key Architectural Concepts</h3><p><strong>1. Subprocess Communication<br></strong>Your code never talks to the LLM directly. The SDK spawns Cortex as a child process and communicates through an NDJSON stream on stdout. Each line is a typed message — SystemMessage, AssistantMessage, ResultMessage, or StreamEvent.</p><p><strong>2. The Agent Loop<br></strong>When you send a prompt, the agent enters an autonomous reasoning loop:</p><ul><li><strong>Reason</strong>: The LLM reads context and decides what to do.</li><li><strong>Act</strong>: The agent calls a tool (Read a file, execute SQL, edit code…).</li><li><strong>Observe</strong>: The agent sees the tool’s output.</li><li><strong>Decide</strong>: Is the task done? If not, loop back to Reason.</li></ul><p>A single prompt like “Fix the bug in code.py” might trigger multiple iterations including reading the file, identifying the issue, applying a fix, verifying the edit.</p><p><strong>3. You Control vs. Agent Decides</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*DB3zILx6D52rLki3N6S95g.png" /><figcaption>Control and decisions</figcaption></figure><p><strong>4. Permission Model<br></strong>The SDK offers granular control over tool execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*5JF9u6rJULj0q11eTMpbig.png" /><figcaption>Control over tool execution</figcaption></figure><p><strong>5. Message Stream<br></strong>Every interaction produces typed messages you consume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*-AwUz9jHAknrqEaVO14gfA.png" /><figcaption>Typed messages</figcaption></figure><p>An AssistantMessage contains <strong>content blocks</strong>: TextBlock (reasoning text), ToolUseBlock (a tool call), ToolResultBlock (tool output), or ThinkingBlock (chain-of-thought).</p><p><strong>6. Skills Carry Over<br></strong>Cortex Code ships with a library of built-in skills. These skills are not exclusive to the interactive CLI. When you run the agent through the SDK, the full set of skills remains available. If a prompt matches a skill’s domain, the agent activates it the same way it would in a terminal session.</p><p><strong>7. MCP Integration<br></strong>The SDK supports the <strong>Model Context Protocol</strong> for custom tools. In Python, you can define tools inline using the @tool decorator and create_sdk_mcp_server(), which runs an MCP server in the same process (no external server required). Note that as of this SDK version, MCP is the only supported path for custom tool integration.</p><h3>Example 1: The “Hands-Off” Bug Hunter</h3><p>I wanted to see if I could point the SDK at a broken script and have it “auto-heal” the code without any human intervention. I used a simple buggy_calculator.py with some classic ZeroDivisionError and KeyError traps.</p><h4>The Buggy File</h4><p>Create buggy_calculator.py:</p><pre># buggy_calculator.py<br>import json<br>from datetime import datetime<br><br>def calculate_average(numbers):<br>    total = 0<br>    for num in numbers:<br>        total += num<br>    return total / len(numbers)  # Bug: ZeroDivisionError on empty list<br><br>def parse_user_config(config_string):<br>    config = json.loads(config_string)<br>    return {<br>        &quot;username&quot;: config[&quot;user&quot;][&quot;name&quot;].strip(),    # Bug: KeyError if &quot;user&quot; or &quot;name&quot; missing<br>        &quot;timeout&quot;: int(config[&quot;settings&quot;][&quot;timeout&quot;]), # Bug: KeyError if nested keys missing<br>        &quot;created&quot;: datetime.strptime(<br>            config[&quot;metadata&quot;][&quot;created_at&quot;],          # Bug: KeyError if key missing<br>            &quot;%Y-%m-%d&quot;<br>        ),<br>    }<br><br>def find_outliers(data, threshold):<br>    mean = sum(data) / len(data)  # Bug: ZeroDivisionError on empty list<br>    std_dev = (sum((x - mean) ** 2 for x in data) / len(data)) ** 0.5  # Same bug<br>    return [x for x in data if abs(x - mean) &gt; threshold * std_dev]<br><br>def merge_sorted_lists(list_a, list_b):<br>    result = []<br>    i, j = 0, 0<br>    while i &lt; len(list_a) and j &lt; len(list_b):<br>        if list_a[i] &lt;= list_b[j]:<br>            result.append(list_a[i])<br>            i += 1<br>        else:<br>            result.append(list_b[j])<br>            j += 1<br>    # Bug: remaining elements from both lists are never appended<br>    return result</pre><h4>The Agent Script</h4><p>This script invokes the Cortex Code CLI as a subprocess, streaming NDJSON output in real time while the agent finds and fixes every bug:</p><pre># fix_bugs.py<br>import asyncio<br>import json<br><br>PROMPT = &quot;&quot;&quot;<br>Review the file buggy_calculator.py for bugs that would cause crashes or incorrect results.<br>For each bug you find:<br>1. Explain what the bug is and when it would trigger<br>2. Fix the bug in the file<br>Be thorough -- check for edge cases like empty inputs, missing keys, and incomplete logic.<br>&quot;&quot;&quot;<br>async def main():<br>    print(&quot;Agent starting bug analysis...\n&quot;)<br>    proc = await asyncio.create_subprocess_exec(<br>        &quot;cortex&quot;,<br>        &quot;-p&quot;, PROMPT,<br>        &quot;--output-format&quot;, &quot;stream-json&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Read&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Write&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Edit&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Glob&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Grep&quot;,<br>        &quot;--allowed-tools&quot;, &quot;Bash&quot;,<br>        stdout=asyncio.subprocess.PIPE,<br>        stderr=asyncio.subprocess.PIPE,<br>    )<br>    while True:<br>        line = await proc.stdout.readline()<br>        if not line:<br>            break<br>        text = line.decode().strip()<br>        if not text:<br>            continue<br>        try:<br>            msg = json.loads(text)<br>        except json.JSONDecodeError:<br>            continue<br>        msg_type = msg.get(&quot;type&quot;)<br>        if msg_type == &quot;assistant&quot;:<br>            content = msg.get(&quot;message&quot;, {}).get(&quot;content&quot;, [])<br>            for block in content:<br>                if block.get(&quot;type&quot;) == &quot;text&quot;:<br>                    print(block[&quot;text&quot;], end=&quot;&quot;)<br>                elif block.get(&quot;type&quot;) == &quot;tool_use&quot;:<br>                    print(f&quot;\n&gt; Tool: {block[&#39;name&#39;]}&quot;)<br>        elif msg_type == &quot;result&quot;:<br>            subtype = msg.get(&quot;subtype&quot;, &quot;unknown&quot;)<br>            duration = msg.get(&quot;duration_ms&quot;, 0)<br>            if subtype == &quot;success&quot;:<br>                print(f&quot;\n\nAll bugs fixed successfully. ({duration}ms)&quot;)<br>            else:<br>                print(f&quot;\n\nAgent finished with status: {subtype} ({duration}ms)&quot;)<br>    await proc.wait()<br>asyncio.run(main())</pre><p>When you run python fix_bugs.py, the agent will:</p><ol><li><strong>Read</strong> buggy_calculator.py to understand the code</li><li><strong>Reason</strong> about each function and identify edge cases</li><li><strong>Edit</strong> the file multiple times — adding empty-list guards, safe key access with .get(), and appending remaining elements in merge_sorted_lists</li><li><strong>Report</strong> what it fixed and why</li></ol><p>You see the full stream of reasoning, tool calls, and edits in real time. The fixed file is written back to disk (no manual intervention needed).</p><p>Here&#39;s what the agent produces (reasoning abbreviated for clarity):</p><pre>Agent starting bug analysis...<br><br>I&#39;ll review buggy_calculator.py for bugs that could cause crashes or incorrect results.<br><br><strong>&gt; Tool: Read<br></strong><br>I&#39;ve read the file. Let me analyse each function for bugs.<br><br>**Bug 1: `calculate_average` -- ZeroDivisionError on empty list**<br>The function divides by `len(numbers)` without checking if the list is empty.<br>When called with `calculate_average([])`, this crashes with `ZeroDivisionError`.<br><br><strong>&gt; Tool: Edit<br></strong><br>Fixed: Added an early return for empty lists:<br>    if not numbers:<br>        return 0<br><br>**Bug 2: `parse_user_config` -- KeyError on missing nested keys**<br>The function accesses `config[&quot;user&quot;][&quot;name&quot;]`, `config[&quot;settings&quot;][&quot;timeout&quot;]`,<br>and `config[&quot;metadata&quot;][&quot;created_at&quot;]` directly. If any of these keys are missing,<br>it raises `KeyError`.<br><br><strong>&gt; Tool: Edit<br></strong><br>Fixed: Replaced direct key access with `.get()` and sensible defaults:<br>    user = config.get(&quot;user&quot;, {})<br>    settings = config.get(&quot;settings&quot;, {})<br>    metadata = config.get(&quot;metadata&quot;, {})<br><br>**Bug 3: `find_outliers` -- ZeroDivisionError on empty list**<br>Same pattern as `calculate_average` -- `sum(data) / len(data)` crashes on empty input.<br><br><strong>&gt; Tool: Edit<br></strong><br>Fixed: Added an early return for empty data lists.<br><br>**Bug 4: `merge_sorted_lists` -- remaining elements never appended**<br>After the `while` loop exits, any remaining elements in `list_a` or `list_b` are<br>silently dropped. For example, `merge_sorted_lists([1, 3, 5], [2, 4])` returns<br>`[1, 2, 3, 4]` instead of `[1, 2, 3, 4, 5]`.<br><br><strong>&gt; Tool: Edit<br></strong><br>Fixed: Added `result.extend(list_a[i:])` and `result.extend(list_b[j:])` after the loop.<br><br>All bugs fixed successfully. (12850ms)</pre><h3>Example 2: Agentic Feature Engineering and Selection for Machine Learning</h3><p>For more complex work, like feature engineering, one prompt usually isn’t enough. You end up with “context drift” if you try to do too much at once. The better way is to break it into turns.</p><p>Let’s build a customer churn prediction model. You have a raw dataset and need to go from raw columns to a ranked, validated feature set, but you don’t want to hand-code every transformation. Instead, you let the agent explore the data, engineer candidate features, evaluate them, and return a final ranked feature list as structured JSON.</p><h4>The Dataset</h4><p>Create customer_churn.csv , a simplified dataset with 10 columns:</p><pre>customer_id,tenure_months,monthly_charges,total_charges,contract_type,payment_method,num_support_tickets,has_online_security,has_tech_support,churned<br>C001,12,64.50,774.00,month-to-month,credit_card,3,0,0,1<br>C002,48,89.20,4281.60,one_year,bank_transfer,0,1,1,0<br>C003,3,29.99,89.97,month-to-month,credit_card,5,0,0,1<br>C004,72,105.00,7560.00,two_year,auto_pay,1,1,1,0<br>C005,1,45.00,45.00,month-to-month,credit_card,2,0,0,1<br>...</pre><p>In practice this would be hundreds or thousands of rows by generating more records synthetically based on the sample records. The columns mix numeric, categorical, and binary data — exactly the kind of messy input that benefits from automated feature engineering.</p><h4>The Orchestration Script</h4><p>This is the full pipeline script. It defines a reusable run_agent_turn() helper that spawns the Cortex Code CLI as a subprocess with --output-format stream-json and --allowed-tools, reads NDJSON messages line-by-line from stdout, and returns parsed results including any structured JSON output. The main() function then runs four sequential turns with Python decision logic between each turn controlling whether the pipeline continues or aborts.</p><pre># ml_feature_pipeline.py<br>import asyncio<br>import json<br><br># Tools the agent is allowed to use across all turns.<br>ALLOWED_TOOLS = [&quot;Read&quot;, &quot;Write&quot;, &quot;Edit&quot;, &quot;Glob&quot;, &quot;Grep&quot;, &quot;Bash&quot;]<br># JSON Schema for the final structured output -- Turn 4&#39;s response<br># must conform to this shape.<br>FEATURE_SCHEMA = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;target_column&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        &quot;selected_features&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;items&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;name&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;importance_score&quot;: {&quot;type&quot;: &quot;number&quot;},<br>                    &quot;category&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;enum&quot;: [&quot;original&quot;, &quot;engineered&quot;],<br>                    },<br>                    &quot;rationale&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                },<br>                &quot;required&quot;: [&quot;name&quot;, &quot;importance_score&quot;, &quot;category&quot;, &quot;rationale&quot;],<br>            },<br>        },<br>        &quot;dropped_features&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;items&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;name&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;reason&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                },<br>                &quot;required&quot;: [&quot;name&quot;, &quot;reason&quot;],<br>            },<br>        },<br>    },<br>    &quot;required&quot;: [&quot;target_column&quot;, &quot;selected_features&quot;, &quot;dropped_features&quot;],<br>}<br><br>async def run_agent_turn(prompt: str, output_schema: dict | None = None) -&gt; dict:<br>    &quot;&quot;&quot;Run a single agent turn via the cortex CLI and return parsed results.<br>    Returns a dict with:<br>        - &quot;text&quot;: concatenated assistant text blocks<br>        - &quot;result_subtype&quot;: &quot;success&quot; | &quot;error&quot; | ...<br>        - &quot;duration_ms&quot;: execution time<br>        - &quot;structured_output&quot;: parsed JSON if output_schema was provided, else None<br>    &quot;&quot;&quot;<br>    cmd = [&quot;cortex&quot;, &quot;-p&quot;, prompt, &quot;--output-format&quot;, &quot;stream-json&quot;]<br>    for tool in ALLOWED_TOOLS:<br>        cmd.extend([&quot;--allowed-tools&quot;, tool])<br>    if output_schema:<br>        cmd.extend([&quot;--output-format-json-schema&quot;, json.dumps(output_schema)])<br>    proc = await asyncio.create_subprocess_exec(<br>        *cmd,<br>        stdout=asyncio.subprocess.PIPE,<br>        stderr=asyncio.subprocess.PIPE,<br>    )<br>    text_parts = []<br>    result_subtype = &quot;unknown&quot;<br>    duration_ms = 0<br>    structured_output = None<br>    while True:<br>        line = await proc.stdout.readline()<br>        if not line:<br>            break<br>        text = line.decode().strip()<br>        if not text:<br>            continue<br>        try:<br>            msg = json.loads(text)<br>        except json.JSONDecodeError:<br>            continue<br>        msg_type = msg.get(&quot;type&quot;)<br>        if msg_type == &quot;assistant&quot;:<br>            content = msg.get(&quot;message&quot;, {}).get(&quot;content&quot;, [])<br>            for block in content:<br>                if block.get(&quot;type&quot;) == &quot;text&quot;:<br>                    text_parts.append(block[&quot;text&quot;])<br>                    print(block[&quot;text&quot;], end=&quot;&quot;)<br>                elif block.get(&quot;type&quot;) == &quot;tool_use&quot;:<br>                    print(f&quot;\n&gt; Tool: {block[&#39;name&#39;]}&quot;)<br>        elif msg_type == &quot;result&quot;:<br>            result_subtype = msg.get(&quot;subtype&quot;, &quot;unknown&quot;)<br>            duration_ms = msg.get(&quot;duration_ms&quot;, 0)<br>            structured_output = msg.get(&quot;structured_output&quot;)<br>            print(f&quot;\n[Turn complete: {result_subtype} ({duration_ms}ms)]&quot;)<br>    await proc.wait()<br>    return {<br>        &quot;text&quot;: &quot;&quot;.join(text_parts),<br>        &quot;result_subtype&quot;: result_subtype,<br>        &quot;duration_ms&quot;: duration_ms,<br>        &quot;structured_output&quot;: structured_output,<br>    }<br><br>async def main():<br>    <br>    ## Turn 1: Explore the dataset<br>    print(&quot;=&quot; * 60)<br>    print(&quot;TURN 1: Data Exploration&quot;)<br>    print(&quot;=&quot; * 60)<br>    turn1 = await run_agent_turn(&quot;&quot;&quot;<br>        Read customer_churn.csv and profile it:<br>        - List every column with its dtype, unique count, and missing-value count<br>        - For numeric columns, report min/median/max and any outliers<br>        - For categorical columns, report value distributions<br>        - Compute correlations with the &#39;churned&#39; target column<br>        - Summarise your findings at the end<br>    &quot;&quot;&quot;)<br>    # Decision gate: check if the data is usable <br>    if &quot;missing&quot; in turn1[&quot;text&quot;].lower() and &quot;100%&quot; in turn1[&quot;text&quot;]:<br>        print(&quot;\n[PIPELINE] Dataset has entirely empty columns. Aborting.&quot;)<br>        return<br>    <br>    ## Turn 2: Engineer candidate features <br>    print(&quot;\n&quot; + &quot;=&quot; * 60)<br>    print(&quot;TURN 2: Feature Engineering&quot;)<br>    print(&quot;=&quot; * 60)<br>    await run_agent_turn(&quot;&quot;&quot;<br>        Based on the customer_churn.csv dataset, write a Python script called<br>        feature_engineering.py that:<br>        1. Reads customer_churn.csv<br>        2. Generates candidate features:<br>           - charge_per_month = total_charges / max(tenure_months, 1)<br>           - ticket_rate = num_support_tickets / max(tenure_months, 1)<br>           - has_protection = has_online_security | has_tech_support<br>           - is_new_customer = 1 if tenure_months &lt;= 6 else 0<br>           - One-hot encode contract_type and payment_method<br>        3. Drops customer_id (non-predictive) and the original<br>           categorical columns after encoding<br>        4. Saves the result to features_output.csv<br>        5. Prints the shape and column list when done<br>        Make sure the script handles edge cases (division by zero,<br>        missing values) and runs without errors.<br>    &quot;&quot;&quot;)<br><br>    ## Turn 3: Evaluate feature importance<br>    print(&quot;\n&quot; + &quot;=&quot; * 60)<br>    print(&quot;TURN 3: Feature Evaluation&quot;)<br>    print(&quot;=&quot; * 60)<br>    turn3 = await run_agent_turn(&quot;&quot;&quot;<br>        Run feature_engineering.py to generate features_output.csv.<br>        Then evaluate each feature&#39;s predictive power for the &#39;churned&#39; target:<br>        1. Compute the absolute Pearson correlation of every feature with &#39;churned&#39;<br>        2. Rank features from most to least important<br>        3. Flag any features with near-zero variance or high mutual correlation<br>           (&gt;0.9 with another feature)<br>        Print a ranked table of features with their scores.<br>    &quot;&quot;&quot;)<br><br>    ## Turn 4: Structured selection<br>    print(&quot;\n&quot; + &quot;=&quot; * 60)<br>    print(&quot;TURN 4: Feature Selection (Structured Output)&quot;)<br>    print(&quot;=&quot; * 60)<br>    turn4 = await run_agent_turn(<br>        f&quot;&quot;&quot;<br>        Here are the feature evaluation results from a previous analysis:<br>        {turn3[&#39;text&#39;]}<br>        Based on these results, select the final feature set for a churn<br>        prediction model. Include features with importance score &gt; 0.05.<br>        Drop features that are redundant or have near-zero variance.<br>        Return your selection as structured JSON matching the provided schema.<br>        For each selected feature, include its importance score, whether it&#39;s<br>        an original or engineered feature, and a brief rationale.<br>        For each dropped feature, explain why it was excluded.<br>        &quot;&quot;&quot;,<br>        output_schema=FEATURE_SCHEMA,<br>    )<br><br>    ## Use the structured result programmatically<br>    result = turn4[&quot;structured_output&quot;]<br>    if result:<br>        print(&quot;\n&quot; + &quot;=&quot; * 60)<br>        print(&quot;PIPELINE RESULT&quot;)<br>        print(&quot;=&quot; * 60)<br>        print(f&quot;Target: {result[&#39;target_column&#39;]}&quot;)<br>        print(f&quot;Selected features: {len(result[&#39;selected_features&#39;])}&quot;)<br>        for f in result[&quot;selected_features&quot;]:<br>            print(f&quot;  {f[&#39;importance_score&#39;]:.3f}  {f[&#39;name&#39;]:30s}  [{f[&#39;category&#39;]}]&quot;)<br>        print(f&quot;\nDropped features: {len(result[&#39;dropped_features&#39;])}&quot;)<br>        for f in result[&quot;dropped_features&quot;]:<br>            print(f&quot;  x {f[&#39;name&#39;]:30s}  ({f[&#39;reason&#39;]})&quot;)<br>        # Write the final feature manifest for downstream consumers<br>        with open(&quot;feature_manifest.json&quot;, &quot;w&quot;) as fp:<br>            json.dump(result, fp, indent=2)<br>        print(&quot;\nFeature manifest saved to feature_manifest.json&quot;)<br><br>asyncio.run(main())</pre><h4>How It Works</h4><ol><li><strong>Turn 1 (Explore):</strong> The agent profiles the CSV and checks for data quality.</li><li><strong>Turn 2 (Code):</strong> The agent writes a transform.py script to handle one-hot encoding.</li><li><strong>Turn 3 (Execute):</strong> The agent uses the Bash tool to run that script and check the output.</li><li><strong>Turn 4 (JSON):</strong> The agent returns a structured feature_manifest.json using a schema I provided.</li></ol><p>Here&#39;s what the pipeline I built produces (agent reasoning abbreviated for clarity):</p><pre><strong>============================================================<br>TURN 1: Data Exploration<br>============================================================</strong><br>I&#39;ll read customer_churn.csv and profile the dataset.<br><br><strong>&gt; Tool: Read<br></strong><br>The dataset has 50 rows and 10 columns. Here&#39;s the profile:<br>| Column               | Dtype   | Unique | Missing | Min    | Median  | Max      |<br>|----------------------|---------|--------|---------|--------|---------|----------|<br>| customer_id          | string  | 50     | 0       | -      | -       | -        |<br>| tenure_months        | int     | 38     | 0       | 1      | 20.0    | 72       |<br>| monthly_charges      | float   | 46     | 0       | 29.99  | 74.0    | 110.0    |<br>| total_charges        | float   | 50     | 0       | 30.0   | 1976.0  | 7560.0   |<br>| contract_type        | string  | 3      | 0       | -      | -       | -        |<br>| payment_method       | string  | 3      | 0       | -      | -       | -        |<br>| num_support_tickets  | int     | 8      | 0       | 0      | 1.0     | 7        |<br>| has_online_security  | int     | 2      | 0       | 0      | -       | 1        |<br>| has_tech_support     | int     | 2      | 0       | 0      | -       | 1        |<br>| churned              | int     | 2      | 0       | 0      | -       | 1        |<br><br>**Correlations with `churned`**:<br>- tenure_months:       -0.82 (strong negative -- longer tenure = less churn)<br>- num_support_tickets:  0.79 (strong positive -- more tickets = more churn)<br>- has_online_security: -0.72<br>- has_tech_support:    -0.60<br>- monthly_charges:     -0.48<br>- total_charges:       -0.74<br>No columns are entirely missing. The dataset is clean and usable.<br><br>[Turn complete: success (14520ms)]<br><br><strong>============================================================<br>TURN 2: Feature Engineering<br>============================================================</strong><br>I&#39;ll create feature_engineering.py with the candidate features.<br><br><strong>&gt; Tool: Write<br></strong><br>I&#39;ve written feature_engineering.py. The script:<br>1. Reads customer_churn.csv<br>2. Engineers 4 new features: charge_per_month, ticket_rate, has_protection, is_new_customer<br>3. One-hot encodes contract_type (3 categories) and payment_method (3 categories)<br>4. Drops customer_id and the original categorical columns<br><br><strong>&gt; Tool: Bash<br></strong><br>Output shape: (50, 16). Columns:<br>tenure_months, monthly_charges, total_charges, num_support_tickets,<br>has_online_security, has_tech_support, churned, charge_per_month,<br>ticket_rate, has_protection, is_new_customer, contract_month-to-month,<br>contract_one_year, contract_two_year, payment_auto_pay, payment_bank_transfer<br><br>[Turn complete: success (21340ms)]<br><br><strong>============================================================<br>TURN 3: Feature Evaluation<br>============================================================</strong><br>I&#39;ll run feature_engineering.py and evaluate feature importance.<br><br><strong>&gt; Tool: Bash<br></strong><br>Feature Importance (absolute Pearson correlation with `churned`):<br>| Rank | Feature                   | Correlation |<br>|------|---------------------------|-------|<br>| 1    | tenure_months             | 0.821 |<br>| 2    | contract_month-to-month   | 0.806 |<br>| 3    | num_support_tickets       | 0.789 |<br>| 4    | total_charges             | 0.742 |<br>| 5    | is_new_customer           | 0.723 |<br>| 6    | has_online_security       | 0.718 |<br>| 7    | ticket_rate               | 0.695 |<br>| 8    | has_tech_support          | 0.601 |<br>| 9    | has_protection            | 0.584 |<br>| 10   | monthly_charges           | 0.483 |<br>| 11   | charge_per_month          | 0.412 |<br>| 12   | contract_two_year         | 0.378 |<br>| 13   | payment_auto_pay          | 0.305 |<br>| 14   | contract_one_year         | 0.267 |<br>| 15   | payment_bank_transfer     | 0.041 |<br><br>**Redundancy flags**:<br>- total_charges &amp; tenure_months: correlation 0.94 (&gt;0.9 threshold)<br>- has_protection &amp; has_online_security: correlation 0.91 (&gt;0.9 threshold)<br><br>[Turn complete: success (18760ms)]<br><br><strong>============================================================<br>TURN 4: Feature Selection (Structured Output)<br>============================================================</strong><br>Based on the evaluation results, I&#39;ll select the optimal feature set<br>and return structured JSON.<br><br>[Turn complete: success (9830ms)]<br><br><strong>============================================================<br>PIPELINE RESULT<br>============================================================</strong><br>Target: churned<br>Selected features: 9<br>  0.821  tenure_months                 [original]<br>  0.806  contract_month-to-month       [engineered]<br>  0.789  num_support_tickets           [original]<br>  0.723  is_new_customer               [engineered]<br>  0.718  has_online_security           [original]<br>  0.695  ticket_rate                   [engineered]<br>  0.601  has_tech_support              [original]<br>  0.483  monthly_charges               [original]<br>  0.412  charge_per_month              [engineered]<br>Dropped features: 6<br>  x total_charges                   (redundant with tenure_months, r=0.94)<br>  x has_protection                  (redundant with has_online_security, r=0.91)<br>  x contract_two_year               (below importance threshold after multicollinearity check)<br>  x payment_auto_pay                (moderate importance but highly correlated with contract_type features)<br>  x contract_one_year               (below importance threshold after multicollinearity check)<br>  x payment_bank_transfer           (near-zero correlation: 0.041)<br><br>Feature manifest saved to feature_manifest.json</pre><p>The final feature_manifest.json is a machine-readable artefact that a downstream training pipeline can consume directly (no parsing of agent text required).</p><h3>Python SDK Deep Dive: Configuration, APIs, and Patterns</h3><p>Now that you’ve seen the SDK in action, here’s a closer look at the key configuration options, API surfaces, and patterns you’ll use most often.</p><h4>Configuring the Agent with CortexCodeAgentOptions</h4><p>CortexCodeAgentOptions is the configuration dataclass you pass to both query() and CortexCodeSDKClient. The options fall into four groups:</p><p><strong>Environment</strong>: cwd (working directory), model (e.g., &quot;claude-sonnet-4-6&quot;, &quot;claude-opus-4-6&quot;, &quot;gpt-5.2&quot;), connection (Snowflake connection name), profile (named settings profile), cli_path (custom CLI binary path).</p><p><strong>Permissions</strong>: --allowed-tools (explicit tool whitelist via CLI), permission_mode (&quot;default&quot;, &quot;acceptEdits&quot;, &quot;plan&quot;, &quot;bypassPermissions&quot;), allowed_tools / disallowed_tools (whitelist/blacklist in SDK), can_use_tool (async callback for custom logic).</p><p><strong>Extensibility</strong>: mcp_servers (custom tool servers), hooks (lifecycle event handlers, Python only), agents (subagent definitions).</p><p>Here’s how configurations differ by environment:</p><pre># Development: full autonomy via CLI<br>dev_cmd = [<br>    &quot;cortex&quot;, &quot;-p&quot;, prompt,<br>    &quot;--output-format&quot;, &quot;stream-json&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Read&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Write&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Edit&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Glob&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Grep&quot;,<br>    &quot;--allowed-tools&quot;, &quot;Bash&quot;,<br>]</pre><pre># Production: scoped permissions via SDK<br>prod = CortexCodeAgentOptions(<br>    cwd=&quot;/path/to/project&quot;,<br>    model=&quot;claude-opus-4-6&quot;,<br>    allowed_tools=[&quot;Read&quot;, &quot;Glob&quot;, &quot;Grep&quot;, &quot;snowflake_sql_execute&quot;],<br>    disallowed_tools=[&quot;Bash&quot;, &quot;Write&quot;],<br>    can_use_tool=my_permission_callback,<br>)</pre><h4>Single-Turn vs. Multi-Turn APIs</h4><p>query(prompt, options): Fire-and-forget. Spawns a CLI subprocess, streams back messages, and terminates. Use for one-shot tasks.</p><p>CortexCodeSDKClient: Persistent session. The CLI subprocess stays alive across turns, preserving full context. Use when later steps depend on earlier ones.</p><pre># Multi-turn: each query() call builds on the previous context<br># Turn 1<br>async with CortexCodeSDKClient(options) as client:<br>    await client.query(&quot;Read the database schema and summarise the tables.&quot;)<br>    async for msg in client.receive_response():<br>        handle_message(msg)<br><br># Turn 2 knows about the schema from Turn 1<br>    await client.query(&quot;Now create a semantic view for the customer table.&quot;)<br>    async for msg in client.receive_response():<br>        handle_message(msg)</pre><p>Key CortexCodeSDKClient methods beyond query() and receive_response():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*bfuLBIHyReKTzT_Ym8d38A.png" /><figcaption>SDK client methods</figcaption></figure><h4>Message Types at a Glance</h4><p>The SDK streams typed messages you consume in an async for loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*PwPyRL2svnxT9LP0mysVdA.png" /><figcaption>SDK stream typed messages</figcaption></figure><p>Each AssistantMessage contains <strong>content blocks</strong>: TextBlock (reasoning text), ToolUseBlock (tool call with .name and .input), ToolResultBlock (tool output), or ThinkingBlock (chain-of-thought).</p><h4>Permission Handling with can_use_tool</h4><p>For production systems, the can_use_tool callback intercepts every tool call before execution:</p><pre>from cortex_code_agent_sdk import PermissionResultAllow, PermissionResultDeny<br><br>async def can_use_tool(tool_name, tool_input, context):<br>    # Allow read-only tools unconditionally<br>    if tool_name in (&quot;Read&quot;, &quot;Glob&quot;, &quot;Grep&quot;):<br>        return PermissionResultAllow()<br>    # Block destructive commands<br>    if tool_name == &quot;Bash&quot; and &quot;rm &quot; in tool_input.get(&quot;command&quot;, &quot;&quot;):<br>        return PermissionResultDeny(message=&quot;Destructive commands not allowed&quot;)<br>    # Allow but add a timeout constraint<br>    if tool_name == &quot;Bash&quot;:<br>        return PermissionResultAllow(<br>            updated_input={**tool_input, &quot;command&quot;: f&quot;timeout 30 {tool_input[&#39;command&#39;]}&quot;}<br>        )<br>    return PermissionResultDeny(message=f&quot;Tool &#39;{tool_name}&#39; requires approval&quot;)</pre><p>You can combine can_use_tool with permission_mode — the built-in mode filters first, and your callback handles the rest.</p><h4>Hooks: Observing Agent Behaviour (Python Only)</h4><p>Hooks let you tap into the agent lifecycle for logging, auditing, or custom logic. The most useful hooks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*ixYRVkqbVTnJhBdid06YZw.png" /><figcaption>Hooks</figcaption></figure><pre>options = CortexCodeAgentOptions(<br>    allowed_tools=[&quot;Read&quot;, &quot;Write&quot;, &quot;Edit&quot;, &quot;Glob&quot;, &quot;Grep&quot;, &quot;Bash&quot;],<br>    hooks={<br>        &quot;PreToolUse&quot;: my_pre_tool_logger,<br>        &quot;PostToolUse&quot;: my_post_tool_logger,<br>        &quot;Stop&quot;: my_completion_handler,<br>    },<br>)</pre><p>Other available hooks: PostToolUseFailure, UserPromptSubmit, SubagentStart, SubagentStop, Notification, PermissionRequest, PreCompact.</p><h4>MCP Custom Tools: Extending the Agent</h4><p>The Model Context Protocol lets you give the agent custom tools. In Python, define them inline with @tool and run them in-process:</p><pre>from cortex_code_agent_sdk import tool, create_sdk_mcp_server<br><br>@tool(&quot;search_jira&quot;, &quot;Search Jira tickets&quot;, {&quot;query&quot;: str, &quot;project&quot;: str})<br>async def search_jira(args):<br>    results = await jira_client.search(args[&quot;query&quot;], project=args[&quot;project&quot;])<br>    return {&quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: json.dumps(results)}]}<br>server = create_sdk_mcp_server(name=&quot;internal&quot;, version=&quot;1.0.0&quot;, tools=[search_jira])<br>options = CortexCodeAgentOptions(<br>    allowed_tools=[&quot;Read&quot;, &quot;Write&quot;, &quot;Edit&quot;, &quot;Glob&quot;, &quot;Grep&quot;, &quot;Bash&quot;],<br>    mcp_servers={&quot;internal&quot;: server},<br>)</pre><p>The agent can now call search_jira alongside built-in tools -- no external server process needed.</p><h4>Error Handling</h4><p>The SDK raises specific exceptions for different failure modes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*i_zZYzCTT-UwbDGqKqIjgw.png" /><figcaption>Failure modes</figcaption></figure><p>All inherit from CortexCodeSDKError. Also check ResultMessage.subtype for agent-level errors like &quot;error_max_turns&quot; or &quot;error_max_budget_usd&quot;.</p><h3>Design Principles for Your Agentic Workflows</h3><ol><li><strong>Prompt engineering is your primary control mechanism.</strong> Be specific about what you want, what format to use, and what constraints to follow. Include role context in your prompts.</li><li><strong>Scope permissions to the task.</strong> Use allowed_tools to whitelist only what&#39;s needed. A code analysis agent needs Read, Glob, Grep -- not Write or Bash.</li><li><strong>Use structured output for machine consumption.</strong> When downstream code consumes agent results, define a JSON Schema via output_format instead of parsing free text.</li><li><strong>Multi-turn only when you need context carry-over.</strong> Single-turn is simpler and cheaper. Use multi-turn only when later steps genuinely depend on earlier context.</li><li><strong>Observe the stream.</strong> Even in autonomous mode, log what the agent does. The message stream gives you full visibility for debugging and auditing.</li><li><strong>Handle errors explicitly.</strong> Check ResultMessage.subtype for error_max_turns, error_during_execution, or error_max_budget_usd. Wrap JSON parsing in try/except.</li></ol><h3>Summary</h3><p>The Cortex Code Agent SDK turns the AI from a “chat buddy” into a piece of infrastructure. It isn’t about replacing the developer; it’s about offloading the boring, repetitive parts of the lifecycle — the boilerplate, the basic refactors, and the initial data profiling — so we can focus on the actual architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811be94b004e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/building-programmable-ai-agents-on-snowflake-a-deep-dive-into-the-cortex-code-agent-sdk-811be94b004e">Building Programmable AI Agents on Snowflake: A Deep Dive into the 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>
    </channel>
</rss>