<?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 Ameeya khadanga on Medium]]></title>
        <description><![CDATA[Stories by Ameeya khadanga on Medium]]></description>
        <link>https://medium.com/@ameeatus?source=rss-ca01cb24732b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2ocMfhlU66AcAZum</url>
            <title>Stories by Ameeya khadanga on Medium</title>
            <link>https://medium.com/@ameeatus?source=rss-ca01cb24732b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:21:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ameeatus/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[I Built Custom AI Skills for Snowflake Pipelines — Here’s How It Turned 5 Days of Work Into 5 Hours]]></title>
            <link>https://medium.com/@ameeatus/i-built-custom-ai-skills-for-snowflake-pipelines-heres-how-it-turned-5-days-of-work-into-5-hours-d7b01ce2d499?source=rss-ca01cb24732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b01ce2d499</guid>
            <dc:creator><![CDATA[Ameeya khadanga]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 00:38:42 GMT</pubDate>
            <atom:updated>2026-07-05T00:38:42.285Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Custom skills turned a coding assistant into a repeatable development accelerator for pipeline engineering.</em></p><h3>TL;DR</h3><ul><li>Snowflake’s <strong>Cortex Code</strong> (the AI assistant in Workspaces) can query your account directly — not just generate code, but discover, analyze, and document existing pipelines.</li><li>The real unlock isn’t one-off prompting — it’s <strong>custom skills</strong>: reusable instruction files that teach the AI your patterns, naming conventions, and workflows.</li><li>Combined with an AGENTS.md context file, the AI &quot;remembers&quot; your project across sessions even though it has no persistent memory.</li><li>I’ve used this to reverse-engineer 3 pipelines, generate column mappings, redesign architectures, and validate UAT runs — each taking ~2 hours instead of ~5 days.</li></ul><h3>The Problem</h3><p>I inherited a member data pipeline at a large enterprise. The pipeline loaded data from raw source tables through a curated zone into a target staging layer, where a downstream connector would pick it up and push to an external system.</p><p>The problems:</p><ol><li><strong>No documentation</strong> — the pipeline was built by a vendor team years ago. The only “documentation” was the service account running SQL twice daily.</li><li><strong>Streams kept breaking</strong> — the original design used Snowflake streams, which go stale after 14 days of inactivity. Every holiday weekend, the pipeline would break.</li><li><strong>Hardcoded for one tenant</strong> — the SQL was written for TENANT_ID = 1, but we needed to support multiple tenants.</li><li><strong>No column mapping</strong> — nobody could tell me which source columns mapped to which target columns, what transformations were applied, or what data type risks existed.</li></ol><p>The traditional approach: schedule meetings with the vendor team, request documentation, manually trace SQL, spend a week building a replacement. The actual approach: one conversation with an AI assistant.</p><h3>Part 1: The First Session (5 Hours That Changed Everything)</h3><h3>Reverse-Engineering a Pipeline from Query History</h3><p>I opened a Snowflake Workspace, started Cortex Code, and typed:</p><blockquote><em>“Find all SQL queries run by the service account </em><em>SVC_PIPELINE_RUNNER in the last 7 days against any member tables.&quot;</em></blockquote><p>The AI wrote and executed a query against SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY, analyzed 100+ results, and identified the exact <strong>11-step ETL pattern</strong> the service account runs twice daily:</p><pre>-- What the AI generated and ran<br>SELECT query_id, query_text, query_type, start_time, end_time,<br>       rows_inserted, rows_deleted, rows_updated,<br>       execution_status<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE user_name = &#39;SVC_PIPELINE_RUNNER&#39;<br>  AND start_time &gt;= DATEADD(&#39;day&#39;, -7, CURRENT_TIMESTAMP())<br>  AND execution_status = &#39;SUCCESS&#39;<br>ORDER BY start_time;</pre><p>It grouped the queries by transaction boundaries (BEGIN/COMMIT), identified the DML sequence (DELETE → INSERT → UPDATE → connector fetch → archive), and documented all 11 steps in execution order.</p><p><strong>Time: 30 minutes.</strong> Manually, this would have taken a full day of query history spelunking.</p><h3>Redesigning the Architecture</h3><p>When I told it about the stream staleness problem, it proposed three alternatives:</p><ol><li><strong>Change Tracking</strong> — use CHANGES clause instead of streams</li><li><strong>Dynamic Tables</strong> — let Snowflake handle incremental refresh</li><li><strong>Watermark-based</strong> — track a high-water mark timestamp, pull everything newer</li></ol><p>I picked Dynamic Tables + Watermark (v2). It built the full pipeline. Then I challenged it:</p><blockquote><em>“Isn’t the Dynamic Table just an extra layer here? Can this be simpler?”</em></blockquote><p>It immediately proposed three simpler alternatives. I picked the pure watermark approach. The final v3 pipeline:</p><pre>-- Simplified: watermark-based incremental load<br>INSERT INTO DEV_TGT_DB.TGT_SCHMA_4_TNNTA_STG.MEMBER_STAGING (<br>    MEMBER_ID, FIRST_NAME, LAST_NAME, DOB, <br>    LOAD_TIMESTAMP, RUN_ID, TENANT_ID<br>)<br>SELECT <br>    src.MEMBER_ID,<br>    UPPER(TRIM(src.FIRST_NAME)),<br>    UPPER(TRIM(src.LAST_NAME)),<br>    src.DATE_OF_BIRTH,<br>    CURRENT_TIMESTAMP(),<br>    :run_id,<br>    cfg.TENANT_ID<br>FROM RAW_DB.RAW_SCHEMA.MEMBER src<br>JOIN DEV_TGT_DB.TGT_SCHMA_4_TNNTA.PIPELINE_CONFIG cfg<br>  ON cfg.IS_ACTIVE = &#39;Y&#39;<br>WHERE src.LOAD_TIMESTAMP &gt; (<br>    SELECT COALESCE(MAX(LOAD_TIMESTAMP), &#39;1900-01-01&#39;)<br>    FROM DEV_TGT_DB.TGT_SCHMA_4_TNNTA.PIPELINE_RUN_LOG<br>    WHERE TABLE_NAME = &#39;MEMBER_STAGING&#39;<br>      AND PUBLISH_FLAG = &#39;Y&#39;<br>);</pre><p>Key improvements:</p><ul><li><strong>No streams</strong> — reads directly from source using a watermark (no more staleness)</li><li><strong>Config-driven</strong> — pulls all active tenants from a config table (no hardcoded IDs)</li><li><strong>Replayable</strong> — watermark table lets you re-run from any point</li><li><strong>Zero parameters</strong> — just CALL SP_MEMBER_PIPELINE()</li></ul><h3>Column Mapping Generation</h3><p>I said: “Map all columns from the source member table to the target staging table.”</p><p>It ran DESCRIBE TABLE on both sides, auto-matched 29 member columns and 22 address columns by name patterns, identified renames (e.g., PRIMARY_PHONE_NUMBER → PHONE_PRIMARY), documented COALESCE defaults and lookup joins, and <strong>flagged a truncation risk</strong> — a GROUP_NUMBER column going from VARCHAR(50) in source to VARCHAR(15) in target. That flag alone probably saved a production incident.</p><h3>The Time Breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83WZu-uiGIjD88lv1yufTA.png" /></figure><h3>Part 2: Custom Skills — Making It Repeatable</h3><p>The first session was impressive. But it was still a one-shot. If I started a new session tomorrow, I’d have to re-explain my naming conventions, table structures, and pipeline patterns from scratch.</p><p>That’s when I discovered <strong>custom skills</strong>.</p><h3>What Are Custom Skills?</h3><p>Skills are markdown files that live in your workspace at .snowflake/cortex/skills/&lt;skill-name&gt;/SKILL.md. They contain structured instructions that the AI reads automatically at session start.</p><p>Think of them as <strong>playbooks</strong> — instead of explaining your workflow every time, you write it once, and the AI follows it exactly on every invocation.</p><h3>Skill File Structure</h3><pre>.snowflake/cortex/skills/<br>├── pipeline-reverse-engineer/<br>│   └── SKILL.md<br>├── watermark-pipeline-builder/<br>│   └── SKILL.md<br>├── column-mapping-generator/<br>│   └── SKILL.md<br>└── daily-usage-report/<br>    └── SKILL.md</pre><h3>Example: Pipeline Reverse-Engineer Skill</h3><pre>---<br>name: pipeline-reverse-engineer<br>description: Reverse-engineer a pipeline from query history for a given service account.<br>  Triggered by &quot;reverse-engineer pipeline for &lt;service_account&gt;&quot;<br>---<br><br># Instructions<br>## 1. Identify Service Account<br>- Get the service account name from the user<br>- Read AGENTS.md for environment context (database, schema, role)<br>## 2. Query Execution History<br>SELECT query_id, query_text, query_type, start_time, end_time,<br>       rows_inserted, rows_deleted, rows_updated, rows_produced,<br>       execution_status<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE user_name = &#39;&lt;SERVICE_ACCOUNT&gt;&#39;<br>  AND start_time &gt;= DATEADD(&#39;day&#39;, -1, CURRENT_TIMESTAMP())<br>  AND execution_status = &#39;SUCCESS&#39;<br>ORDER BY start_time;<br>## 3. Identify Pipeline Phases<br>- Group queries by transaction boundaries (BEGIN/COMMIT)<br>- Identify pattern: DELETE → INSERT → UPDATE → fetch → COMMIT<br>- Note session settings (TRANSACTION_ABORT_ON_ERROR, timezone, etc.)<br>## 4. Extract Full SQL<br>- For each DML, get full query_text<br>- Identify WHERE clauses, JOIN conditions, watermark logic<br>## 5. Document Findings<br>- Create pipeline_documentation.md with step-by-step SQL<br>- Include: Step number, SQL, rows affected, purpose<br>- Draw flow diagram<br>## 6. Compare Against Existing Docs<br>- If documentation already exists, diff against actual execution<br>- Flag new steps, missing steps, or changed logic<br></pre><p>Now I just say <strong>“reverse-engineer pipeline for SVC_ETL_LOADER”</strong> and it follows all six steps automatically — no re-explanation needed.</p><h3>The AGENTS.md Pattern</h3><p>Beyond skills, I have an AGENTS.md file at the workspace root that gives the AI persistent project context:</p><pre># Project Context</pre><pre>## Environment<br>- DEV database prefix: DEV_<br>- PROD database prefix: PROD_<br>- Target database: DEV_TGT_DB (dev) / PROD_TGT_DB (prod)</pre><pre>## Service Accounts<br>- Tenant A pipeline: SVC_PIPELINE_RUNNER<br>- Tenant B pipeline: SVC_ETL_LOADER</pre><pre>## Naming Conventions<br>- Timestamps: LOAD_TIMESTAMP (source watermark column)<br>- Run tracking: RUN_ID (UUID per pipeline execution)<br>- Status flags: RECORD_STATUS (&#39;ACT&#39;/&#39;COM&#39;), PUBLISH_FLAG (&#39;Y&#39;/&#39;N&#39;)</pre><pre>## SQL Standards<br>- Always use fully qualified table names (DB.SCHEMA.TABLE)<br>- CTEs over subqueries<br>- UPPER(TRIM()) on all string columns<br>- COALESCE with sensible defaults for nullable fields</pre><pre>## Known Risks<br>- GROUP_NUMBER: VARCHAR(50) in source, VARCHAR(15) in target — truncation risk</pre><p>Between AGENTS.md and the skills, the AI effectively <strong>&quot;remembers&quot; my project</strong> even though it has no persistent memory between sessions.</p><h3>My Custom Skills</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lploMbpw7haaYMu6-oBCSw.png" /></figure><h3>Part 3: Scaling to Multiple Pipelines</h3><p>With skills in place, I tackled two more pipelines. The results proved the approach scales.</p><h3>Pipeline 2: Raw-to-Curated</h3><p>I heard from a colleague that another team already had a pipeline loading raw member data into the curated zone — but I didn’t know the service account, the SQL, or the schedule.</p><p>I told Cortex Code: <em>“There’s a pipeline loading raw member data into the curated zone. Can you find it?”</em></p><p>It searched QUERY_HISTORY, identified the service account (SVC_ETL_LOADER), pulled the last 24 hours of its executions, and extracted the full 10-step pipeline. <strong>30 minutes</strong> — what would have been a multi-day discovery exercise of asking around, requesting access, and reading through stored procedures.</p><p>Then something interesting happened. I reached out to the architecture team to get the official mapping document for this pipeline. They rerouted me to the vendor team — the ones who actually own the service account. The vendor shared their source-to-target mapping, and I compared it against what Cortex Code had auto-generated from query history.</p><p><strong>The AI-generated mapping matched the official document almost perfectly</strong> — and actually caught things the official doc didn’t cover (implicit COALESCE defaults and a VARCHAR truncation risk).</p><p>That’s when it clicked: this isn’t just a code generator. It’s a <strong>discovery and validation tool</strong>.</p><h3>Pipeline 3: Raw-to-Target (Direct)</h3><p>Using the same skills, I explored a simplified architecture — going straight from raw to the target staging layer, skipping the curated zone entirely. Full column mapping, CDC variant, and architecture comparison doc — all generated in ~2 hours.</p><h3>Each Pipeline: ~2 Hours</h3><p>From “I know nothing about this service account” to “fully documented with column mappings, redesigned architecture, and validation queries” — <strong>~2 hours per pipeline</strong>. The skills do the same rigorous process every time.</p><h3>Part 4: Monitoring Your AI Spend</h3><p>One concern with AI coding assistants: <strong>cost visibility</strong>. How much are you actually spending? Is it worth it?</p><p>I built a daily-usage-report skill that queries SNOWFLAKE.ACCOUNT_USAGE.CORTEX_CODE_SNOWSIGHT_USAGE_HISTORY and gives me:</p><ul><li><strong>Total tokens consumed</strong> and <strong>credits burned</strong></li><li><strong>Cache hit ratio</strong> — the key efficiency metric. When you stay in one conversation, Snowflake caches prior context (cache reads are cheaper). Starting new sessions = full-price cache writes every time.</li><li><strong>Most expensive single request</strong> — usually the first message of a new session</li><li><strong>Efficiency tips</strong> — built-in thresholds that tell you when to batch questions or stay in longer sessions</li></ul><pre>SELECT<br>    DATE(USAGE_TIME) AS report_date,<br>    COUNT(*) AS total_requests,<br>    SUM(TOKENS) AS total_tokens,<br>    ROUND(SUM(TOKEN_CREDITS), 4) AS total_credits,<br>    ROUND(AVG(TOKENS), 0) AS avg_tokens_per_request<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_CODE_SNOWSIGHT_USAGE_HISTORY<br>WHERE USER_NAME = CURRENT_USER()<br>  AND USAGE_TIME &gt;= DATEADD(&#39;day&#39;, -1, CURRENT_TIMESTAMP())<br>GROUP BY 1;</pre><p><strong>Practical insight</strong>: I cut my daily credit spend by ~30% just by learning to stay in longer sessions instead of starting fresh conversations for each question. Cache reads are significantly cheaper than cache writes.</p><p><strong>For adoption conversations</strong>: When management asks “how much is this costing us?” — you have the data. Credits per pipeline built, cost per hour of AI-assisted development. When you can show 5 hours × AI cost vs. 5 days × developer salary, the ROI is obvious.</p><h3>Part 5: What My Workspace Looks Like Now</h3><pre>/<br>├── AGENTS.md                          ← Project context (AI reads every session)<br>├── .snowflake/cortex/skills/          ← Custom skills<br>│   ├── pipeline-reverse-engineer/<br>│   ├── watermark-pipeline-builder/<br>│   ├── column-mapping-generator/<br>│   └── daily-usage-report/<br>│<br>├── curated-to-target/                 ← Pipeline 1<br>│   ├── pipeline_documentation.md      ← 11-step DML documentation<br>│   ├── column_mapping.md<br>│   ├── risk_assessment.md<br>│   └── investigations/<br>│<br>├── raw-to-curated/                    ← Pipeline 2<br>│   ├── pipeline_full_sql.sql          ← Reverse-engineered<br>│   ├── pipeline_watermark.sql         ← Redesigned version<br>│   └── column_mapping.md<br>│<br>├── raw-to-target/                     ← Pipeline 3<br>│   ├── pipeline_direct.sql<br>│   ├── pipeline_cdc.sql               ← CDC variant<br>│   └── column_mapping.md<br>│<br>└── usage_reports/                     ← Daily cost tracking<br>    └── usage_report_2025-06-24.md</pre><h3>This Is NOT Vibe Coding</h3><p>I want to be explicit about this: <strong>I reviewed every output.</strong> I challenged designs (“isn’t this too complex?”). I pointed it to the right tables when it asked. I compared AI-generated mappings against official vendor documentation.</p><p>The AI handled the heavy lifting:</p><ul><li>Mining query history across thousands of executions</li><li>Writing boilerplate SQL with proper error handling</li><li>Generating column mapping tables from schema metadata</li><li>Documenting architecture with diagrams and comparison tables</li></ul><p>I stayed in control of every decision:</p><ul><li>Which architecture pattern to use</li><li>Whether to add Dynamic Tables or keep it simple</li><li>When to make it config-driven</li><li>Validating output against vendor documentation</li></ul><p>This is collaborative engineering, not blind delegation.</p><h3>How To Set This Up Yourself</h3><h3>Step 1: Open a Workspace</h3><p>Snowsight → Workspaces → create or open any workspace.</p><h3>Step 2: Create AGENTS.md</h3><p>At your workspace root, create an AGENTS.md file with your project&#39;s specifics:</p><ul><li>Database/schema names</li><li>Service accounts</li><li>Naming conventions</li><li>Known risks or quirks</li></ul><h3>Step 3: Create Your First Skill</h3><p>Create .snowflake/cortex/skills/my-skill/SKILL.md with:</p><pre>---<br>name: my-skill<br>description: What it does and when to trigger it.<br>---</pre><pre># Instructions<br>1. Step one...<br>2. Step two...<br>3. Step three...</pre><h3>Step 4: Start a Session</h3><p>Open any file in the workspace. The AI panel is on the right. Type your trigger phrase and watch it follow your skill instructions.</p><h3>Step 5: Iterate</h3><p>After every session, ask yourself: “What did I re-explain that I shouldn’t have to?” — that’s your next skill.</p><h3>Lessons Learned</h3><ol><li><strong>Skills &gt; Prompting</strong> — One-off prompts are powerful. Reusable skills are 10x more powerful. The first pipeline took 5 hours. The second took 2. The third took 2. That’s the compounding effect of investing in skills.</li><li><strong>AGENTS.md is essential</strong> — Without project context, the AI generates generic code. With AGENTS.md, it generates code that matches your naming conventions, references your actual tables, and follows your team’s SQL standards.</li><li><strong>AI as a discovery tool</strong> — The most surprising use case wasn’t code generation — it was <strong>finding things</strong>. Mining query history to discover undocumented pipelines, identifying service accounts, extracting execution patterns from thousands of queries.</li><li><strong>Validate against official docs</strong> — When my AI-generated column mapping matched the vendor’s official document (and caught things they missed), I knew the approach was sound. Always validate. But expect to be pleasantly surprised.</li><li><strong>Monitor your spend</strong> — Build a usage report skill early. It pays for itself in optimization insights and gives you data for ROI conversations.</li></ol><h3>Part 6: The AI That Respects Your IAM</h3><p>This is the finding that surprised me most — and it’s worth its own section.</p><h3>The Problem</h3><p>I was building a CDC pipeline that needed intermediate materialization (extract from source → compute MD5 hashes → compare against mirror → identify changes). The standard approach: CREATE TEMPORARY TABLE. I wrote it up, ready to hand off to the service account.</p><p>Then I asked the AI: “Can the service account create temp tables?”</p><h3>What Happened</h3><p>It ran SHOW GRANTS TO USER and SHOW GRANTS TO ROLE, traced the full role hierarchy, and reported:</p><blockquote>“No. The service account has DML-only access — INSERT, UPDATE, DELETE, SELECT, TRUNCATE on specific pre-existing tables. No CREATE TABLE or CREATE TEMPORARY TABLE on any schema.”</blockquote><p>Most AI code generators would have happily produced code that fails on deployment. This one <strong>checked first</strong>, then automatically refactored.</p><h3>The Iteration (Three Designs in Three Messages)</h3><p><strong>Design 1</strong>: Temp tables (original) — won’t work, no DDL privileges.</p><p><strong>Design 2</strong>: CTEs everywhere — works, but duplicates the raw extract logic (once for MERGE, once for INSERT INTO STG). Double-scan of a potentially massive source table.</p><p><strong>Design 3</strong> (final): <strong>STG-first pattern</strong> — INSERT the changes into STG first (single CTE scan), then MERGE into the mirror table by reading back from STG via RUN_ID. One scan. No temp tables. No duplication.</p><pre>-- Phase 1: Single scan of source → only changes go to STG<br>INSERT INTO DEV_TGT_DB.TGT_SCHMA_4_TNNTA_STG.MEMBER_STG (...)<br>WITH raw_extract AS (...),<br>     deduped AS (...),<br>     with_hash AS (...),<br>     changes AS (<br>         SELECT h.*<br>         FROM with_hash h<br>         LEFT JOIN DEV_TGT_DB.TGT_SCHMA_4_TNNTA.MEMBER m ON h.member_key = m.member_key<br>         WHERE m.member_key IS NULL OR m.row_hash &lt;&gt; h.row_hash<br>     )<br>SELECT ... FROM changes;</pre><pre>-- Phase 2: MERGE mirror from STG (small dataset, fast)<br>MERGE INTO DEV_TGT_DB.TGT_SCHMA_4_TNNTA.MEMBER tgt<br>USING (SELECT * FROM DEV_TGT_DB.TGT_SCHMA_4_TNNTA_STG.MEMBER_STG WHERE RUN_ID = :run_id) src<br>ON tgt.member_key = src.member_key<br>WHEN MATCHED THEN UPDATE SET ...<br>WHEN NOT MATCHED THEN INSERT ...;</pre><p>This wasn’t me telling it the answer. It was a <strong>conversation</strong>: I challenged the CTE duplication, suggested using STG as the intermediate, and it immediately saw the advantage and rewrote the pipeline.</p><h3>The Permanent Rule</h3><p>After this, I had the AI add a constraint to AGENTS.md and the pipeline-builder skill:</p><blockquote>“Service accounts have DML-only access. NO CREATE TABLE / CREATE TEMP TABLE. All pipeline SQL must use CTEs or pre-existing tables. Prefer STG-first pattern for materialized intermediates.”</blockquote><p>Now every pipeline it generates — for any tenant, any future project — will respect this constraint. It won’t suggest temp tables. It won’t generate DDL the service account can’t run. It defaults to patterns that work within the security model.</p><p><strong>The insight</strong>: Most AI coding tools generate code in a vacuum. They don’t know your role hierarchy, your grants, your security posture. Custom skills + AGENTS.md let you encode these constraints once, and the AI adapts permanently.</p><h3>Part 7: UAT Validation — From Manual to Automated</h3><p>The uat-validator skill went from concept to production in this session. Here&#39;s what it looks like in practice.</p><h3>The Skill</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwpQdscpPZciNWm5-0HK5A.png" /></figure><h3>Live Validation: Under 2 Minutes</h3><p>I ran the full validation on pipeline iteration 2 (run 6ed1a332):</p><pre>Pipeline: Curated-to-Target (Tenant A, CLIENT_ID=100)<br>Run ID:   6ed1a332-6f46-11f1-adab-b500d2999365<br>Duration: ~45 minutes (17:00 → 17:45 UTC)<br><br>Phase           | Status<br>Staging Load    | PASS (91,071 MEMBER + 182,138 ADDRESS)<br>Publish         | PASS (PUBLISH_FLAG = &#39;Y&#39;)<br>Archive         | PASS (HIST counts match, RECORD_STATUS = &#39;COM&#39;)<br>STG Cleanup     | PASS (0 rows remaining)<br>Run Closure     | PASS (LOAD_END_TIMESTAMP set)<br>Overall: PASS ✓</pre><p>It also validated Tenant B’s first run and correctly identified it as a <strong>full reload</strong> — 180M member rows + 469M address rows. Instead of flagging this as an error, it checked for prior completed runs (found none), confirmed the watermark defaulted to 1900-01-01, and marked the staging phase as PASS with an explanatory note:</p><blockquote>“Full reload is expected behavior for a first-time run — no prior watermark existed.”</blockquote><p>That’s the difference between a dumb check (“row count seems high → FAIL”) and a contextual validation that understands pipeline semantics.</p><h3>The Output</h3><p>The skill auto-generates a UAT markdown document with:</p><ul><li>Header (pipeline, tenant, run_id, date, overall result)</li><li>Per-phase pass/fail table</li><li>Full SQL queries with actual result tables</li><li>Findings and recommendations</li></ul><p>Anyone on the team can now say <strong>“validate the run”</strong> and get the same rigorous check — without knowing the 7 queries, the pass criteria, or the pipeline architecture.</p><h3>What’s Next</h3><p>I’m working on additional skills for:</p><ul><li><strong>Cross-account workspace sync</strong> — portable way to move skill files and pipeline docs between dev and prod workspaces</li><li><strong>Pipeline comparison</strong> — diff two versions of a pipeline and highlight logic changes</li><li><strong>Unified watermark consolidation</strong> — single run log table shared across all pipeline variants, differentiated by table name and tenant</li></ul><p>But the biggest shift is moving from Snowsight Workspaces to <strong>Cortex Code CLI</strong> — specifically for <strong>hooks</strong>. Today, my guardrails are “soft” (AGENTS.md rules the AI follows voluntarily). With CLI hooks, I can enforce hard blocks:</p><ul><li>PreToolUse hooks that reject any SQL containing DROP or TRUNCATE on production schemas</li><li>Multi-tenant safety hooks that prevent Tenant A’s service account from touching Tenant B’s schemas</li><li>Audit hooks that log every AI-generated DML before execution</li><li>Plan mode enforcement — requiring human approval before any write operation</li></ul><p>That’s Part 2 of this series: <strong>“From AI Assistant to AI Guardrails.”</strong></p><p>The skills are <strong>portable</strong> — they’re just markdown files in a folder. Copy them into any workspace and they work immediately. If you’re doing data engineering on Snowflake, I’d encourage you to start building your own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b01ce2d499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Cortex Agent as Orchestrator: LangGraph + FastAPI + React Streaming]]></title>
            <link>https://medium.com/@ameeatus/snowflake-cortex-agent-as-orchestrator-langgraph-fastapi-react-streaming-d4b7f9b8a9b6?source=rss-ca01cb24732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4b7f9b8a9b6</guid>
            <category><![CDATA[snowflake-cortex-agent]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[sse-streaming]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Ameeya khadanga]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 22:58:17 GMT</pubDate>
            <atom:updated>2026-06-07T22:58:17.727Z</atom:updated>
            <content:encoded><![CDATA[<h3>I built an identity-resolution assistant that helps me investigate whether records belong to the same person, create Jira tickets, answer FAQ questions, and explain data lineage or data issues. It streams responses and tool events live to the browser, with Cortex Agent as the orchestrator and LangGraph as the agentic framework.</h3><p>Snowflake Cortex Agent speaks Server-Sent Events. Browsers speak WebSocket. In this architecture, Cortex Agent acted as the orchestrator: it selected tools, routed execution between server-side and client-side paths, and managed prompt context while streaming. My LangGraph graph sat in the middle, and I had to make both sides stream in real time — without blocking the event loop.</p><h3>The Problem</h3><p>The Cortex Agent REST API streams its responses as SSE (text/event-stream), emitting discrete events for tool calls, text deltas, and metadata. Cortex Agent was the orchestrator in this version, not just a text generator: it decided when to call tools, how to route those calls, and when to continue generation after tool results. My React frontend, however, connected over WebSocket. Getting those two protocols to talk — and to do it without buffering the whole response — turned out to be the most interesting engineering problem in this iteration.</p><p>In the baseline flow, every LLM call also re-sent the same 800-line system prompt plus accumulated conversation history, which made latency and token cost grow as conversations got longer.</p><p>But before getting into the solution, it’s worth understanding what I was replacing. This architecture did not start from scratch — it replaced a working but increasingly painful baseline script.</p><h3>Where This Started: The Baseline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC2WahYBY0BbJWEgHZdA3A.png" /></figure><p>Every Cortex call received the same payload shape: the full 800-line system prompt, the entire conversation history loaded from an external database, and the new user message — concatenated together on every single request. The third call was not an “agent” in the later Snowflake sense; it was another COMPLETE()-style function call that used the prompt and input parameters to determine identity-resolution accuracy or generate the final memcompare / lineage summary. This meant token cost scaled linearly with conversation length. A ten-turn conversation sent ten turns of history to the LLM on turn eleven, in addition to the 800-line prompt.</p><p>Conversation history was real — but it was managed manually. Each user turn was written to an external database after the response, then read back and injected into the next prompt. There was no framework managing this; it was application code threading history into the Cortex COMPLETE() call. In the FAQ branch, retrieval was done through the Cortex Search Service before the final answer was returned.</p><p>There was no loop. If the agent wanted to call two tools in sequence, it could not — the design allowed one shot per turn. No PII guard existed, so sensitive fields could reach the LLM unchecked. Manual prompt assembly and JSON response parsing were brittle, so any change in output shape could break the downstream flow silently. The Jira branch and the data lineage branch were both hardcoded in Python.</p><p>This was the starting point. Everything in the next section was built to address exactly these pain points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LygnkL_CCB-HYT29XtUsKQ.png" /></figure><p>The SSE parsing row is more important than it looks. In the baseline, a schema change in one event field produced empty results with no error — there was no structured dispatch to catch it. Here, unknown events are logged and skipped; known events are handled explicitly by name.</p><h3>Project Structure</h3><p>The codebase for this architecture spans three folders:</p><pre>core_agent_package/         # Core agent package (Python)<br>  config.py                 # Env-var config (PAT, account URL, DB, schema)<br>  cortex_client.py          # CortexClient — thread creation + SSE parsing<br>  graph.py                  # LangGraph state graph (build_graph)<br>  state.py                  # AgentState TypedDict with merge-reducer<br>  logs/                     # Structured logging helpers<br>  tools/<br>    pii_guard.py            # Regex pre-flight: SSN / DOB / source key patterns<br>    id_validation.py        # ID validation tool (calls internal REST API)<br>    member_compare.py       # Record comparison tool<br>    data_lineage.py         # Data issue mapping and data lineage tools<br>    faq.py                  # FAQ search (Cortex Search, server-side)<br>    jira_tools.py           # Ticket creation tool<br>    mock_data.py            # Realistic mock data for all 5 tools<br>    __init__.py             # execute_tool(name, args) dispatcher<br>backend/<br>  main.py                   # FastAPI app - /ws/chat WebSocket + streaming bridge<br>  requirements.txt          # fastapi, uvicorn, websockets, langgraph, requests<br>frontend/<br>  src/<br>    App.jsx                 # WebSocket lifecycle management<br>    ChatHistory.jsx         # Message display<br>    ChatInput.jsx           # User input<br>    EventStream.jsx         # Live SSE event display panel<br>  package.json              # React 18 + Vite 5<br>  vite.config.js</pre><p>The core agent package is imported directly by backend/main.py — no API layer between them. The frontend talks only to the FastAPI WebSocket; it has no direct Snowflake dependency.</p><h3>What This Looks Like at Runtime</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*MK4nzJ588fYLmxZIzFzF6g.png" /></figure><p>Before any LLM call, a regex PII guard blocks messages containing SSN, DOB, or internal key patterns. Nothing reaches Snowflake until that passes.</p><h3>The Cortex Agent Spec</h3><p>The agent is not a raw LLM call. It is a <strong>named, deployed Snowflake resource</strong> defined by a JSON spec and created via the Cortex Agent management API:</p><p>In this architecture, this spec is effectively the orchestrator contract: tool selection policy, routing behavior, response format policy, and server-side resource bindings are all declared here.</p><pre>POST /api/v2/databases/{DB}/schemas/{SCHEMA}/agents?createMode=orReplace</pre><p>The spec has six top-level keys:</p><pre>{<br>  &quot;name&quot;: &quot;IDENTITY_AGENT&quot;,<br>  &quot;models&quot;: { &quot;orchestration&quot;: &quot;auto&quot; },<br>  &quot;orchestration&quot;: { &quot;budget&quot;: { &quot;seconds&quot;: 300 } },<br>  &quot;instructions&quot;: {<br>    &quot;system&quot;: &quot;...&quot;,<br>    &quot;orchestration&quot;: &quot;...&quot;,<br>    &quot;response&quot;: &quot;...&quot;<br>    },<br>    &quot;tools&quot;: [&quot;...&quot;],<br>    &quot;tool_resources&quot;: { &quot;...&quot;: &quot;...&quot; }<br>}</pre><p><strong>models.orchestration: &quot;auto&quot;</strong> — Snowflake selects the model (Mistral-Large or Llama3-70b) based on availability. No hardcoded model name in the spec.</p><p><strong>orchestration.budget.seconds: 300</strong> — hard timeout on the agent&#39;s reasoning loop. If it hasn&#39;t finished within 5 minutes, the run is terminated.</p><p><strong>Three instruction blocks</strong> — each is an array of strings in the JSON file (for readability) that deploy_agent.py joins into a single string before sending to the API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQUB4vEDtUXlzuRiMX9vDw.png" /></figure><h3>Tool Definitions In The Spec</h3><p>The same spec also declares the tool catalog. In this codebase, the tools array includes six tool definitions with schema metadata and routing intent:</p><ul><li>validate IDs</li><li>compare records</li><li>data issue summary</li><li>data lineage</li><li>FAQ search (Cortex Search tool type)</li><li>create ticket</li></ul><p>Each tool definition includes:</p><ul><li>tool_spec.type (for example generic or cortex_search)</li><li>tool_spec.name</li><li>tool_spec.description</li><li>tool_spec.input_schema (JSON schema for arguments)</li></ul><p>type: &quot;generic&quot; is the custom-tool path. In practice, this is where you define tools whose input schema and behavior you control.</p><p>In this implementation, tool_resources then binds the FAQ search tool to a specific Cortex Search Service resource.</p><h3>Specific Routing Example: search_faq vs create_jira_ticket</h3><p>In this spec, search_faq is declared as type: &quot;cortex_search&quot; and has a matching tool_resources.search_faq entry:</p><pre>&quot;tool_resources&quot;: {<br>    &quot;search_faq&quot;: {<br>        &quot;name&quot;: &quot;SNOWFLAKE_LEARNING_DB.PUBLIC.IDENTITY_FAQ_SEARCH_SVC&quot;,<br>        &quot;title_column&quot;: &quot;QUESTION&quot;,<br>        &quot;id_column&quot;: &quot;FAQ_ID&quot;<br>    }<br>}</pre><p>That binding is what makes search_faq a Snowflake server-side tool in this flow. When the agent selects it, SSE shows response.tool_use with client_side_execute: false, then Snowflake executes the search internally and emits response.tool_result in the same run.</p><p>Now compare that with a generic tool like create_jira_ticket. It has a tool definition in tools, but no entry under tool_resources in this spec. In that case, Cortex emits response.tool_use with a tool_use_id and client_side_execute: true (or absent). The client must:</p><ol><li>Read the tool_use_id, tool name, and input from SSE.</li><li>Execute the tool locally in Python.</li><li>Send a tool_result block back with the same tool_use_id.</li></ol><p>So the practical split is:</p><ul><li>search_faq + tool_resources binding -&gt; executed server-side in Snowflake.</li><li>create_jira_ticket with no tool_resources binding in this spec -&gt; returned to client for local execution via tool_use_id round-trip.</li></ul><h3>How To Make A Custom Tool Server-Side</h3><p>If you want a custom tool to run server-side, the pattern is:</p><ol><li>Implement the logic in Snowflake (for example, via a stored procedure or UDF-backed service).</li><li>Expose it as a server-side-capable tool resource.</li><li>Bind that resource in tool_resources for the tool name.</li></ol><p>Then Cortex can execute it inside Snowflake and emit client_side_execute: false instead of returning it to the client.</p><p>Illustrative pattern example:</p><pre>{<br>    &quot;tools&quot;: [<br>        {<br>            &quot;tool_spec&quot;: {<br>                &quot;type&quot;: &quot;generic&quot;,<br>                &quot;name&quot;: &quot;get_data_lineage&quot;,<br>                &quot;description&quot;: &quot;Return lineage timeline for an identity key&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;id_list&quot;: {&quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}<br>                    },<br>                    &quot;required&quot;: [&quot;id_list&quot;]<br>                }<br>            }<br>        }<br>    ],<br>    &quot;tool_resources&quot;: {<br>        &quot;get_data_lineage&quot;: {<br>            &quot;name&quot;: &quot;SNOWFLAKE_LEARNING_DB.PUBLIC.IDENTITY_LINEAGE_SVC&quot;<br>        }<br>    }<br>}</pre><p>In this example, get_data_lineage is still a custom tool definition (type: &quot;generic&quot;), but once bound to a Snowflake-side resource it can be executed server-side by Cortex.</p><p>This is important for the historical baseline too: in the earlier architecture, all tool behavior and selection policy was already encoded in the large prompt/spec-driven flow, then executed through hardcoded routing. The later architecture made that orchestration loop explicit and stream-aware, but the tool definitions themselves were already a first-class part of the design.</p><p>The agent never sees raw demographic data directly — its system prompt instructs it to treat certain key types as restricted and to refer to source record identifiers as “one record” without surfacing actual values. Those rules live in the spec, not in application code.</p><p>One non-obvious deployment detail: Snowflake’s API expects instruction blocks as <strong>single strings</strong>. The deploy_agent.py script joins the array with &quot;\n&quot;.join(...) before the POST — so the JSON file stays human-readable but the wire format is a flat string.</p><h3>Layer 1 — Parsing the Cortex SSE Stream</h3><p>The CortexClient._execute_run() method in cortex_client.py does all the heavy lifting. It opens a streaming requests.post and iterates r.iter_lines() synchronously:</p><pre>with requests.post(<br>    url, headers=self.headers, json=payload,<br>    stream=True, timeout=(10, 300),<br>) as r:<br>    r.raise_for_status()<br><br>for raw_line in r.iter_lines():<br>        if not raw_line:<br>            continue<br>        line = raw_line.decode(&quot;utf-8&quot;).strip()<br>        if line.startswith(&quot;event:&quot;):<br>            current_event = line[6:].strip()<br>            continue<br>        if not line.startswith(&quot;data:&quot;):<br>            continue<br>        json_str = line[5:].strip()<br>        if json_str == &quot;[DONE]&quot;:<br>            break<br>        data = json.loads(json_str)</pre><p>Each SSE message is a pair of lines: an event: header followed by a data: line containing JSON. The parser tracks current_event across lines, then dispatches:</p><pre>if current_event == &quot;response.tool_use&quot;:<br>    # Only collect tools that must run locally<br>    if data.get(&quot;client_side_execute&quot;, True):<br>        result.tool_calls.append({<br>            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>        })<br><br>elif current_event == &quot;response.text.delta&quot;:<br>    result.text_chunks.append(data.get(&quot;text&quot;, &quot;&quot;))<br><br>elif current_event == &quot;response.tool_result&quot;:<br>    # Server-side tool (e.g. Cortex Search) — Snowflake handled it<br>    # Log only; no client action needed<br>    pass</pre><p>The client_side_execute field is the key routing signal. Snowflake sets it False for server-side tools like search_faq (Cortex Search) — those are executed inside Snowflake&#39;s infrastructure and their results are folded back into the LLM context automatically. When it is True (or absent), the tool must be executed by my Python process and the result sent back in a second :run call.</p><h3>Server-Side Tool Execution Path</h3><p>This is the exact execution behavior when Cortex decides a tool is server-side:</p><ol><li>Cortex emits response.tool_use with client_side_execute: false.</li><li>My client does <strong>not</strong> dispatch that tool to local Python.</li><li>Snowflake executes the tool internally (for example, FAQ retrieval via Cortex Search Service).</li><li>Cortex emits response.tool_result for that server-side execution.</li><li>The same run continues and streams response.text.delta / response.text with the tool output already incorporated.</li></ol><p>So if a tool is registered as server-side, execution stays inside Snowflake end-to-end. Local Python only participates when client_side_execute is true.</p><p>The same pattern applies to other Snowflake-managed server-side resources (for example analyst or stored-procedure-backed capabilities) when they are exposed to the agent as server-side tools.</p><h3>Layer 2 — Bridging to WebSocket in Real Time</h3><p>The synchronous iter_lines() loop runs in a thread. The FastAPI WebSocket endpoint is async. I needed to pass events from the blocking I/O thread to the async event loop without buffering.</p><p>Concrete code references in this implementation:</p><ul><li>backend/main.py -&gt; run_agent_with_streaming(...)</li><li>backend/main.py -&gt; streaming_execute_run(...) (temporary monkey-patched _execute_run)</li><li>backend/main.py -&gt; stream_events(...) (async queue consumer)</li></ul><pre># backend main.py snippet<br>&quot;&quot;&quot;<br>FastAPI backend with WebSocket support for real-time SSE streaming<br>from the Cortex Agent.<br><br>Features:<br>- Real-time SSE event streaming (tool_use, text_delta, tool_result, metadata)<br>- Session management with LangGraph checkpointer<br>- Multi-turn conversation support<br>- Proper error handling and connection management<br>&quot;&quot;&quot;<br><br>import sys<br>import os<br>import json<br>import uuid<br>import asyncio<br>from typing import Dict<br>from fastapi import FastAPI, WebSocket, WebSocketDisconnect<br>from fastapi.middleware.cors import CORSMiddleware<br>from langgraph.checkpoint.memory import MemorySaver<br><br># Add cortex_agent to sys.path for import<br>sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), &#39;..&#39;)))<br><br>from cortex_agent.config import PAT, ACCOUNT_BASE_URL, DB, SCHEMA, AGENT_NAME<br>from cortex_agent.cortex_client import CortexClient<br>from cortex_agent.graph import build_graph<br>from cortex_agent.state import AgentState<br><br>app = FastAPI(title=&quot;Cortex MCID Agent API&quot;)<br><br># Allow CORS for local frontend dev<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br># Global instances - initialized once at startup<br>checkpointer = MemorySaver()<br>compiled_graph = build_graph(checkpointer=checkpointer)<br>cortex_client = CortexClient(ACCOUNT_BASE_URL, PAT, DB, SCHEMA, AGENT_NAME)<br><br># Active WebSocket connections with session tracking<br>active_connections: Dict[str, WebSocket] = {}<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    &quot;&quot;&quot;Initialize the agent on startup.&quot;&quot;&quot;<br>    print(&quot;=&quot; * 60)<br>    print(&quot;🚀 Cortex Agent Backend Starting...&quot;)<br>    print(f&quot;   Account: {ACCOUNT_BASE_URL}&quot;)<br>    print(f&quot;   Database: {DB}.{SCHEMA}&quot;)<br>    print(f&quot;   Agent: {AGENT_NAME}&quot;)<br>    print(&quot;=&quot; * 60)<br><br><br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Health check endpoint.&quot;&quot;&quot;<br>    return {&quot;status&quot;: &quot;healthy&quot;, &quot;agent&quot;: AGENT_NAME}<br><br><br>@app.websocket(&quot;/ws/chat&quot;) # WebSocket endpoint for front end interaction <br>async def websocket_endpoint(websocket: WebSocket):<br>    &quot;&quot;&quot;<br>    WebSocket endpoint for real-time chat with SSE event streaming.<br>    <br>    Message format from client:<br>        {&quot;message&quot;: &quot;user message text&quot;, &quot;session_id&quot;: &quot;optional-session-id&quot;}<br>    <br>    Response format to client:<br>        {&quot;type&quot;: &quot;event&quot;, &quot;event&quot;: &quot;tool_use&quot;, &quot;data&quot;: {...}}<br>        {&quot;type&quot;: &quot;event&quot;, &quot;event&quot;: &quot;text_delta&quot;, &quot;data&quot;: {&quot;text&quot;: &quot;...&quot;}}<br>        {&quot;type&quot;: &quot;final&quot;, &quot;response&quot;: &quot;final text&quot;, &quot;state&quot;: {...}}<br>        {&quot;type&quot;: &quot;error&quot;, &quot;error&quot;: &quot;error message&quot;}<br>    &quot;&quot;&quot;<br>    await websocket.accept()<br>    session_id = str(uuid.uuid4())<br>    active_connections[session_id] = websocket<br>    <br>    print(f&quot;✅ WebSocket connected | session={session_id}&quot;)<br>    <br>    try:<br>        # Send connection confirmation<br>        await websocket.send_json({<br>            &quot;type&quot;: &quot;connected&quot;,<br>            &quot;session_id&quot;: session_id,<br>            &quot;message&quot;: &quot;Connected to Cortex Agent&quot;<br>        })<br>        <br>        while True:<br>            # Receive message from client<br>            data = await websocket.receive_text() # recewive from frontend<br>            <br>            try:<br>                payload = json.loads(data)<br>                user_message = payload.get(&quot;message&quot;, data) #retrieve message from frontend<br>                client_session_id = payload.get(&quot;session_id&quot;, session_id) # retrieve session id from frontend<br>            except json.JSONDecodeError:<br>                user_message = data<br>                client_session_id = session_id<br>            <br>            print(f&quot;📨 Received message | session={client_session_id} | msg=&#39;{user_message[:50]}...&#39;&quot;)<br>            <br>            # Send acknowledgment<br>            await websocket.send_json({<br>                &quot;type&quot;: &quot;processing&quot;,<br>                &quot;message&quot;: &quot;Processing your request...&quot;<br>            })<br>            <br>            try:  # calling the cortex agent with streaming response handling<br>                # Run the agent with streaming<br>                await run_agent_with_streaming(<br>                    websocket=websocket,<br>                    user_message=user_message,<br>                    session_id=client_session_id<br>                )<br>                <br>            except Exception as e:<br>                error_msg = f&quot;Agent error: {str(e)}&quot;<br>                print(f&quot;❌ Error | session={client_session_id} | {error_msg}&quot;)<br>                await websocket.send_json({<br>                    &quot;type&quot;: &quot;error&quot;,<br>                    &quot;error&quot;: error_msg<br>                })<br>    <br>    except WebSocketDisconnect:<br>        print(f&quot;🔌 WebSocket disconnected | session={session_id}&quot;)<br>        if session_id in active_connections:<br>            del active_connections[session_id]<br>    <br>    except Exception as e:<br>        print(f&quot;❌ WebSocket error | session={session_id} | {str(e)}&quot;)<br>        if session_id in active_connections:<br>            del active_connections[session_id]<br><br><br>async def run_agent_with_streaming(<br>    websocket: WebSocket,<br>    user_message: str,<br>    session_id: str<br>):<br>    &quot;&quot;&quot;<br>    Run the cortex agent and stream SSE events to the WebSocket client in real-time.<br>    <br>    This function intercepts the Cortex Agent&#39;s SSE stream and forwards events<br>    to the WebSocket client as they arrive using a queue.<br>    &quot;&quot;&quot;<br>    <br>    # Prepare initial state<br>    initial_state = {<br>        &quot;user_message&quot;: user_message,<br>        &quot;user_id&quot;: &quot;web_user&quot;,<br>        &quot;chat_id&quot;: 0,<br>    }<br>    <br>    # Config with session for checkpointer<br>    config = {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: session_id,<br>            &quot;client&quot;: cortex_client<br>        }<br>    }<br>    <br>    # Create a queue for real-time event streaming<br>    event_queue = asyncio.Queue()<br>    <br>    # We&#39;ll stream events by patching the cortex_client temporarily<br>    original_execute_run = cortex_client._execute_run<br>    <br>    def streaming_execute_run(payload: dict):<br>        &quot;&quot;&quot;Wrapper that captures SSE events by calling cortex agent api and puts them in queue (synchronous).&quot;&quot;&quot;<br>        from cortex_agent.cortex_client import CortexRunResult<br>        import requests<br>        <br>        url = (<br>            f&quot;{cortex_client.base_url}/api/v2/databases/{cortex_client.db}&quot;<br>            f&quot;/schemas/{cortex_client.schema}/agents/{cortex_client.agent}:run&quot;<br>        )<br>        result = CortexRunResult()<br>        current_event = None<br>        <br>        with requests.post(<br>            url, headers=cortex_client.headers, json=payload,<br>            stream=True, timeout=(10, 300),<br>        ) as r:<br>            if not r.ok:<br>                r.raise_for_status()<br>            <br>            for raw_line in r.iter_lines():<br>                if not raw_line:<br>                    continue<br>                line = raw_line.decode(&quot;utf-8&quot;).strip()<br>                <br>                if line.startswith(&quot;event:&quot;):<br>                    current_event = line[6:].strip()<br>                    continue<br>                <br>                if not line.startswith(&quot;data:&quot;):<br>                    continue<br>                <br>                json_str = line[5:].strip()<br>                if json_str == &quot;[DONE]&quot;:<br>                    break<br>                <br>                try:<br>                    data = json.loads(json_str)<br>                except json.JSONDecodeError:<br>                    continue<br>                <br>                result.raw_events.append({&quot;event&quot;: current_event, &quot;data&quot;: data})<br>                <br>                # Put event in queue for real-time streaming (thread-safe)<br>                event_queue.put_nowait({<br>                    &quot;type&quot;: &quot;sse_event&quot;,<br>                    &quot;event&quot;: current_event,<br>                    &quot;data&quot;: data<br>                })<br>                <br>                # Process event for result object<br>                if current_event == &quot;metadata&quot; and &quot;metadata&quot; in data:<br>                    meta = data[&quot;metadata&quot;]<br>                    if meta.get(&quot;role&quot;) == &quot;assistant&quot;:<br>                        result.parent_message_id = meta.get(&quot;message_id&quot;, result.parent_message_id)<br>                <br>                elif current_event == &quot;response.tool_use&quot;:<br>                    if data.get(&quot;client_side_execute&quot;, True):<br>                        tool_call = {<br>                            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>                            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>                            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>                        }<br>                        result.tool_calls.append(tool_call)<br>                <br>                elif current_event == &quot;response.text.delta&quot;:<br>                    chunk = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if chunk:<br>                        result.text_chunks.append(chunk)<br>                <br>                elif current_event == &quot;response.text&quot;:<br>                    text = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if text:<br>                        result.final_text = text<br>                <br>                elif current_event == &quot;response&quot;:<br>                    result.final_text = cortex_client._extract_text(data)<br>                <br>                elif current_event == &quot;error&quot;:<br>                    err_msg = data.get(&quot;message&quot;, &quot;unknown error&quot;)<br>                    err_code = data.get(&quot;code&quot;, &quot;&quot;)<br>                    result.final_text = f&quot;[Agent Error {err_code}]: {err_msg}&quot;<br>        <br>        return result<br>    <br>    # Temporarily replace the method<br>    cortex_client._execute_run = streaming_execute_run<br>    <br>    # Task to consume events from queue and send to WebSocket<br>    async def stream_events():<br>        &quot;&quot;&quot;Continuously read from queue and send events to WebSocket.&quot;&quot;&quot;<br>        while True:<br>            try:<br>                event = await asyncio.wait_for(event_queue.get(), timeout=0.1)<br>                await websocket.send_json(event)<br>            except asyncio.TimeoutError:<br>                # Check if graph is done<br>                if not graph_task or graph_task.done():<br>                    # Drain any remaining events<br>                    while not event_queue.empty():<br>                        event = event_queue.get_nowait()<br>                        await websocket.send_json(event)<br>                    break<br>            except Exception as e:<br>                print(f&quot;Error streaming event: {e}&quot;)<br>                break<br>    <br>    try:<br>        # Start the graph execution in a thread<br>        graph_task = asyncio.create_task(<br>            asyncio.to_thread(<br>                compiled_graph.invoke,<br>                initial_state,<br>                config<br>            )<br>        )<br>        <br>        # Start streaming events concurrently<br>        stream_task = asyncio.create_task(stream_events())<br>        <br>        # Wait for graph to complete<br>        final_state = await graph_task<br>        <br>        # Wait for streaming to finish<br>        await stream_task<br>        <br>        # Send final response<br>        await websocket.send_json({<br>            &quot;type&quot;: &quot;final&quot;,<br>            &quot;response&quot;: final_state.get(&quot;final_response&quot;, &quot;(no response)&quot;),<br>            &quot;state&quot;: {<br>                &quot;thread_id&quot;: final_state.get(&quot;thread_id&quot;),<br>                &quot;parent_message_id&quot;: final_state.get(&quot;parent_message_id&quot;),<br>                &quot;pii_blocked&quot;: final_state.get(&quot;pii_blocked&quot;, False),<br>                &quot;node_outputs&quot;: final_state.get(&quot;node_outputs&quot;, {}),<br>            }<br>        })<br>        <br>        print(f&quot;✅ Agent completed | session={session_id} | response_len={len(final_state.get(&#39;final_response&#39;, &#39;&#39;))}&quot;)<br>        <br>    finally:<br>        # Restore original method<br>        cortex_client._execute_run = original_execute_run<br><br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>The solution: an asyncio.Queue as the bridge, with queue.put_nowait() called from the synchronous side and asyncio.wait_for(queue.get(), timeout=0.1) on the async side.</p><p>In backend/main.py, the streaming wrapper monkey-patches cortex_client._execute_run for the duration of the request:</p><p>The async consumer drains the queue and forwards events to the browser:</p><p>The graph runs concurrently via asyncio.to_thread:</p><p>After both tasks stream_task and graph_task finish, a {&quot;type&quot;: &quot;final&quot;, ...} message carries the complete response and state back to the browser. The original _execute_run is restored in the finally block.</p><h3>What Lives In cortex_agent</h3><p>The WebSocket bridge in backend/main.py is only the transport layer. The actual agent behavior lives in cortex_agent, and that is what makes the architecture complete:</p><ul><li>cortex_agent/cortex_client.py creates the Snowflake thread, sends :run requests, parses SSE events, and separates client-side tool calls from server-side ones.</li></ul><pre># cortex_client.py snippet<br>&quot;&quot;&quot;<br>Snowflake Cortex Agent REST API client with SSE stream parsing.<br><br>Reused from cortex_agent_client_side — handles thread creation,<br>agent :run calls, and parsing tool_use / text events.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>import json<br>from dataclasses import dataclass, field<br><br>import requests<br><br>from .logs import get_logger<br><br>logger = get_logger(&quot;cortex-client&quot;)<br><br><br>@dataclass<br>class CortexRunResult:<br>    &quot;&quot;&quot;Parsed result from a single Cortex Agent :run SSE stream.&quot;&quot;&quot;<br>    tool_calls: list[dict] = field(default_factory=list)<br>    text_chunks: list[str] = field(default_factory=list)<br>    final_text: str = &quot;&quot;<br>    parent_message_id: int = 0<br>    raw_events: list[dict] = field(default_factory=list)<br><br>    @property<br>    def has_tool_calls(self) -&gt; bool:<br>        return len(self.tool_calls) &gt; 0<br><br>    @property<br>    def assembled_text(self) -&gt; str:<br>        return self.final_text or &quot;&quot;.join(self.text_chunks).strip()<br><br><br>class CortexClient:<br>    &quot;&quot;&quot;Client for the Snowflake Cortex Agent REST API.&quot;&quot;&quot;<br><br>    def __init__(self, base_url: str, pat: str, db: str, schema: str, agent: str):<br>        logger.info(&quot;Initializing CortexClient constructor| base_url=%s db=%s schema=%s agent=%s&quot;,<br>                    base_url, db, schema, agent)<br>        self.base_url = base_url.rstrip(&quot;/&quot;)<br>        self.db = db<br>        self.schema = schema<br>        self.agent = agent<br>        self.headers = {<br>            &quot;Authorization&quot;: f&quot;Bearer {pat.strip()}&quot;,<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            &quot;Accept&quot;: &quot;application/json&quot;,<br>        }<br><br>    def create_thread(self) -&gt; tuple[str, int]:<br>        &quot;&quot;&quot;Create a Cortex thread. Returns (thread_id, parent_message_id).&quot;&quot;&quot;<br>        logger.info(&quot;inside create_thread ..Creating Cortex thread...&quot;)<br>        url = f&quot;{self.base_url}/api/v2/cortex/threads&quot;<br>        r = requests.post(<br>            url,<br>            headers=self.headers,<br>            json={&quot;origin_application&quot;: &quot;mcid_langgraph&quot;},<br>            timeout=30,<br>        )<br>        if not r.ok:<br>            logger.error(&quot;create_thread failed | status=%s body=%s&quot;, r.status_code, r.text[:500])<br>            r.raise_for_status()<br>        data = r.json()<br>        thread_id = data.get(&quot;thread_id&quot;) or data.get(&quot;threadId&quot;) or data.get(&quot;id&quot;)<br>        parent_id = data.get(&quot;parent_message_id&quot;) or data.get(&quot;parentMessageId&quot;) or data.get(&quot;message_id&quot;, 0)<br>        logger.info(&quot;Thread created | thread_id=%s parent_message_id=%s&quot;, thread_id, parent_id)<br>        return thread_id, parent_id<br><br>    def run_agent(self, thread_id: str, parent_message_id: int, user_message: str) -&gt; CortexRunResult:<br>        &quot;&quot;&quot;Send a user message to the agent and parse the SSE stream for results.&quot;&quot;&quot;<br>        logger.info(&quot;inside run_agent ..Running agent with user message...&quot;)<br>        payload = {<br>            &quot;thread_id&quot;: thread_id,<br>            &quot;parent_message_id&quot;: parent_message_id,<br>            &quot;stream&quot;: True,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: user_message}]}<br>            ],<br>        }<br>        logger.info(&quot;Sending user message | thread=%s parent=%s&quot;, thread_id, parent_message_id)<br>        return self._execute_run(payload)<br><br>    def run_agent_with_tool_results(<br>        self, thread_id: str, parent_message_id: int, tool_results: list[dict]<br>    ) -&gt; CortexRunResult:<br>        &quot;&quot;&quot;Send tool results back to the agent and parse the SSE stream.&quot;&quot;&quot;<br>        logger.info(&quot;Sending tool results | thread=%s parent=%s count=%d&quot;,<br>                     thread_id, parent_message_id, len(tool_results))<br><br>        # Build content items following Snowflake&#39;s documented tool_result schema:<br>        #   {<br>        #     &quot;type&quot;: &quot;tool_result&quot;,<br>        #     &quot;tool_result&quot;: {<br>        #       &quot;tool_use_id&quot;: &quot;...&quot;,<br>        #       &quot;name&quot;: &quot;&lt;tool name&gt;&quot;,<br>        #       &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: {...}}],<br>        #       &quot;status&quot;: &quot;success&quot; | &quot;error&quot;<br>        #     }<br>        #   }<br>        content_parts = []<br>        for tr in tool_results:<br>            raw = tr[&quot;content&quot;]<br>            # Try to parse as JSON so the agent gets structured data<br>            try:<br>                parsed = json.loads(raw) if isinstance(raw, str) else raw<br>            except (json.JSONDecodeError, TypeError):<br>                parsed = raw<br><br>            # Snowflake requires `&quot;json&quot;` to be an object `{}`, never a<br>            # string, number, or array.  Wrap any non-dict value.<br>            if isinstance(parsed, dict):<br>                json_value = parsed<br>            elif isinstance(parsed, list):<br>                json_value = {&quot;result&quot;: parsed}<br>            else:<br>                json_value = {&quot;result&quot;: parsed}<br><br>            tool_result_obj: dict = {<br>                &quot;tool_use_id&quot;: tr[&quot;tool_use_id&quot;],<br>                &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: json_value}],<br>                &quot;status&quot;: &quot;error&quot; if tr.get(&quot;is_error&quot;) else &quot;success&quot;,<br>            }<br><br>            # Include tool name when available (from graph.execute_tools)<br>            if tr.get(&quot;tool_name&quot;):<br>                tool_result_obj[&quot;name&quot;] = tr[&quot;tool_name&quot;]<br><br>            content_parts.append({<br>                &quot;type&quot;: &quot;tool_result&quot;,<br>                &quot;tool_result&quot;: tool_result_obj,<br>            })<br><br>        payload = {<br>            &quot;thread_id&quot;: thread_id,<br>            &quot;parent_message_id&quot;: parent_message_id,<br>            # Use the same key as run_agent (streaming SSE)<br>            &quot;stream&quot;: True,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: content_parts},<br>            ],<br>        }<br>        logger.info(&quot;Sending %d tool result(s) | thread=%s parent=%s&quot;,<br>                     len(tool_results), thread_id, parent_message_id)<br>        logger.info(&quot;Tool result payload | %s&quot;, json.dumps(payload, default=str)[:2000])<br>        return self._execute_run(payload)<br>    def _execute_run(self, payload: dict) -&gt; CortexRunResult:<br>        &quot;&quot;&quot; Internal method to execute an agent run with the given payload and parse the SSE stream for results.   &quot;&quot;&quot;<br>        logger.info(&quot;inside _execute_run ..Executing agent run with payload...&quot;)<br>        url = (<br>            f&quot;{self.base_url}/api/v2/databases/{self.db}&quot;<br>            f&quot;/schemas/{self.schema}/agents/{self.agent}:run&quot;<br>        )<br>        result = CortexRunResult()<br>        current_event: str | None = None<br><br>        with requests.post(<br>            url, headers=self.headers, json=payload,<br>            stream=True, timeout=(10, 300),<br>        ) as r:<br>            logger.info(&quot;Agent :run response | status=%s&quot;, r.status_code)<br>            if not r.ok:<br>                body = r.text[:500] if r.text else &quot;(empty)&quot;<br>                logger.error(&quot;Agent :run failed | status=%s body=%s&quot;, r.status_code, body)<br>                logger.error(&quot;Agent :run payload sent | %s&quot;, json.dumps(payload, default=str)[:1000])<br>            r.raise_for_status()<br><br>            for raw_line in r.iter_lines():<br>                if not raw_line:<br>                    continue<br>                line = raw_line.decode(&quot;utf-8&quot;).strip()<br><br>                if line.startswith(&quot;event:&quot;):<br>                    current_event = line[6:].strip()<br>                    logger.info(&quot;SSE event | %s&quot;, current_event)<br><br>                    continue<br><br>                if not line.startswith(&quot;data:&quot;):<br>                    continue<br><br>                json_str = line[5:].strip()<br>                if json_str == &quot;[DONE]&quot;:<br>                    logger.info(&quot;SSE stream complete&quot;)<br>                    break<br><br>                try:<br>                    data = json.loads(json_str)<br>                except json.JSONDecodeError:<br>                    logger.warning(&quot;Skipping non-JSON SSE data | %s&quot;, json_str)<br>                    continue<br><br>                result.raw_events.append({&quot;event&quot;: current_event, &quot;data&quot;: data})<br>                logger.info(&quot;SSE data | event=%s keys=%s&quot;, current_event, list(data.keys()) if isinstance(data, dict) else type(data).__name__)<br>                if current_event == &quot;metadata&quot; and &quot;metadata&quot; in data:<br>                    meta = data[&quot;metadata&quot;]<br>                    if meta.get(&quot;role&quot;) == &quot;assistant&quot;:<br>                        result.parent_message_id = meta.get(&quot;message_id&quot;, result.parent_message_id)<br>                        logger.info(&quot;Assistant message_id captured | %s&quot;, result.parent_message_id)<br><br>                elif current_event == &quot;response.tool_use&quot;:<br>                    # Only collect client-side tools for local execution.<br>                    # Server-side tools (cortex_search, cortex_analyst) have<br>                    # client_side_execute=False and are handled by Snowflake.<br>                    if data.get(&quot;client_side_execute&quot;, True):<br>                        tool_call = {<br>                            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>                            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>                            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>                        }<br>                        result.tool_calls.append(tool_call)<br>                        logger.info(&quot;Tool call (client-side) | name=%s args=%s&quot;,<br>                                    tool_call[&quot;name&quot;], tool_call[&quot;input&quot;])<br>                    else:<br>                        logger.info(&quot;Tool call (server-side, skipping) | name=%s&quot;,<br>                                    data.get(&quot;name&quot;, &quot;unknown&quot;))<br><br>                elif current_event == &quot;response.tool_result&quot;:<br>                    # Server-side tool (e.g. Cortex Search) — executed inside<br>                    # Snowflake. We log it but don&#39;t need to act; the agent<br>                    # continues processing and will produce final text.<br>                    tool_name = data.get(&quot;name&quot;, &quot;unknown&quot;)<br>                    logger.info(&quot;Tool result (server-side) | name=%s&quot;, tool_name)<br><br>                elif current_event == &quot;response.text.delta&quot;:<br>                    chunk = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if chunk:<br>                        result.text_chunks.append(chunk)<br><br>                elif current_event == &quot;response.text&quot;:<br>                    text = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if text:<br>                        result.final_text = text<br><br>                elif current_event == &quot;response&quot;:<br>                    result.final_text = self._extract_text(data)<br>                <br>                elif current_event == &quot;error&quot;:<br>                    err_msg = data.get(&quot;message&quot;, &quot;unknown error&quot;)<br>                    err_code = data.get(&quot;code&quot;, &quot;&quot;)<br>                    logger.error(&quot;SSE error event | code=%s message=%s&quot;, err_code, err_msg)<br>                    result.final_text = f&quot;[Agent Error {err_code}]: {err_msg}&quot;<br><br>        logger.info(&quot;Run result | tool_calls=%d text_len=%d&quot;,<br>                     len(result.tool_calls), len(result.assembled_text))<br>        return result<br><br>    @staticmethod<br>    def _extract_text(data: dict) -&gt; str:<br>        content = data.get(&quot;content&quot;, [])<br>        if not isinstance(content, list):<br>            return &quot;&quot;<br>        parts = []<br>        for item in content:<br>            if isinstance(item, dict) and item.get(&quot;type&quot;) == &quot;text&quot;:<br>                t = item.get(&quot;text&quot;, &quot;&quot;)<br>                if t:<br>                    parts.append(t)<br>        return &quot;\n&quot;.join(parts).strip()</pre><ul><li>cortex_agent/graph.py defines the LangGraph loop: pii_check -&gt; init_thread -&gt; call_agent -&gt; execute_tools -&gt; call_agent until no tools remain.</li></ul><pre># cortex_agent/graph.py snippet<br>&quot;&quot;&quot;<br>LangGraph graph for Cortex Agent — client-side tool execution.<br><br>Architecture:<br>    ┌───────────┐<br>    │   START    │<br>    └─────┬─────┘<br>          │<br>    ┌─────▼─────┐   PII detected<br>    │  pii_check │──────────────────────► END  (block message)<br>    └─────┬─────┘<br>          │ clean<br>    ┌─────▼──────┐   already has thread_id?<br>    │ init_thread │   ──► skip creation<br>    └─────┬──────┘<br>          │<br>    ┌─────▼──────┐◄──────────────────────┐<br>    │ call_agent  │                       │<br>    └─────┬──────┘                       │<br>          │                              │<br>    ┌─────▼──────┐                       │<br>    │   route     │──► done ──► END      │<br>    └─────┬──────┘                       │<br>          │ tools                        │<br>    ┌─────▼──────────┐                   │<br>    │ execute_tools   │──────────────────┘<br>    └────────────────┘        (loop)<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.types import RunnableConfig<br><br>from .state import AgentState<br>from .cortex_client import CortexClient, CortexRunResult<br>from .tools import execute_tool<br>from .tools.pii_guard import detect_sensitive_patterns, build_pii_block_response<br>from .config import MAX_TOOL_ITERATIONS<br>from .logs import get_logger<br><br>logger = get_logger(&quot;graph&quot;)<br><br><br># ================================================================== #<br>#  Node: pii_check<br># ================================================================== #<br><br>def pii_check(state: AgentState) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Pre-check the user message for PII / sensitive patterns.<br>    If detected, set pii_blocked=True and a block response.<br>    &quot;&quot;&quot;<br>    msg = state.get(&quot;user_message&quot;, &quot;&quot;)<br>    is_sensitive, patterns = detect_sensitive_patterns(msg)<br><br>    if is_sensitive:<br>        logger.warning(&quot;PII guard blocked request | patterns=%s&quot;, patterns)<br>        return {<br>            &quot;pii_blocked&quot;: True,<br>            &quot;final_response&quot;: build_pii_block_response(patterns),<br>        }<br><br>    return {&quot;pii_blocked&quot;: False}<br><br><br>def pii_route(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;Route after PII check: block or continue.&quot;&quot;&quot;<br>    if state.get(&quot;pii_blocked&quot;):<br>        return &quot;blocked&quot;<br>    return &quot;clean&quot;<br><br><br># ================================================================== #<br>#  Node: init_thread<br># ================================================================== #<br><br>def init_thread(state: AgentState, config: RunnableConfig) -&gt; dict:<br>    &quot;&quot;&quot;Create a Cortex thread if one doesn&#39;t exist yet.&quot;&quot;&quot;<br>    if state.get(&quot;thread_id&quot;):<br>        logger.info(&quot;Reusing existing thread | thread_id=%s&quot;, state[&quot;thread_id&quot;])<br>        return {}<br><br>    client: CortexClient = config[&quot;configurable&quot;][&quot;client&quot;]<br>    thread_id, parent_id = client.create_thread()<br>    return {<br>        &quot;thread_id&quot;: thread_id,<br>        &quot;parent_message_id&quot;: parent_id,<br>        &quot;iteration&quot;: 0,<br>    }<br><br><br># ================================================================== #<br>#  Node: call_agent<br># ================================================================== #<br><br>def call_agent(state: AgentState, config: RunnableConfig) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Send a user message or tool results to the Cortex Agent.<br>    Parses the SSE stream and captures tool calls or final text.<br>    &quot;&quot;&quot;<br>    client: CortexClient = config[&quot;configurable&quot;][&quot;client&quot;]<br>    tool_results = state.get(&quot;tool_results&quot;, [])<br><br>    if tool_results:<br>        result: CortexRunResult = client.run_agent_with_tool_results(<br>            state[&quot;thread_id&quot;],<br>            state[&quot;parent_message_id&quot;],<br>            tool_results,<br>        )<br>    else:<br>        result = client.run_agent(<br>            state[&quot;thread_id&quot;],<br>            state[&quot;parent_message_id&quot;],<br>            state[&quot;user_message&quot;],<br>        )<br><br>    updates: dict = {<br>        &quot;pending_tool_calls&quot;: result.tool_calls,<br>        &quot;tool_results&quot;: [],<br>        &quot;iteration&quot;: state.get(&quot;iteration&quot;, 0) + 1,<br>    }<br><br>    if result.parent_message_id:<br>        updates[&quot;parent_message_id&quot;] = result.parent_message_id<br><br>    if not result.has_tool_calls:<br>        updates[&quot;final_response&quot;] = result.assembled_text<br>        logger.info(&quot;Agent produced final text (%d chars)&quot;, len(result.assembled_text))<br>    else:<br>        logger.info(&quot;Agent requested %d tool call(s)&quot;, len(result.tool_calls))<br><br>    return updates<br><br><br># ================================================================== #<br>#  Node: execute_tools<br># ================================================================== #<br><br>def execute_tools(state: AgentState) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Execute all pending client-side tool calls and prepare results<br>    for the next call_agent invocation.<br>    &quot;&quot;&quot;<br>    pending = state.get(&quot;pending_tool_calls&quot;, [])<br>    results = []<br>    node_outputs = dict(state.get(&quot;node_outputs&quot;) or {})<br><br>    for tc in pending:<br>        name = tc[&quot;name&quot;]<br>        args = tc.get(&quot;input&quot;, {})<br>        tool_use_id = tc[&quot;tool_use_id&quot;]<br><br>        logger.info(&quot;Executing tool | name=%s id=%s&quot;, name, tool_use_id)<br>        content, is_error = execute_tool(name, args)<br><br>        results.append({<br>            &quot;tool_use_id&quot;: tool_use_id,<br>            &quot;tool_name&quot;: name,<br>            &quot;content&quot;: content,<br>            &quot;is_error&quot;: is_error,<br>        })<br><br>        # Track per-issue output for Jira / summary<br>        mcid_list = args.get(&quot;mcid_list&quot;, [])<br>        if mcid_list and name == &quot;create_jira_ticket&quot;:<br>            key = &quot;|&quot;.join(str(m) for m in mcid_list)<br>            entry = node_outputs.get(key, {})<br>            if &quot;Created successfully&quot; in content or &quot;Ticket ID:&quot; in content:<br>                # Extract ticket ID from content<br>                for line in content.splitlines():<br>                    if line.startswith(&quot;Ticket ID:&quot;):<br>                        entry[&quot;jira_no&quot;] = line.split(&quot;:&quot;, 1)[1].strip()<br>                        break<br>            entry[&quot;agent_name&quot;] = &quot;create_jira_ticket&quot;<br>            entry[&quot;mcid_list&quot;] = mcid_list<br>            node_outputs[key] = entry<br><br>    logger.info(<br>        &quot;Tools executed | count=%d errors=%d&quot;,<br>        len(results),<br>        sum(1 for r in results if r[&quot;is_error&quot;]),<br>    )<br><br>    return {<br>        &quot;tool_results&quot;: results,<br>        &quot;pending_tool_calls&quot;: [],<br>        &quot;node_outputs&quot;: node_outputs,<br>    }<br><br><br># ================================================================== #<br>#  Conditional Edge: route_decision<br># ================================================================== #<br><br>def route_decision(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;<br>    After call_agent, decide whether to execute tools or finish.<br>    &quot;&quot;&quot;<br>    if state.get(&quot;iteration&quot;, 0) &gt;= MAX_TOOL_ITERATIONS:<br>        logger.warning(&quot;Max tool iterations (%d) reached — stopping.&quot;, MAX_TOOL_ITERATIONS)<br>        return &quot;done&quot;<br><br>    if state.get(&quot;pending_tool_calls&quot;):<br>        return &quot;execute_tools&quot;<br><br>    return &quot;done&quot;<br><br><br># ================================================================== #<br>#  Build &amp; Compile<br># ================================================================== #<br><br>def build_graph(checkpointer=None):<br>    &quot;&quot;&quot;<br>    Construct and compile the LangGraph StateGraph.<br><br>    Args:<br>        checkpointer:  A LangGraph checkpointer for automatic state<br>                       persistence across turns.  Pass ``None`` for<br>                       stateless single-turn usage (e.g. unit tests).<br>                       Common choices:<br>                         - ``MemorySaver()``      — in-process dict<br>                         - ``SqliteSaver(conn)``   — file-backed<br>                         - ``PostgresSaver(pool)`` — production<br><br>    Required initial state keys:<br>        user_message  — the user&#39;s prompt<br><br>    The CortexClient must be passed via config, not state:<br>        config = {&quot;configurable&quot;: {&quot;client&quot;: client_instance}}<br><br>    When using a checkpointer, also include the session thread_id:<br>        config = {&quot;configurable&quot;: {&quot;client&quot;: client, &quot;thread_id&quot;: &quot;&lt;session&gt;&quot;}}<br>    The checkpointer auto-restores thread_id, parent_message_id,<br>    node_outputs, etc. from the previous turn — no manual carry-forward.<br>    &quot;&quot;&quot;<br>    graph = StateGraph(AgentState)<br><br>    # Nodes<br>    graph.add_node(&quot;pii_check&quot;, pii_check)<br>    graph.add_node(&quot;init_thread&quot;, init_thread)<br>    graph.add_node(&quot;call_agent&quot;, call_agent)<br>    graph.add_node(&quot;execute_tools&quot;, execute_tools)<br><br>    # START → pii_check<br>    graph.add_edge(START, &quot;pii_check&quot;)<br><br>    # pii_check → blocked(END) | clean → init_thread<br>    graph.add_conditional_edges(<br>        &quot;pii_check&quot;,<br>        pii_route,<br>        {<br>            &quot;blocked&quot;: END,<br>            &quot;clean&quot;: &quot;init_thread&quot;,<br>        },<br>    )<br><br>    # init_thread → call_agent<br>    graph.add_edge(&quot;init_thread&quot;, &quot;call_agent&quot;)<br><br>    # call_agent → route → execute_tools | done(END)<br>    graph.add_conditional_edges(<br>        &quot;call_agent&quot;,<br>        route_decision,<br>        {<br>            &quot;execute_tools&quot;: &quot;execute_tools&quot;,<br>            &quot;done&quot;: END,<br>        },<br>    )<br><br>    # execute_tools → call_agent  (loop back)<br>    graph.add_edge(&quot;execute_tools&quot;, &quot;call_agent&quot;)<br><br>    compiled = graph.compile(checkpointer=checkpointer)<br>    logger.info(&quot;MCID LangGraph compiled | checkpointer=%s&quot;,<br>                type(checkpointer).__name__ if checkpointer else &quot;None&quot;)<br>    return compiled</pre><ul><li>cortex_agent/state.py defines the shared AgentState, including thread_id, parent_message_id, pending_tool_calls, tool_results, and node_outputs.</li></ul><pre>&quot;&quot;&quot;LangGraph state for MCID Cortex Agent — client-side tool execution.<br><br>Memory tiers used:<br>  - **Checkpointer** (MemorySaver / SqliteSaver) auto-persists the full state<br>    between invoke() calls sharing the same LangGraph thread_id.  This means<br>    thread_id, parent_message_id, and node_outputs survive across turns without<br>    manual carry-forward in main.py.<br>  - **Cortex server-side thread** still holds the conversation messages.<br>    LangGraph does NOT duplicate that — it only persists orchestration metadata.<br><br>Reducers:<br>  - node_outputs uses a custom merge-reducer so that new per-issue entries are<br>    merged into the existing dict rather than overwriting it.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>from typing import Annotated, Any, TypedDict<br><br><br># ------------------------------------------------------------------ #<br>#  Custom reducer for node_outputs (merge, don&#39;t overwrite)<br># ------------------------------------------------------------------ #<br><br>def _merge_node_outputs(<br>    existing: dict[str, &quot;NodeOutput&quot;] | None,<br>    new: dict[str, &quot;NodeOutput&quot;] | None,<br>) -&gt; dict[str, &quot;NodeOutput&quot;]:<br>    &quot;&quot;&quot;Merge new per-issue entries into the existing dict.<br><br>    This keeps all previously tracked issues in state while adding<br>    or updating entries from the current turn.<br>    &quot;&quot;&quot;<br>    base = dict(existing) if existing else {}<br>    if new:<br>        for key, val in new.items():<br>            if key in base:<br>                # Merge fields — keep existing, overlay new<br>                merged = {**base[key], **val}<br>                base[key] = merged  # type: ignore[assignment]<br>            else:<br>                base[key] = val<br>    return base<br><br><br># ------------------------------------------------------------------ #<br>#  State types<br># ------------------------------------------------------------------ #<br><br>class ToolCall(TypedDict):<br>    &quot;&quot;&quot;A tool call from Cortex Agent (client_side_execute=true).&quot;&quot;&quot;<br>    tool_use_id: str<br>    name: str<br>    input: dict<br><br><br>class ToolResult(TypedDict):<br>    &quot;&quot;&quot;A tool result to send back to Cortex Agent.&quot;&quot;&quot;<br>    tool_use_id: str<br>    content: str<br>    is_error: bool<br><br><br>class NodeOutput(TypedDict, total=False):<br>    &quot;&quot;&quot;<br>    Per-issue tracking object — maps to your projectwork&#39;s NodeOutput model.<br>    Keyed by pipe-delimited MCIDs in the node_outputs dict.<br>    &quot;&quot;&quot;<br>    agent_name: str<br>    issue_description: str<br>    issue_category: str<br>    mcid_list: list[str]<br>    jira_no: str<br>    eof: str<br><br><br>class AgentState(TypedDict, total=False):<br>    &quot;&quot;&quot;<br>    Shared state flowing through the LangGraph graph.<br><br>    Mirrors your projectwork&#39;s ChatState but adapted for Cortex Agent<br>    orchestration.  Persisted between turns by the checkpointer.<br><br>    Attributes:<br>        user_message:       Current user prompt.<br>        user_id:            Logged-in user identifier.<br>        chat_id:            Chat session ID.<br>        thread_id:          Cortex thread ID for conversation continuity.<br>        parent_message_id:  Last message ID in the thread.<br>        pending_tool_calls: Tool calls returned by Cortex (client_side_execute).<br>        tool_results:       Results after local tool execution.<br>        final_response:     Agent&#39;s final text response.<br>        node_outputs:       Per-issue tracking — uses merge-reducer so entries<br>                            accumulate across turns (e.g. multiple Jira tickets).<br>        iteration:          Safety counter for tool-execution loops.<br>        pii_blocked:        True if PII was detected and request was blocked.<br>    &quot;&quot;&quot;<br>    user_message: str<br>    user_id: str<br>    chat_id: int<br>    thread_id: str<br>    parent_message_id: int<br>    pending_tool_calls: list[ToolCall]<br>    tool_results: list[ToolResult]<br>    final_response: str<br>    node_outputs: Annotated[dict[str, NodeOutput], _merge_node_outputs]<br>    iteration: int<br>    pii_blocked: bool</pre><ul><li>cortex_agent/tools.py is the local dispatcher that executes client-side tools like Jira creation and record comparison.</li><li>cortex_agent/config.py supplies the agent name, database, schema, PAT, and the tool-loop limit.</li></ul><p>What it does: hands the incoming WebSocket message to the streaming bridge, which runs the LangGraph agent in a thread, captures Cortex SSE events, and forwards them to the browser as they arrive.</p><h3>The Tool Round-Trip Loop</h3><p>When the SSE stream contains response.tool_use events with client_side_execute: true, the LangGraph call_agent node returns them to the graph router. The execute_tools node runs the corresponding Python functions locally (Snowflake SDK calls, REST API calls, etc.) and builds tool_result content blocks:</p><pre>{<br>    &quot;type&quot;: &quot;tool_result&quot;,<br>    &quot;tool_result&quot;: {<br>        &quot;tool_use_id&quot;: &quot;...&quot;,<br>        &quot;name&quot;: &quot;validate_ids&quot;,<br>        &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: {&quot;result&quot;: [...]}}],<br>        &quot;status&quot;: &quot;success&quot;<br>    }<br>}</pre><p>These are posted back to /agents/:run with stream=True, starting a new SSE stream. The loop repeats until no tool_use events remain in the response.</p><p>One constraint I hit: json inside a tool_result must be a JSON object ({}), never a string or array. Snowflake&#39;s parser rejects non-object values silently. My client wraps lists and scalars:</p><pre>if isinstance(parsed, dict):<br>    json_value = parsed<br>elif isinstance(parsed, list):<br>    json_value = {&quot;result&quot;: parsed}<br>else:<br>    json_value = {&quot;result&quot;: parsed}</pre><h3>Tradeoffs I Accepted</h3><p><strong>SSE protocol coupling</strong> is real. My event parser is tightly coupled to Snowflake’s SSE event names (response.tool_use, response.text.delta, etc.). When Snowflake changed the response event schema between API versions, my _extract_text fallback was the only safety net.</p><p><strong>The monkey-patch pattern</strong> works but is not pretty. I replaced it in later iterations with a proper LangGraph astream_events call (available when using GPT-4o as orchestrator via compiled_graph.astream_events()). The async-native approach is cleaner — no queue, no thread boundary.</p><p><strong>Tool results add a round-trip.</strong> Every client-side tool call adds one full SSE request-response cycle. For a query that triggers three tools, that is three sequential :run calls before the agent produces final text. Latency is noticeable.</p><h3>What Comes Next: GPT-4o and MCP</h3><p>This architecture keeps all tools in Python and all orchestration inside Snowflake Cortex. That works, but it has a ceiling: the Mistral/Llama3 models reasoning inside Cortex are weaker than GPT-4o for complex multi-step analysis. The SSE protocol coupling is also fragile — I am parsing a schema I do not own.</p><p>The next iteration in this series switches the orchestrator from Snowflake Cortex to GPT-4o, and replaces the hand-wired Python tool registry with <strong>Model Context Protocol (MCP)</strong>. Instead of dispatching tools locally, the agent connects to a Snowflake-hosted MCP server over streamable_http. The tools — identity lookup, source mapping, record comparison — are served as MCP tool definitions and executed inside Snowflake&#39;s infrastructure.</p><pre>GPT-4o (orchestrator)<br>  │<br>  ▼<br>MultiServerMCPClient  (LangGraph ToolNode)<br>  │  streamable_http + PAT<br>  ▼<br>Snowflake MCP Server  (IDENTITY_MCP_SERVER)<br>  │  tools: identity lookups, source mapping, record analysis, FAQ search<br>  ▼<br>Snowflake Cortex Agent  (nested — handles lineage + cross-walk SPs)<br>  │  REST + SSE<br>  ▼<br>Response</pre><p>The graph shrinks from 4 nodes to 2 (supervisor + tools). The monkey-patch queue pattern disappears — LangGraph&#39;s native astream_events async generator handles streaming cleanly. The tradeoff: the tool round-trip becomes a 3-hop chain (GPT-4o → MCP client → MCP server → Cortex Agent → SSE back), and the PII guard from this architecture is absent in the initial MCP version.</p><p>That’s the subject of the next post in this series.</p><h3>Takeaways</h3><ul><li><strong>SSE line parsing is simple but brittle</strong>: event: + data: pairs are easy to parse, but you are coupling to a schema you do not control. Log raw events in development.</li><li><strong>client_side_execute is your routing key</strong>: Snowflake tells you which tools it cannot run itself. Trust it, and skip server-side tool results on the client.</li><li><strong>asyncio.Queue is the right bridge</strong>: For sync-to-async event forwarding, a queue with put_nowait (sync) and wait_for(get(), timeout) (async) is clean and backpressure-safe.</li><li><strong>Monkey-patching for streaming is a smell</strong>: It works, but the correct fix is an async-native streaming primitive at the graph level (astream_events). Plan for it from the start.</li><li><strong>Tool results must be objects</strong>: Snowflake’s tool_result.content[].json field rejects non-dict values silently. Wrap your data defensively.</li></ul><p><em>Disclaimer: This article reflects my personal engineering experience. All examples are anonymized and shared for educational purposes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4b7f9b8a9b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Cortex Agent as Orchestrator: LangGraph + FastAPI + React Streaming]]></title>
            <link>https://medium.com/@ameeatus/snowflake-cortex-agent-as-orchestrator-langgraph-fastapi-react-streaming-366142e9803a?source=rss-ca01cb24732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/366142e9803a</guid>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[snowflake-cortex-agent]]></category>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[sse-streaming]]></category>
            <dc:creator><![CDATA[Ameeya khadanga]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 22:42:22 GMT</pubDate>
            <atom:updated>2026-06-07T23:05:14.595Z</atom:updated>
            <content:encoded><![CDATA[<p>I built an identity-resolution assistant that helps me investigate whether records belong to the same person, create Jira tickets, answer FAQ questions, and explain data lineage or data issues. It streams responses and tool events live to the browser, with Cortex Agent as the orchestrator and LangGraph as the agentic framework.</p><p>Snowflake Cortex Agent speaks Server-Sent Events. Browsers speak WebSocket. In this architecture, Cortex Agent acted as the orchestrator: it selected tools, routed execution between server-side and client-side paths, and managed prompt context while streaming. My LangGraph graph sat in the middle, and I had to make both sides stream in real time — without blocking the event loop.</p><h3>The Problem</h3><p>The Cortex Agent REST API streams its responses as SSE (text/event-stream), emitting discrete events for tool calls, text deltas, and metadata. Cortex Agent was the orchestrator in this version, not just a text generator: it decided when to call tools, how to route those calls, and when to continue generation after tool results. My React frontend, however, connected over WebSocket. Getting those two protocols to talk — and to do it without buffering the whole response — turned out to be the most interesting engineering problem in this iteration.</p><p>In the baseline flow, every LLM call also re-sent the same 800-line system prompt plus accumulated conversation history, which made latency and token cost grow as conversations got longer.</p><p>But before getting into the solution, it’s worth understanding what I was replacing. This architecture did not start from scratch — it replaced a working but increasingly painful baseline script.</p><h3>Where This Started: The Baseline</h3><p>LangGraph already existed in this baseline, but the flow behaved mostly sequentially with hardcoded routing and no iterative tool loop. Every user request followed the same fixed pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC2WahYBY0BbJWEgHZdA3A.png" /></figure><p>Every Cortex call received the same payload shape: the full 800-line system prompt, the entire conversation history loaded from an external database, and the new user message — concatenated together on every single request. The third call was not an “agent” in the later Snowflake sense; it was another COMPLETE()-style function call that used the prompt and input parameters to determine identity-resolution accuracy or generate the final memcompare / lineage summary. This meant token cost scaled linearly with conversation length. A ten-turn conversation sent ten turns of history to the LLM on turn eleven, in addition to the 800-line prompt.</p><p>Conversation history was real — but it was managed manually. Each user turn was written to an external database after the response, then read back and injected into the next prompt. There was no framework managing this; it was application code threading history into the Cortex COMPLETE() call. In the FAQ branch, retrieval was done through the Cortex Search Service before the final answer was returned.</p><p>There was no loop. If the agent wanted to call two tools in sequence, it could not — the design allowed one shot per turn. No PII guard existed, so sensitive fields could reach the LLM unchecked. Manual prompt assembly and JSON response parsing were brittle, so any change in output shape could break the downstream flow silently. The Jira branch and the data lineage branch were both hardcoded in Python.</p><p>This was the starting point. Everything in the next section was built to address exactly these pain points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLsOJ0LjHdwoHqXDAmL3Gw.png" /></figure><p>The SSE parsing row is more important than it looks. In the baseline, a schema change in one event field produced empty results with no error — there was no structured dispatch to catch it. Here, unknown events are logged and skipped; known events are handled explicitly by name.</p><h3>Project Structure</h3><p>The codebase for this architecture spans three folders:</p><pre>core_agent_package/         # Core agent package (Python)<br>  config.py                 # Env-var config (PAT, account URL, DB, schema)<br>  cortex_client.py          # CortexClient — thread creation + SSE parsing<br>  graph.py                  # LangGraph state graph (build_graph)<br>  state.py                  # AgentState TypedDict with merge-reducer<br>  logs/                     # Structured logging helpers<br>  tools/<br>    pii_guard.py            # Regex pre-flight: SSN / DOB / source key patterns<br>    id_validation.py        # ID validation tool (calls internal REST API)<br>    member_compare.py       # Record comparison tool<br>    data_lineage.py         # Data issue mapping and data lineage tools<br>    faq.py                  # FAQ search (Cortex Search, server-side)<br>    jira_tools.py           # Ticket creation tool<br>    mock_data.py            # Realistic mock data for all 5 tools<br>    __init__.py             # execute_tool(name, args) dispatcher<br>backend/<br>  main.py                   # FastAPI app - /ws/chat WebSocket + streaming bridge<br>  requirements.txt          # fastapi, uvicorn, websockets, langgraph, requests<br>frontend/<br>  src/<br>    App.jsx                 # WebSocket lifecycle management<br>    ChatHistory.jsx         # Message display<br>    ChatInput.jsx           # User input<br>    EventStream.jsx         # Live SSE event display panel<br>  package.json              # React 18 + Vite 5<br>  vite.config.js</pre><p>The core agent package is imported directly by backend/main.py — no API layer between them. The frontend talks only to the FastAPI WebSocket; it has no direct Snowflake dependency.</p><h3>What This Looks Like at Runtime</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFjWpNDV-VAdNqlw9o_ang.png" /></figure><p>Before any LLM call, a regex PII guard blocks messages containing SSN, DOB, or internal key patterns. Nothing reaches Snowflake until that passes.</p><h3>The Cortex Agent Spec</h3><p>The agent is not a raw LLM call. It is a <strong>named, deployed Snowflake resource</strong> defined by a JSON spec and created via the Cortex Agent management API:</p><p>In this architecture, this spec is effectively the orchestrator contract: tool selection policy, routing behavior, response format policy, and server-side resource bindings are all declared here.</p><pre>POST /api/v2/databases/{DB}/schemas/{SCHEMA}/agents?createMode=orReplace</pre><p>The spec has six top-level keys:</p><pre>{<br>  &quot;name&quot;: &quot;IDENTITY_AGENT&quot;,<br>  &quot;models&quot;: { &quot;orchestration&quot;: &quot;auto&quot; },<br>  &quot;orchestration&quot;: { &quot;budget&quot;: { &quot;seconds&quot;: 300 } },<br>  &quot;instructions&quot;: {<br>    &quot;system&quot;: &quot;...&quot;,<br>    &quot;orchestration&quot;: &quot;...&quot;,<br>    &quot;response&quot;: &quot;...&quot;<br>    },<br>    &quot;tools&quot;: [&quot;...&quot;],<br>    &quot;tool_resources&quot;: { &quot;...&quot;: &quot;...&quot; }<br>}</pre><p><strong>models.orchestration: &quot;auto&quot;</strong> — Snowflake selects the model (Mistral-Large or Llama3-70b) based on availability. No hardcoded model name in the spec.</p><p><strong>orchestration.budget.seconds: 300</strong> — hard timeout on the agent&#39;s reasoning loop. If it hasn&#39;t finished within 5 minutes, the run is terminated.</p><p><strong>Three instruction blocks</strong> — each is an array of strings in the JSON file (for readability) that deploy_agent.py joins into a single string before sending to the API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQUB4vEDtUXlzuRiMX9vDw.png" /></figure><h3>Tool Definitions In The Spec</h3><p>The same spec also declares the tool catalog. In this codebase, the tools array includes six tool definitions with schema metadata and routing intent:</p><ul><li>validate IDs</li><li>compare records</li><li>data issue summary</li><li>data lineage</li><li>FAQ search (Cortex Search tool type)</li><li>create ticket</li></ul><p>Each tool definition includes:</p><ul><li>tool_spec.type (for example generic or cortex_search)</li><li>tool_spec.name</li><li>tool_spec.description</li><li>tool_spec.input_schema (JSON schema for arguments)</li></ul><p>type: &quot;generic&quot; is the custom-tool path. In practice, this is where you define tools whose input schema and behavior you control.</p><p>In this implementation, tool_resources then binds the FAQ search tool to a specific Cortex Search Service resource.</p><h3>Specific Routing Example: search_faq vs create_jira_ticket</h3><p>In this spec, search_faq is declared as type: &quot;cortex_search&quot; and has a matching tool_resources.search_faq entry:</p><pre>&quot;tool_resources&quot;: {<br>    &quot;search_faq&quot;: {<br>        &quot;name&quot;: &quot;SNOWFLAKE_LEARNING_DB.PUBLIC.IDENTITY_FAQ_SEARCH_SVC&quot;,<br>        &quot;title_column&quot;: &quot;QUESTION&quot;,<br>        &quot;id_column&quot;: &quot;FAQ_ID&quot;<br>    }<br>}</pre><p>That binding is what makes search_faq a Snowflake server-side tool in this flow. When the agent selects it, SSE shows response.tool_use with client_side_execute: false, then Snowflake executes the search internally and emits response.tool_result in the same run.</p><p>Now compare that with a generic tool like create_jira_ticket. It has a tool definition in tools, but no entry under tool_resources in this spec. In that case, Cortex emits response.tool_use with a tool_use_id and client_side_execute: true (or absent). The client must:</p><ol><li>Read the tool_use_id, tool name, and input from SSE.</li><li>Execute the tool locally in Python.</li><li>Send a tool_result block back with the same tool_use_id.</li></ol><p>So the practical split is:</p><ul><li>search_faq + tool_resources binding -&gt; executed server-side in Snowflake.</li><li>create_jira_ticket with no tool_resources binding in this spec -&gt; returned to client for local execution via tool_use_id round-trip.</li></ul><h3>How To Make A Custom Tool Server-Side</h3><p>If you want a custom tool to run server-side, the pattern is:</p><ol><li>Implement the logic in Snowflake (for example, via a stored procedure or UDF-backed service).</li><li>Expose it as a server-side-capable tool resource.</li><li>Bind that resource in tool_resources for the tool name.</li></ol><p>Then Cortex can execute it inside Snowflake and emit client_side_execute: false instead of returning it to the client.</p><p>Illustrative pattern example:</p><pre>{<br>    &quot;tools&quot;: [<br>        {<br>            &quot;tool_spec&quot;: {<br>                &quot;type&quot;: &quot;generic&quot;,<br>                &quot;name&quot;: &quot;get_data_lineage&quot;,<br>                &quot;description&quot;: &quot;Return lineage timeline for an identity key&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;id_list&quot;: {&quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}<br>                    },<br>                    &quot;required&quot;: [&quot;id_list&quot;]<br>                }<br>            }<br>        }<br>    ],<br>    &quot;tool_resources&quot;: {<br>        &quot;get_data_lineage&quot;: {<br>            &quot;name&quot;: &quot;SNOWFLAKE_LEARNING_DB.PUBLIC.IDENTITY_LINEAGE_SVC&quot;<br>        }<br>    }<br>}</pre><p>In this example, get_data_lineage is still a custom tool definition (type: &quot;generic&quot;), but once bound to a Snowflake-side resource it can be executed server-side by Cortex.</p><p>This is important for the historical baseline too: in the earlier architecture, all tool behavior and selection policy was already encoded in the large prompt/spec-driven flow, then executed through hardcoded routing. The later architecture made that orchestration loop explicit and stream-aware, but the tool definitions themselves were already a first-class part of the design.</p><p>The agent never sees raw demographic data directly — its system prompt instructs it to treat certain key types as restricted and to refer to source record identifiers as “one record” without surfacing actual values. Those rules live in the spec, not in application code.</p><p>One non-obvious deployment detail: Snowflake’s API expects instruction blocks as <strong>single strings</strong>. The deploy_agent.py script joins the array with &quot;\n&quot;.join(...) before the POST — so the JSON file stays human-readable but the wire format is a flat string.</p><h3>Layer 1 — Parsing the Cortex SSE Stream</h3><p>The CortexClient._execute_run() method in cortex_client.py does all the heavy lifting. It opens a streaming requests.post and iterates r.iter_lines() synchronously:</p><pre>with requests.post(<br>    url, headers=self.headers, json=payload,<br>    stream=True, timeout=(10, 300),<br>) as r:<br>    r.raise_for_status()<br><br>    for raw_line in r.iter_lines():<br>        if not raw_line:<br>            continue<br>        line = raw_line.decode(&quot;utf-8&quot;).strip()<br><br>        if line.startswith(&quot;event:&quot;):<br>            current_event = line[6:].strip()<br>            continue<br><br>        if not line.startswith(&quot;data:&quot;):<br>            continue<br><br>        json_str = line[5:].strip()<br>        if json_str == &quot;[DONE]&quot;:<br>            break<br><br>        data = json.loads(json_str)<br>        # ... dispatch on current_event</pre><p>Each SSE message is a pair of lines: an event: header followed by a data: line containing JSON. The parser tracks current_event across lines, then dispatches:</p><pre>if current_event == &quot;response.tool_use&quot;:<br>    # Only collect tools that must run locally<br>    if data.get(&quot;client_side_execute&quot;, True):<br>        result.tool_calls.append({<br>            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>        })<br><br>elif current_event == &quot;response.text.delta&quot;:<br>    result.text_chunks.append(data.get(&quot;text&quot;, &quot;&quot;))<br><br>elif current_event == &quot;response.tool_result&quot;:<br>    # Server-side tool (e.g. Cortex Search) — Snowflake handled it<br>    # Log only; no client action needed<br>    pass</pre><p>The client_side_execute field is the key routing signal. Snowflake sets it False for server-side tools like search_faq (Cortex Search) — those are executed inside Snowflake&#39;s infrastructure and their results are folded back into the LLM context automatically. When it is True (or absent), the tool must be executed by my Python process and the result sent back in a second :run call.</p><h3>Server-Side Tool Execution Path</h3><p>This is the exact execution behavior when Cortex decides a tool is server-side:</p><ol><li>Cortex emits response.tool_use with client_side_execute: false.</li><li>My client does <strong>not</strong> dispatch that tool to local Python.</li><li>Snowflake executes the tool internally (for example, FAQ retrieval via Cortex Search Service).</li><li>Cortex emits response.tool_result for that server-side execution.</li><li>The same run continues and streams response.text.delta / response.text with the tool output already incorporated.</li></ol><p>So if a tool is registered as server-side, execution stays inside Snowflake end-to-end. Local Python only participates when client_side_execute is true.</p><p>The same pattern applies to other Snowflake-managed server-side resources (for example analyst or stored-procedure-backed capabilities) when they are exposed to the agent as server-side tools.</p><h3>Layer 2 — Bridging to WebSocket in Real Time</h3><p>The synchronous iter_lines() loop runs in a thread. The FastAPI WebSocket endpoint is async. I needed to pass events from the blocking I/O thread to the async event loop without buffering.</p><p>Concrete code references in this implementation:</p><ul><li>backend/main.py -&gt; run_agent_with_streaming(...)</li><li>backend/main.py -&gt; streaming_execute_run(...) (temporary monkey-patched _execute_run)</li><li>backend/main.py -&gt; stream_events(...) (async queue consumer)</li></ul><pre># backend main.py snippet<br>&quot;&quot;&quot;<br>FastAPI backend with WebSocket support for real-time SSE streaming<br>from the Cortex Agent.<br><br>Features:<br>- Real-time SSE event streaming (tool_use, text_delta, tool_result, metadata)<br>- Session management with LangGraph checkpointer<br>- Multi-turn conversation support<br>- Proper error handling and connection management<br>&quot;&quot;&quot;<br><br>import sys<br>import os<br>import json<br>import uuid<br>import asyncio<br>from typing import Dict<br>from fastapi import FastAPI, WebSocket, WebSocketDisconnect<br>from fastapi.middleware.cors import CORSMiddleware<br>from langgraph.checkpoint.memory import MemorySaver<br><br># Add cortex_agent to sys.path for import<br>sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), &#39;..&#39;)))<br><br>from cortex_agent.config import PAT, ACCOUNT_BASE_URL, DB, SCHEMA, AGENT_NAME<br>from cortex_agent.cortex_client import CortexClient<br>from cortex_agent.graph import build_graph<br>from cortex_agent.state import AgentState<br><br>app = FastAPI(title=&quot;Cortex Agent API&quot;)<br><br># Allow CORS for local frontend dev<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br># Global instances - initialized once at startup<br>checkpointer = MemorySaver()<br>compiled_graph = build_graph(checkpointer=checkpointer)<br>cortex_client = CortexClient(ACCOUNT_BASE_URL, PAT, DB, SCHEMA, AGENT_NAME)<br><br># Active WebSocket connections with session tracking<br>active_connections: Dict[str, WebSocket] = {}<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    &quot;&quot;&quot;Initialize the agent on startup.&quot;&quot;&quot;<br>    print(&quot;=&quot; * 60)<br>    print(&quot;🚀 Cortex Agent Backend Starting...&quot;)<br>    print(f&quot;   Account: {ACCOUNT_BASE_URL}&quot;)<br>    print(f&quot;   Database: {DB}.{SCHEMA}&quot;)<br>    print(f&quot;   Agent: {AGENT_NAME}&quot;)<br>    print(&quot;=&quot; * 60)<br><br><br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Health check endpoint.&quot;&quot;&quot;<br>    return {&quot;status&quot;: &quot;healthy&quot;, &quot;agent&quot;: AGENT_NAME}<br><br><br>@app.websocket(&quot;/ws/chat&quot;) # WebSocket endpoint for front end interaction <br>async def websocket_endpoint(websocket: WebSocket):<br>    &quot;&quot;&quot;<br>    WebSocket endpoint for real-time chat with SSE event streaming.<br>    <br>    Message format from client:<br>        {&quot;message&quot;: &quot;user message text&quot;, &quot;session_id&quot;: &quot;optional-session-id&quot;}<br>    <br>    Response format to client:<br>        {&quot;type&quot;: &quot;event&quot;, &quot;event&quot;: &quot;tool_use&quot;, &quot;data&quot;: {...}}<br>        {&quot;type&quot;: &quot;event&quot;, &quot;event&quot;: &quot;text_delta&quot;, &quot;data&quot;: {&quot;text&quot;: &quot;...&quot;}}<br>        {&quot;type&quot;: &quot;final&quot;, &quot;response&quot;: &quot;final text&quot;, &quot;state&quot;: {...}}<br>        {&quot;type&quot;: &quot;error&quot;, &quot;error&quot;: &quot;error message&quot;}<br>    &quot;&quot;&quot;<br>    await websocket.accept()<br>    session_id = str(uuid.uuid4())<br>    active_connections[session_id] = websocket<br>    <br>    print(f&quot;✅ WebSocket connected | session={session_id}&quot;)<br>    <br>    try:<br>        # Send connection confirmation<br>        await websocket.send_json({<br>            &quot;type&quot;: &quot;connected&quot;,<br>            &quot;session_id&quot;: session_id,<br>            &quot;message&quot;: &quot;Connected to Cortex Agent&quot;<br>        })<br>        <br>        while True:<br>            # Receive message from client<br>            data = await websocket.receive_text() # recewive from frontend<br>            <br>            try:<br>                payload = json.loads(data)<br>                user_message = payload.get(&quot;message&quot;, data) #retrieve message from frontend<br>                client_session_id = payload.get(&quot;session_id&quot;, session_id) # retrieve session id from frontend<br>            except json.JSONDecodeError:<br>                user_message = data<br>                client_session_id = session_id<br>            <br>            print(f&quot;📨 Received message | session={client_session_id} | msg=&#39;{user_message[:50]}...&#39;&quot;)<br>            <br>            # Send acknowledgment<br>            await websocket.send_json({<br>                &quot;type&quot;: &quot;processing&quot;,<br>                &quot;message&quot;: &quot;Processing your request...&quot;<br>            })<br>            <br>            try:  # calling the cortex agent with streaming response handling<br>                # Run the agent with streaming<br>                await run_agent_with_streaming(<br>                    websocket=websocket,<br>                    user_message=user_message,<br>                    session_id=client_session_id<br>                )<br>                <br>            except Exception as e:<br>                error_msg = f&quot;Agent error: {str(e)}&quot;<br>                print(f&quot;❌ Error | session={client_session_id} | {error_msg}&quot;)<br>                await websocket.send_json({<br>                    &quot;type&quot;: &quot;error&quot;,<br>                    &quot;error&quot;: error_msg<br>                })<br>    <br>    except WebSocketDisconnect:<br>        print(f&quot;🔌 WebSocket disconnected | session={session_id}&quot;)<br>        if session_id in active_connections:<br>            del active_connections[session_id]<br>    <br>    except Exception as e:<br>        print(f&quot;❌ WebSocket error | session={session_id} | {str(e)}&quot;)<br>        if session_id in active_connections:<br>            del active_connections[session_id]<br><br><br>async def run_agent_with_streaming(<br>    websocket: WebSocket,<br>    user_message: str,<br>    session_id: str<br>):<br>    &quot;&quot;&quot;<br>    Run the cortex agent and stream SSE events to the WebSocket client in real-time.<br>    <br>    This function intercepts the Cortex Agent&#39;s SSE stream and forwards events<br>    to the WebSocket client as they arrive using a queue.<br>    &quot;&quot;&quot;<br>    <br>    # Prepare initial state<br>    initial_state = {<br>        &quot;user_message&quot;: user_message,<br>        &quot;user_id&quot;: &quot;web_user&quot;,<br>        &quot;chat_id&quot;: 0,<br>    }<br>    <br>    # Config with session for checkpointer<br>    config = {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: session_id,<br>            &quot;client&quot;: cortex_client<br>        }<br>    }<br>    <br>    # Create a queue for real-time event streaming<br>    event_queue = asyncio.Queue()<br>    <br>    # We&#39;ll stream events by patching the cortex_client temporarily<br>    original_execute_run = cortex_client._execute_run<br>    <br>    def streaming_execute_run(payload: dict):<br>        &quot;&quot;&quot;Wrapper that captures SSE events by calling cortex agent api and puts them in queue (synchronous).&quot;&quot;&quot;<br>        from cortex_agent.cortex_client import CortexRunResult<br>        import requests<br>        <br>        url = (<br>            f&quot;{cortex_client.base_url}/api/v2/databases/{cortex_client.db}&quot;<br>            f&quot;/schemas/{cortex_client.schema}/agents/{cortex_client.agent}:run&quot;<br>        )<br>        result = CortexRunResult()<br>        current_event = None<br>        <br>        with requests.post(<br>            url, headers=cortex_client.headers, json=payload,<br>            stream=True, timeout=(10, 300),<br>        ) as r:<br>            if not r.ok:<br>                r.raise_for_status()<br>            <br>            for raw_line in r.iter_lines():<br>                if not raw_line:<br>                    continue<br>                line = raw_line.decode(&quot;utf-8&quot;).strip()<br>                <br>                if line.startswith(&quot;event:&quot;):<br>                    current_event = line[6:].strip()<br>                    continue<br>                <br>                if not line.startswith(&quot;data:&quot;):<br>                    continue<br>                <br>                json_str = line[5:].strip()<br>                if json_str == &quot;[DONE]&quot;:<br>                    break<br>                <br>                try:<br>                    data = json.loads(json_str)<br>                except json.JSONDecodeError:<br>                    continue<br>                <br>                result.raw_events.append({&quot;event&quot;: current_event, &quot;data&quot;: data})<br>                <br>                # Put event in queue for real-time streaming (thread-safe)<br>                event_queue.put_nowait({<br>                    &quot;type&quot;: &quot;sse_event&quot;,<br>                    &quot;event&quot;: current_event,<br>                    &quot;data&quot;: data<br>                })<br>                <br>                # Process event for result object<br>                if current_event == &quot;metadata&quot; and &quot;metadata&quot; in data:<br>                    meta = data[&quot;metadata&quot;]<br>                    if meta.get(&quot;role&quot;) == &quot;assistant&quot;:<br>                        result.parent_message_id = meta.get(&quot;message_id&quot;, result.parent_message_id)<br>                <br>                elif current_event == &quot;response.tool_use&quot;:<br>                    if data.get(&quot;client_side_execute&quot;, True):<br>                        tool_call = {<br>                            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>                            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>                            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>                        }<br>                        result.tool_calls.append(tool_call)<br>                <br>                elif current_event == &quot;response.text.delta&quot;:<br>                    chunk = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if chunk:<br>                        result.text_chunks.append(chunk)<br>                <br>                elif current_event == &quot;response.text&quot;:<br>                    text = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if text:<br>                        result.final_text = text<br>                <br>                elif current_event == &quot;response&quot;:<br>                    result.final_text = cortex_client._extract_text(data)<br>                <br>                elif current_event == &quot;error&quot;:<br>                    err_msg = data.get(&quot;message&quot;, &quot;unknown error&quot;)<br>                    err_code = data.get(&quot;code&quot;, &quot;&quot;)<br>                    result.final_text = f&quot;[Agent Error {err_code}]: {err_msg}&quot;<br>        <br>        return result<br>    <br>    # Temporarily replace the method<br>    cortex_client._execute_run = streaming_execute_run<br>    <br>    # Task to consume events from queue and send to WebSocket<br>    async def stream_events():<br>        &quot;&quot;&quot;Continuously read from queue and send events to WebSocket.&quot;&quot;&quot;<br>        while True:<br>            try:<br>                event = await asyncio.wait_for(event_queue.get(), timeout=0.1)<br>                await websocket.send_json(event)<br>            except asyncio.TimeoutError:<br>                # Check if graph is done<br>                if not graph_task or graph_task.done():<br>                    # Drain any remaining events<br>                    while not event_queue.empty():<br>                        event = event_queue.get_nowait()<br>                        await websocket.send_json(event)<br>                    break<br>            except Exception as e:<br>                print(f&quot;Error streaming event: {e}&quot;)<br>                break<br>    <br>    try:<br>        # Start the graph execution in a thread<br>        graph_task = asyncio.create_task(<br>            asyncio.to_thread(<br>                compiled_graph.invoke,<br>                initial_state,<br>                config<br>            )<br>        )<br>        <br>        # Start streaming events concurrently<br>        stream_task = asyncio.create_task(stream_events())<br>        <br>        # Wait for graph to complete<br>        final_state = await graph_task<br>        <br>        # Wait for streaming to finish<br>        await stream_task<br>        <br>        # Send final response<br>        await websocket.send_json({<br>            &quot;type&quot;: &quot;final&quot;,<br>            &quot;response&quot;: final_state.get(&quot;final_response&quot;, &quot;(no response)&quot;),<br>            &quot;state&quot;: {<br>                &quot;thread_id&quot;: final_state.get(&quot;thread_id&quot;),<br>                &quot;parent_message_id&quot;: final_state.get(&quot;parent_message_id&quot;),<br>                &quot;pii_blocked&quot;: final_state.get(&quot;pii_blocked&quot;, False),<br>                &quot;node_outputs&quot;: final_state.get(&quot;node_outputs&quot;, {}),<br>            }<br>        })<br>        <br>        print(f&quot;✅ Agent completed | session={session_id} | response_len={len(final_state.get(&#39;final_response&#39;, &#39;&#39;))}&quot;)<br>        <br>    finally:<br>        # Restore original method<br>        cortex_client._execute_run = original_execute_run<br><br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>The solution: an asyncio.Queue as the bridge, with queue.put_nowait() called from the synchronous side and asyncio.wait_for(queue.get(), timeout=0.1) on the async side.</p><p>In backend/main.py, the streaming wrapper monkey-patches cortex_client._execute_run for the duration of the request:</p><p>The async consumer drains the queue and forwards events to the browser:</p><p>The graph runs concurrently via asyncio.to_thread:</p><p>After both tasks stream_task and graph_task finish, a {&quot;type&quot;: &quot;final&quot;, ...} message carries the complete response and state back to the browser. The original _execute_run is restored in the finally block.</p><h3>What Lives In cortex_agent</h3><p>The WebSocket bridge in backend/main.py is only the transport layer. The actual agent behavior lives in cortex_agent, and that is what makes the architecture complete:</p><ul><li>cortex_agent/cortex_client.py creates the Snowflake thread, sends :run requests, parses SSE events, and separates client-side tool calls from server-side ones.</li></ul><pre># cortex_client.py snippet<br>&quot;&quot;&quot;<br>Snowflake Cortex Agent REST API client with SSE stream parsing.<br><br>Reused from cortex_agent_client_side — handles thread creation,<br>agent :run calls, and parsing tool_use / text events.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>import json<br>from dataclasses import dataclass, field<br><br>import requests<br><br>from .logs import get_logger<br><br>logger = get_logger(&quot;cortex-client&quot;)<br><br><br>@dataclass<br>class CortexRunResult:<br>    &quot;&quot;&quot;Parsed result from a single Cortex Agent :run SSE stream.&quot;&quot;&quot;<br>    tool_calls: list[dict] = field(default_factory=list)<br>    text_chunks: list[str] = field(default_factory=list)<br>    final_text: str = &quot;&quot;<br>    parent_message_id: int = 0<br>    raw_events: list[dict] = field(default_factory=list)<br><br>    @property<br>    def has_tool_calls(self) -&gt; bool:<br>        return len(self.tool_calls) &gt; 0<br><br>    @property<br>    def assembled_text(self) -&gt; str:<br>        return self.final_text or &quot;&quot;.join(self.text_chunks).strip()<br><br><br>class CortexClient:<br>    &quot;&quot;&quot;Client for the Snowflake Cortex Agent REST API.&quot;&quot;&quot;<br><br>    def __init__(self, base_url: str, pat: str, db: str, schema: str, agent: str):<br>        logger.info(&quot;Initializing CortexClient constructor| base_url=%s db=%s schema=%s agent=%s&quot;,<br>                    base_url, db, schema, agent)<br>        self.base_url = base_url.rstrip(&quot;/&quot;)<br>        self.db = db<br>        self.schema = schema<br>        self.agent = agent<br>        self.headers = {<br>            &quot;Authorization&quot;: f&quot;Bearer {pat.strip()}&quot;,<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            &quot;Accept&quot;: &quot;application/json&quot;,<br>        }<br><br>    def create_thread(self) -&gt; tuple[str, int]:<br>        &quot;&quot;&quot;Create a Cortex thread. Returns (thread_id, parent_message_id).&quot;&quot;&quot;<br>        logger.info(&quot;inside create_thread ..Creating Cortex thread...&quot;)<br>        url = f&quot;{self.base_url}/api/v2/cortex/threads&quot;<br>        r = requests.post(<br>            url,<br>            headers=self.headers,<br>            json={&quot;origin_application&quot;: &quot;langgraph&quot;},<br>            timeout=30,<br>        )<br>        if not r.ok:<br>            logger.error(&quot;create_thread failed | status=%s body=%s&quot;, r.status_code, r.text[:500])<br>            r.raise_for_status()<br>        data = r.json()<br>        thread_id = data.get(&quot;thread_id&quot;) or data.get(&quot;threadId&quot;) or data.get(&quot;id&quot;)<br>        parent_id = data.get(&quot;parent_message_id&quot;) or data.get(&quot;parentMessageId&quot;) or data.get(&quot;message_id&quot;, 0)<br>        logger.info(&quot;Thread created | thread_id=%s parent_message_id=%s&quot;, thread_id, parent_id)<br>        return thread_id, parent_id<br><br>    def run_agent(self, thread_id: str, parent_message_id: int, user_message: str) -&gt; CortexRunResult:<br>        &quot;&quot;&quot;Send a user message to the agent and parse the SSE stream for results.&quot;&quot;&quot;<br>        logger.info(&quot;inside run_agent ..Running agent with user message...&quot;)<br>        payload = {<br>            &quot;thread_id&quot;: thread_id,<br>            &quot;parent_message_id&quot;: parent_message_id,<br>            &quot;stream&quot;: True,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: user_message}]}<br>            ],<br>        }<br>        logger.info(&quot;Sending user message | thread=%s parent=%s&quot;, thread_id, parent_message_id)<br>        return self._execute_run(payload)<br><br>    def run_agent_with_tool_results(<br>        self, thread_id: str, parent_message_id: int, tool_results: list[dict]<br>    ) -&gt; CortexRunResult:<br>        &quot;&quot;&quot;Send tool results back to the agent and parse the SSE stream.&quot;&quot;&quot;<br>        logger.info(&quot;Sending tool results | thread=%s parent=%s count=%d&quot;,<br>                     thread_id, parent_message_id, len(tool_results))<br><br>        # Build content items following Snowflake&#39;s documented tool_result schema:<br>        #   {<br>        #     &quot;type&quot;: &quot;tool_result&quot;,<br>        #     &quot;tool_result&quot;: {<br>        #       &quot;tool_use_id&quot;: &quot;...&quot;,<br>        #       &quot;name&quot;: &quot;&lt;tool name&gt;&quot;,<br>        #       &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: {...}}],<br>        #       &quot;status&quot;: &quot;success&quot; | &quot;error&quot;<br>        #     }<br>        #   }<br>        content_parts = []<br>        for tr in tool_results:<br>            raw = tr[&quot;content&quot;]<br>            # Try to parse as JSON so the agent gets structured data<br>            try:<br>                parsed = json.loads(raw) if isinstance(raw, str) else raw<br>            except (json.JSONDecodeError, TypeError):<br>                parsed = raw<br><br>            # Snowflake requires `&quot;json&quot;` to be an object `{}`, never a<br>            # string, number, or array.  Wrap any non-dict value.<br>            if isinstance(parsed, dict):<br>                json_value = parsed<br>            elif isinstance(parsed, list):<br>                json_value = {&quot;result&quot;: parsed}<br>            else:<br>                json_value = {&quot;result&quot;: parsed}<br><br>            tool_result_obj: dict = {<br>                &quot;tool_use_id&quot;: tr[&quot;tool_use_id&quot;],<br>                &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: json_value}],<br>                &quot;status&quot;: &quot;error&quot; if tr.get(&quot;is_error&quot;) else &quot;success&quot;,<br>            }<br><br>            # Include tool name when available (from graph.execute_tools)<br>            if tr.get(&quot;tool_name&quot;):<br>                tool_result_obj[&quot;name&quot;] = tr[&quot;tool_name&quot;]<br><br>            content_parts.append({<br>                &quot;type&quot;: &quot;tool_result&quot;,<br>                &quot;tool_result&quot;: tool_result_obj,<br>            })<br><br>        payload = {<br>            &quot;thread_id&quot;: thread_id,<br>            &quot;parent_message_id&quot;: parent_message_id,<br>            # Use the same key as run_agent (streaming SSE)<br>            &quot;stream&quot;: True,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: content_parts},<br>            ],<br>        }<br>        logger.info(&quot;Sending %d tool result(s) | thread=%s parent=%s&quot;,<br>                     len(tool_results), thread_id, parent_message_id)<br>        logger.info(&quot;Tool result payload | %s&quot;, json.dumps(payload, default=str)[:2000])<br>        return self._execute_run(payload)<br>    def _execute_run(self, payload: dict) -&gt; CortexRunResult:<br>        &quot;&quot;&quot; Internal method to execute an agent run with the given payload and parse the SSE stream for results.   &quot;&quot;&quot;<br>        logger.info(&quot;inside _execute_run ..Executing agent run with payload...&quot;)<br>        url = (<br>            f&quot;{self.base_url}/api/v2/databases/{self.db}&quot;<br>            f&quot;/schemas/{self.schema}/agents/{self.agent}:run&quot;<br>        )<br>        result = CortexRunResult()<br>        current_event: str | None = None<br><br>        with requests.post(<br>            url, headers=self.headers, json=payload,<br>            stream=True, timeout=(10, 300),<br>        ) as r:<br>            logger.info(&quot;Agent :run response | status=%s&quot;, r.status_code)<br>            if not r.ok:<br>                body = r.text[:500] if r.text else &quot;(empty)&quot;<br>                logger.error(&quot;Agent :run failed | status=%s body=%s&quot;, r.status_code, body)<br>                logger.error(&quot;Agent :run payload sent | %s&quot;, json.dumps(payload, default=str)[:1000])<br>            r.raise_for_status()<br><br>            for raw_line in r.iter_lines():<br>                if not raw_line:<br>                    continue<br>                line = raw_line.decode(&quot;utf-8&quot;).strip()<br><br>                if line.startswith(&quot;event:&quot;):<br>                    current_event = line[6:].strip()<br>                    logger.info(&quot;SSE event | %s&quot;, current_event)<br><br>                    continue<br><br>                if not line.startswith(&quot;data:&quot;):<br>                    continue<br><br>                json_str = line[5:].strip()<br>                if json_str == &quot;[DONE]&quot;:<br>                    logger.info(&quot;SSE stream complete&quot;)<br>                    break<br><br>                try:<br>                    data = json.loads(json_str)<br>                except json.JSONDecodeError:<br>                    logger.warning(&quot;Skipping non-JSON SSE data | %s&quot;, json_str)<br>                    continue<br><br>                result.raw_events.append({&quot;event&quot;: current_event, &quot;data&quot;: data})<br>                logger.info(&quot;SSE data | event=%s keys=%s&quot;, current_event, list(data.keys()) if isinstance(data, dict) else type(data).__name__)<br>                if current_event == &quot;metadata&quot; and &quot;metadata&quot; in data:<br>                    meta = data[&quot;metadata&quot;]<br>                    if meta.get(&quot;role&quot;) == &quot;assistant&quot;:<br>                        result.parent_message_id = meta.get(&quot;message_id&quot;, result.parent_message_id)<br>                        logger.info(&quot;Assistant message_id captured | %s&quot;, result.parent_message_id)<br><br>                elif current_event == &quot;response.tool_use&quot;:<br>                    # Only collect client-side tools for local execution.<br>                    # Server-side tools (cortex_search, cortex_analyst) have<br>                    # client_side_execute=False and are handled by Snowflake.<br>                    if data.get(&quot;client_side_execute&quot;, True):<br>                        tool_call = {<br>                            &quot;tool_use_id&quot;: data.get(&quot;tool_use_id&quot;, &quot;&quot;),<br>                            &quot;name&quot;: data.get(&quot;name&quot;, &quot;&quot;),<br>                            &quot;input&quot;: data.get(&quot;input&quot;, {}),<br>                        }<br>                        result.tool_calls.append(tool_call)<br>                        logger.info(&quot;Tool call (client-side) | name=%s args=%s&quot;,<br>                                    tool_call[&quot;name&quot;], tool_call[&quot;input&quot;])<br>                    else:<br>                        logger.info(&quot;Tool call (server-side, skipping) | name=%s&quot;,<br>                                    data.get(&quot;name&quot;, &quot;unknown&quot;))<br><br>                elif current_event == &quot;response.tool_result&quot;:<br>                    # Server-side tool (e.g. Cortex Search) — executed inside<br>                    # Snowflake. We log it but don&#39;t need to act; the agent<br>                    # continues processing and will produce final text.<br>                    tool_name = data.get(&quot;name&quot;, &quot;unknown&quot;)<br>                    logger.info(&quot;Tool result (server-side) | name=%s&quot;, tool_name)<br><br>                elif current_event == &quot;response.text.delta&quot;:<br>                    chunk = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if chunk:<br>                        result.text_chunks.append(chunk)<br><br>                elif current_event == &quot;response.text&quot;:<br>                    text = data.get(&quot;text&quot;, &quot;&quot;)<br>                    if text:<br>                        result.final_text = text<br><br>                elif current_event == &quot;response&quot;:<br>                    result.final_text = self._extract_text(data)<br>                <br>                elif current_event == &quot;error&quot;:<br>                    err_msg = data.get(&quot;message&quot;, &quot;unknown error&quot;)<br>                    err_code = data.get(&quot;code&quot;, &quot;&quot;)<br>                    logger.error(&quot;SSE error event | code=%s message=%s&quot;, err_code, err_msg)<br>                    result.final_text = f&quot;[Agent Error {err_code}]: {err_msg}&quot;<br><br>        logger.info(&quot;Run result | tool_calls=%d text_len=%d&quot;,<br>                     len(result.tool_calls), len(result.assembled_text))<br>        return result<br><br>    @staticmethod<br>    def _extract_text(data: dict) -&gt; str:<br>        content = data.get(&quot;content&quot;, [])<br>        if not isinstance(content, list):<br>            return &quot;&quot;<br>        parts = []<br>        for item in content:<br>            if isinstance(item, dict) and item.get(&quot;type&quot;) == &quot;text&quot;:<br>                t = item.get(&quot;text&quot;, &quot;&quot;)<br>                if t:<br>                    parts.append(t)<br>        return &quot;\n&quot;.join(parts).strip()</pre><ul><li>cortex_agent/graph.py defines the LangGraph loop: pii_check -&gt; init_thread -&gt; call_agent -&gt; execute_tools -&gt; call_agent until no tools remain.</li></ul><pre>cortex_agent/graph.py snippet<br>&quot;&quot;&quot;<br>LangGraph graph for Cortex Agent — client-side tool execution.<br><br>Architecture:<br>    ┌───────────┐<br>    │   START    │<br>    └─────┬─────┘<br>          │<br>    ┌─────▼─────┐   PII detected<br>    │  pii_check │──────────────────────► END  (block message)<br>    └─────┬─────┘<br>          │ clean<br>    ┌─────▼──────┐   already has thread_id?<br>    │ init_thread │   ──► skip creation<br>    └─────┬──────┘<br>          │<br>    ┌─────▼──────┐◄──────────────────────┐<br>    │ call_agent  │                       │<br>    └─────┬──────┘                       │<br>          │                              │<br>    ┌─────▼──────┐                       │<br>    │   route     │──► done ──► END      │<br>    └─────┬──────┘                       │<br>          │ tools                        │<br>    ┌─────▼──────────┐                   │<br>    │ execute_tools   │──────────────────┘<br>    └────────────────┘        (loop)<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.types import RunnableConfig<br><br>from .state import AgentState<br>from .cortex_client import CortexClient, CortexRunResult<br>from .tools import execute_tool<br>from .tools.pii_guard import detect_sensitive_patterns, build_pii_block_response<br>from .config import MAX_TOOL_ITERATIONS<br>from .logs import get_logger<br><br>logger = get_logger(&quot;graph&quot;)<br><br><br># ================================================================== #<br>#  Node: pii_check<br># ================================================================== #<br><br>def pii_check(state: AgentState) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Pre-check the user message for PII / sensitive patterns.<br>    If detected, set pii_blocked=True and a block response.<br>    &quot;&quot;&quot;<br>    msg = state.get(&quot;user_message&quot;, &quot;&quot;)<br>    is_sensitive, patterns = detect_sensitive_patterns(msg)<br><br>    if is_sensitive:<br>        logger.warning(&quot;PII guard blocked request | patterns=%s&quot;, patterns)<br>        return {<br>            &quot;pii_blocked&quot;: True,<br>            &quot;final_response&quot;: build_pii_block_response(patterns),<br>        }<br><br>    return {&quot;pii_blocked&quot;: False}<br><br><br>def pii_route(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;Route after PII check: block or continue.&quot;&quot;&quot;<br>    if state.get(&quot;pii_blocked&quot;):<br>        return &quot;blocked&quot;<br>    return &quot;clean&quot;<br><br><br># ================================================================== #<br>#  Node: init_thread<br># ================================================================== #<br><br>def init_thread(state: AgentState, config: RunnableConfig) -&gt; dict:<br>    &quot;&quot;&quot;Create a Cortex thread if one doesn&#39;t exist yet.&quot;&quot;&quot;<br>    if state.get(&quot;thread_id&quot;):<br>        logger.info(&quot;Reusing existing thread | thread_id=%s&quot;, state[&quot;thread_id&quot;])<br>        return {}<br><br>    client: CortexClient = config[&quot;configurable&quot;][&quot;client&quot;]<br>    thread_id, parent_id = client.create_thread()<br>    return {<br>        &quot;thread_id&quot;: thread_id,<br>        &quot;parent_message_id&quot;: parent_id,<br>        &quot;iteration&quot;: 0,<br>    }<br><br><br># ================================================================== #<br>#  Node: call_agent<br># ================================================================== #<br><br>def call_agent(state: AgentState, config: RunnableConfig) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Send a user message or tool results to the Cortex Agent.<br>    Parses the SSE stream and captures tool calls or final text.<br>    &quot;&quot;&quot;<br>    client: CortexClient = config[&quot;configurable&quot;][&quot;client&quot;]<br>    tool_results = state.get(&quot;tool_results&quot;, [])<br><br>    if tool_results:<br>        result: CortexRunResult = client.run_agent_with_tool_results(<br>            state[&quot;thread_id&quot;],<br>            state[&quot;parent_message_id&quot;],<br>            tool_results,<br>        )<br>    else:<br>        result = client.run_agent(<br>            state[&quot;thread_id&quot;],<br>            state[&quot;parent_message_id&quot;],<br>            state[&quot;user_message&quot;],<br>        )<br><br>    updates: dict = {<br>        &quot;pending_tool_calls&quot;: result.tool_calls,<br>        &quot;tool_results&quot;: [],<br>        &quot;iteration&quot;: state.get(&quot;iteration&quot;, 0) + 1,<br>    }<br><br>    if result.parent_message_id:<br>        updates[&quot;parent_message_id&quot;] = result.parent_message_id<br><br>    if not result.has_tool_calls:<br>        updates[&quot;final_response&quot;] = result.assembled_text<br>        logger.info(&quot;Agent produced final text (%d chars)&quot;, len(result.assembled_text))<br>    else:<br>        logger.info(&quot;Agent requested %d tool call(s)&quot;, len(result.tool_calls))<br><br>    return updates<br><br><br># ================================================================== #<br>#  Node: execute_tools<br># ================================================================== #<br><br>def execute_tools(state: AgentState) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Execute all pending client-side tool calls and prepare results<br>    for the next call_agent invocation.<br>    &quot;&quot;&quot;<br>    pending = state.get(&quot;pending_tool_calls&quot;, [])<br>    results = []<br>    node_outputs = dict(state.get(&quot;node_outputs&quot;) or {})<br><br>    for tc in pending:<br>        name = tc[&quot;name&quot;]<br>        args = tc.get(&quot;input&quot;, {})<br>        tool_use_id = tc[&quot;tool_use_id&quot;]<br><br>        logger.info(&quot;Executing tool | name=%s id=%s&quot;, name, tool_use_id)<br>        content, is_error = execute_tool(name, args)<br><br>        results.append({<br>            &quot;tool_use_id&quot;: tool_use_id,<br>            &quot;tool_name&quot;: name,<br>            &quot;content&quot;: content,<br>            &quot;is_error&quot;: is_error,<br>        })<br><br>        # Track per-issue output for Jira / summary<br>        id_list = args.get(&quot;id_list&quot;, [])<br>        if id_list and name == &quot;create_jira_ticket&quot;:<br>            key = &quot;|&quot;.join(str(m) for m in id_list)<br>            entry = node_outputs.get(key, {})<br>            if &quot;Created successfully&quot; in content or &quot;Ticket ID:&quot; in content:<br>                # Extract ticket ID from content<br>                for line in content.splitlines():<br>                    if line.startswith(&quot;Ticket ID:&quot;):<br>                        entry[&quot;jira_no&quot;] = line.split(&quot;:&quot;, 1)[1].strip()<br>                        break<br>            entry[&quot;agent_name&quot;] = &quot;create_jira_ticket&quot;<br>            entry[&quot;id_list&quot;] = id_list<br>            node_outputs[key] = entry<br><br>    logger.info(<br>        &quot;Tools executed | count=%d errors=%d&quot;,<br>        len(results),<br>        sum(1 for r in results if r[&quot;is_error&quot;]),<br>    )<br><br>    return {<br>        &quot;tool_results&quot;: results,<br>        &quot;pending_tool_calls&quot;: [],<br>        &quot;node_outputs&quot;: node_outputs,<br>    }<br><br><br># ================================================================== #<br>#  Conditional Edge: route_decision<br># ================================================================== #<br><br>def route_decision(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;<br>    After call_agent, decide whether to execute tools or finish.<br>    &quot;&quot;&quot;<br>    if state.get(&quot;iteration&quot;, 0) &gt;= MAX_TOOL_ITERATIONS:<br>        logger.warning(&quot;Max tool iterations (%d) reached — stopping.&quot;, MAX_TOOL_ITERATIONS)<br>        return &quot;done&quot;<br><br>    if state.get(&quot;pending_tool_calls&quot;):<br>        return &quot;execute_tools&quot;<br><br>    return &quot;done&quot;<br><br><br># ================================================================== #<br>#  Build &amp; Compile<br># ================================================================== #<br><br>def build_graph(checkpointer=None):<br>    &quot;&quot;&quot;<br>    Construct and compile the LangGraph StateGraph.<br><br>    Args:<br>        checkpointer:  A LangGraph checkpointer for automatic state<br>                       persistence across turns.  Pass ``None`` for<br>                       stateless single-turn usage (e.g. unit tests).<br>                       Common choices:<br>                         - ``MemorySaver()``      — in-process dict<br>                         - ``SqliteSaver(conn)``   — file-backed<br>                         - ``PostgresSaver(pool)`` — production<br><br>    Required initial state keys:<br>        user_message  — the user&#39;s prompt<br><br>    The CortexClient must be passed via config, not state:<br>        config = {&quot;configurable&quot;: {&quot;client&quot;: client_instance}}<br><br>    When using a checkpointer, also include the session thread_id:<br>        config = {&quot;configurable&quot;: {&quot;client&quot;: client, &quot;thread_id&quot;: &quot;&lt;session&gt;&quot;}}<br>    The checkpointer auto-restores thread_id, parent_message_id,<br>    node_outputs, etc. from the previous turn — no manual carry-forward.<br>    &quot;&quot;&quot;<br>    graph = StateGraph(AgentState)<br><br>    # Nodes<br>    graph.add_node(&quot;pii_check&quot;, pii_check)<br>    graph.add_node(&quot;init_thread&quot;, init_thread)<br>    graph.add_node(&quot;call_agent&quot;, call_agent)<br>    graph.add_node(&quot;execute_tools&quot;, execute_tools)<br><br>    # START → pii_check<br>    graph.add_edge(START, &quot;pii_check&quot;)<br><br>    # pii_check → blocked(END) | clean → init_thread<br>    graph.add_conditional_edges(<br>        &quot;pii_check&quot;,<br>        pii_route,<br>        {<br>            &quot;blocked&quot;: END,<br>            &quot;clean&quot;: &quot;init_thread&quot;,<br>        },<br>    )<br><br>    # init_thread → call_agent<br>    graph.add_edge(&quot;init_thread&quot;, &quot;call_agent&quot;)<br><br>    # call_agent → route → execute_tools | done(END)<br>    graph.add_conditional_edges(<br>        &quot;call_agent&quot;,<br>        route_decision,<br>        {<br>            &quot;execute_tools&quot;: &quot;execute_tools&quot;,<br>            &quot;done&quot;: END,<br>        },<br>    )<br><br>    # execute_tools → call_agent  (loop back)<br>    graph.add_edge(&quot;execute_tools&quot;, &quot;call_agent&quot;)<br><br>    compiled = graph.compile(checkpointer=checkpointer)<br>    logger.info(&quot;LangGraph compiled | checkpointer=%s&quot;,<br>                type(checkpointer).__name__ if checkpointer else &quot;None&quot;)<br>    return compiled</pre><ul><li>cortex_agent/state.py defines the shared AgentState, including thread_id, parent_message_id, pending_tool_calls, tool_results, and node_outputs.</li></ul><pre>&quot;&quot;&quot;LangGraph state for Cortex Agent — client-side tool execution.<br><br>Memory tiers used:<br>  - **Checkpointer** (MemorySaver / SqliteSaver) auto-persists the full state<br>    between invoke() calls sharing the same LangGraph thread_id.  This means<br>    thread_id, parent_message_id, and node_outputs survive across turns without<br>    manual carry-forward in main.py.<br>  - **Cortex server-side thread** still holds the conversation messages.<br>    LangGraph does NOT duplicate that — it only persists orchestration metadata.<br><br>Reducers:<br>  - node_outputs uses a custom merge-reducer so that new per-issue entries are<br>    merged into the existing dict rather than overwriting it.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>from typing import Annotated, Any, TypedDict<br><br><br># ------------------------------------------------------------------ #<br>#  Custom reducer for node_outputs (merge, don&#39;t overwrite)<br># ------------------------------------------------------------------ #<br><br>def _merge_node_outputs(<br>    existing: dict[str, &quot;NodeOutput&quot;] | None,<br>    new: dict[str, &quot;NodeOutput&quot;] | None,<br>) -&gt; dict[str, &quot;NodeOutput&quot;]:<br>    &quot;&quot;&quot;Merge new per-issue entries into the existing dict.<br><br>    This keeps all previously tracked issues in state while adding<br>    or updating entries from the current turn.<br>    &quot;&quot;&quot;<br>    base = dict(existing) if existing else {}<br>    if new:<br>        for key, val in new.items():<br>            if key in base:<br>                # Merge fields — keep existing, overlay new<br>                merged = {**base[key], **val}<br>                base[key] = merged  # type: ignore[assignment]<br>            else:<br>                base[key] = val<br>    return base<br><br><br># ------------------------------------------------------------------ #<br>#  State types<br># ------------------------------------------------------------------ #<br><br>class ToolCall(TypedDict):<br>    &quot;&quot;&quot;A tool call from Cortex Agent (client_side_execute=true).&quot;&quot;&quot;<br>    tool_use_id: str<br>    name: str<br>    input: dict<br><br><br>class ToolResult(TypedDict):<br>    &quot;&quot;&quot;A tool result to send back to Cortex Agent.&quot;&quot;&quot;<br>    tool_use_id: str<br>    content: str<br>    is_error: bool<br><br><br>class NodeOutput(TypedDict, total=False):<br>    &quot;&quot;&quot;<br>    Per-issue tracking object — maps to your projectwork&#39;s NodeOutput model.<br>    Keyed by pipe-delimited IDs in the node_outputs dict.<br>    &quot;&quot;&quot;<br>    agent_name: str<br>    issue_description: str<br>    issue_category: str<br>    id_list: list[str]<br>    jira_no: str<br>    eof: str<br><br><br>class AgentState(TypedDict, total=False):<br>    &quot;&quot;&quot;<br>    Shared state flowing through the LangGraph graph.<br><br>    Mirrors your projectwork&#39;s ChatState but adapted for Cortex Agent<br>    orchestration.  Persisted between turns by the checkpointer.<br><br>    Attributes:<br>        user_message:       Current user prompt.<br>        user_id:            Logged-in user identifier.<br>        chat_id:            Chat session ID.<br>        thread_id:          Cortex thread ID for conversation continuity.<br>        parent_message_id:  Last message ID in the thread.<br>        pending_tool_calls: Tool calls returned by Cortex (client_side_execute).<br>        tool_results:       Results after local tool execution.<br>        final_response:     Agent&#39;s final text response.<br>        node_outputs:       Per-issue tracking — uses merge-reducer so entries<br>                            accumulate across turns (e.g. multiple Jira tickets).<br>        iteration:          Safety counter for tool-execution loops.<br>        pii_blocked:        True if PII was detected and request was blocked.<br>    &quot;&quot;&quot;<br>    user_message: str<br>    user_id: str<br>    chat_id: int<br>    thread_id: str<br>    parent_message_id: int<br>    pending_tool_calls: list[ToolCall]<br>    tool_results: list[ToolResult]<br>    final_response: str<br>    node_outputs: Annotated[dict[str, NodeOutput], _merge_node_outputs]<br>    iteration: int<br>    pii_blocked: bool</pre><ul><li>cortex_agent/tools.py is the local dispatcher that executes client-side tools like Jira creation and record comparison.</li><li>cortex_agent/config.py supplies the agent name, database, schema, PAT, and the tool-loop limit.</li></ul><p>What it does: hands the incoming WebSocket message to the streaming bridge, which runs the LangGraph agent in a thread, captures Cortex SSE events, and forwards them to the browser as they arrive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHLYtzykThI8sk0beGFvdA.png" /></figure><h3>he Tool Round-Trip Loop</h3><p>When the SSE stream contains response.tool_use events with client_side_execute: true, the LangGraph call_agent node returns them to the graph router. The execute_tools node runs the corresponding Python functions locally (Snowflake SDK calls, REST API calls, etc.) and builds tool_result content blocks:</p><pre>{<br>    &quot;type&quot;: &quot;tool_result&quot;,<br>    &quot;tool_result&quot;: {<br>        &quot;tool_use_id&quot;: &quot;...&quot;,<br>        &quot;name&quot;: &quot;validate_ids&quot;,<br>        &quot;content&quot;: [{&quot;type&quot;: &quot;json&quot;, &quot;json&quot;: {&quot;result&quot;: [...]}}],<br>        &quot;status&quot;: &quot;success&quot;<br>    }<br>}</pre><p>These are posted back to /agents/:run with stream=True, starting a new SSE stream. The loop repeats until no tool_use events remain in the response.</p><p>One constraint I hit: json inside a tool_result must be a JSON object ({}), never a string or array. Snowflake&#39;s parser rejects non-object values silently. My client wraps lists and scalars:</p><pre>if isinstance(parsed, dict):<br>    json_value = parsed<br>elif isinstance(parsed, list):<br>    json_value = {&quot;result&quot;: parsed}<br>else:<br>    json_value = {&quot;result&quot;: parsed}</pre><h3>Tradeoffs I Accepted</h3><p><strong>SSE protocol coupling</strong> is real. My event parser is tightly coupled to Snowflake’s SSE event names (response.tool_use, response.text.delta, etc.). When Snowflake changed the response event schema between API versions, my _extract_text fallback was the only safety net.</p><p><strong>The monkey-patch pattern</strong> works but is not pretty. I replaced it in later iterations with a proper LangGraph astream_events call (available when using GPT-4o as orchestrator via compiled_graph.astream_events()). The async-native approach is cleaner — no queue, no thread boundary.</p><p><strong>Tool results add a round-trip.</strong> Every client-side tool call adds one full SSE request-response cycle. For a query that triggers three tools, that is three sequential :run calls before the agent produces final text. Latency is noticeable.</p><h3>What Comes Next: GPT-4o and MCP</h3><p>This architecture keeps all tools in Python and all orchestration inside Snowflake Cortex. That works, but it has a ceiling: the Mistral/Llama3 models reasoning inside Cortex are weaker than GPT-4o for complex multi-step analysis. The SSE protocol coupling is also fragile — I am parsing a schema I do not own.</p><p>The next iteration in this series switches the orchestrator from Snowflake Cortex to GPT-4o, and replaces the hand-wired Python tool registry with <strong>Model Context Protocol (MCP)</strong>. Instead of dispatching tools locally, the agent connects to a Snowflake-hosted MCP server over streamable_http. The tools — identity lookup, source mapping, record comparison — are served as MCP tool definitions and executed inside Snowflake&#39;s infrastructure.</p><pre>GPT-4o (orchestrator)<br>  │<br>  ▼<br>MultiServerMCPClient  (LangGraph ToolNode)<br>  │  streamable_http + PAT<br>  ▼<br>Snowflake MCP Server  (IDENTITY_MCP_SERVER)<br>  │  tools: identity lookups, source mapping, record analysis, FAQ search<br>  ▼<br>Snowflake Cortex Agent  (nested — handles lineage + cross-walk SPs)<br>  │  REST + SSE<br>  ▼<br>Response</pre><p>The graph shrinks from 4 nodes to 2 (supervisor + tools). The monkey-patch queue pattern disappears — LangGraph&#39;s native astream_events async generator handles streaming cleanly. The tradeoff: the tool round-trip becomes a 3-hop chain (GPT-4o → MCP client → MCP server → Cortex Agent → SSE back), and the PII guard from this architecture is absent in the initial MCP version.</p><p>That’s the subject of the next post in this series.</p><h3>Takeaways</h3><ul><li><strong>SSE line parsing is simple but brittle</strong>: event: + data: pairs are easy to parse, but you are coupling to a schema you do not control. Log raw events in development.</li><li><strong>client_side_execute is your routing key</strong>: Snowflake tells you which tools it cannot run itself. Trust it, and skip server-side tool results on the client.</li><li><strong>asyncio.Queue is the right bridge</strong>: For sync-to-async event forwarding, a queue with put_nowait (sync) and wait_for(get(), timeout) (async) is clean and backpressure-safe.</li><li><strong>Monkey-patching for streaming is a smell</strong>: It works, but the correct fix is an async-native streaming primitive at the graph level (astream_events). Plan for it from the start.</li><li><strong>Tool results must be objects</strong>: Snowflake’s tool_result.content[].json field rejects non-dict values silently. Wrap your data defensively.</li></ul><p><em>Disclaimer: This article reflects my personal engineering experience. All examples are anonymized and shared for educational purposes.</em></p><p><em>Tags: LangGraph, Snowflake, AI Agents, FastAPI, Python, SSE, LangChain, Cortex</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366142e9803a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>