> ## Documentation Index
> Fetch the complete documentation index at: https://docs.elementum.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Snowflake Cortex Agents Setup

> Complete guide to integrating Snowflake Cortex Agents into Elementum Apps through Intelligence configuration

## Overview

By connecting Cortex Agents to your Elementum Apps, you enable AI-powered automation that runs directly on your Snowflake data warehouse, maintaining data security while leveraging advanced AI capabilities.

Cortex Agents are configured at the **App level** through the Intelligence settings, allowing each App to discover and use external agents available through its CloudLink connection.

## Prerequisites

Before beginning this setup, ensure you have the following in place:

### Elementum Requirements

* **App access**: Access to the App where you want to integrate Cortex Agents.
* **Snowflake AI Provider**: A configured Snowflake AI Provider with a CloudLink that uses **key-pair authentication**.

<Warning>
  **Authentication Requirement**: Snowflake Cortex Agents require a Snowflake AI Provider configured with key-pair authentication. Password-based CloudLinks cannot access Cortex features.
</Warning>

### Snowflake Requirements

Your Snowflake environment must have:

* **Snowflake Edition**: Enterprise or higher
* **Cortex AI Features**: Enabled on your account
* **Cortex Agents**: At least one Cortex Agent configured in your Snowflake account
* **Permissions**: Service account with USAGE privileges on:
  * Cortex functions
  * Agent resources
  * Target database and schema

### Verify Your Snowflake AI Provider

Before proceeding, verify you have a Snowflake AI Provider configured:

<Steps>
  <Step title="Navigate to Organization Settings">
    Go to **Organization Settings** → **Providers**
  </Step>

  <Step title="Check Snowflake Provider">
    Verify a Snowflake provider is configured

    Ensure it uses a CloudLink with **Key-Pair Authentication**
  </Step>

  <Step title="Test Provider">
    Verify the provider is active and can connect to Snowflake
  </Step>
</Steps>

<Info>
  **Need Help with Providers?** See the [Snowflake Cortex Setup Guide](/ai-agents/snowflake-cortex-setup) for detailed instructions on configuring Snowflake AI Providers with key-pair authentication.
</Info>

## Step 1: Prepare Snowflake Cortex Agents

Before connecting to Elementum, ensure your Cortex Agents are properly configured in Snowflake.

### Verify Cortex Agents in Snowflake

<Tabs>
  <Tab title="Using Snowflake UI">
    1. Log into your Snowflake account
    2. Navigate to **AI & ML** → **Cortex Agents**
    3. Verify your agents are listed and active
    4. Note the database and schema where agents are located
  </Tab>

  <Tab title="Using SQL">
    ```sql theme={null}
    -- List available Cortex Agents
    SHOW CORTEX AGENTS IN DATABASE your_database;

    -- View agent details
    DESCRIBE CORTEX AGENT your_database.your_schema.agent_name;
    ```
  </Tab>
</Tabs>

### Required Permissions

Ensure your service account has the necessary permissions:

```sql theme={null}
-- Grant usage on database and schema
GRANT USAGE ON DATABASE your_database TO ROLE elementum_role;
GRANT USAGE ON SCHEMA your_database.your_schema TO ROLE elementum_role;

-- Grant usage on Cortex features
GRANT USAGE ON CORTEX TO ROLE elementum_role;

-- Grant execute on specific agents
GRANT USAGE ON CORTEX AGENT your_database.your_schema.agent_name 
  TO ROLE elementum_role;
```

<Info>
  **Principle of Least Privilege**: Grant only the minimum permissions necessary for the agents and data your Elementum automations will access.
</Info>

## Step 2: Configure Intelligence in Your App

Now you're ready to discover and configure Snowflake Cortex Agents through your App's Intelligence settings.

### Access Intelligence Settings

<Steps>
  <Step title="Navigate to Your App">
    Go to the App where you want to integrate Cortex Agents
  </Step>

  <Step title="Open Intelligence">
    Click **Intelligence** in the App menu
  </Step>
</Steps>

### Add External Agent

<Steps>
  <Step title="Add Agent">
    Click the **Add Agent** button at the top of the Intelligence page
  </Step>

  <Step title="Select External">
    In the agent type selection, choose **External**

    This indicates you're connecting to an agent hosted outside Elementum
  </Step>

  <Step title="Select Snowflake AI Provider">
    Choose your configured Snowflake AI Provider from the dropdown

    **Provider Selection:**

    * Only Snowflake providers with key-pair authentication appear
    * The provider must have access to Cortex features
    * Multiple providers can be available if you have different Snowflake environments
  </Step>

  <Step title="Discover Agents">
    The system uses the selected provider to discover available Cortex Agents

    **What happens:**

    * Elementum connects to Snowflake using the provider's CloudLink credentials
    * Queries the Snowflake Cortex REST API for available agents
    * Lists all agents accessible through the provider's service account
  </Step>

  <Step title="Select Cortex Agent">
    From the discovered agents list, select the Cortex Agent you want to use

    You'll see:

    * Agent name
    * Agent description
    * Database and schema location
    * Available capabilities
  </Step>

  <Step title="Configure Agent Settings">
    **Agent Name**: Optionally customize the display name in Elementum

    **Description**: Add notes about how this agent will be used in your App

    **Configuration**: Review agent input/output schemas
  </Step>

  <Step title="Save Configuration">
    Click **Save** to connect the external agent

    The agent will now appear in your App's Intelligence configuration
  </Step>
</Steps>

### What Happens During Discovery

When you add an external agent, Elementum:

1. **Selects Provider**: Uses the selected Snowflake AI Provider's connection
2. **Authenticates**: Authenticates with Snowflake using the provider's CloudLink credentials
3. **Discovers Agents**: Queries the Cortex REST API for available agents
4. **Retrieves Metadata**: Gets agent capabilities, schemas, and configuration
5. **Registers Agent**: Makes the agent available for use in App automations
6. **Monitors Status**: Tracks agent availability through the provider connection

```mermaid theme={null}
sequenceDiagram
    participant App as App Intelligence
    participant Prov as Snowflake AI Provider
    participant CL as CloudLink
    participant SF as Snowflake
    participant API as Cortex REST API
    
    App->>Prov: Request Agent Discovery
    Prov->>CL: Use Provider CloudLink
    CL->>SF: Authenticate (Key-Pair)
    SF->>CL: Connection Established
    Prov->>API: List Available Agents
    API->>Prov: Return Agent Metadata
    Prov->>App: Display Available Agents
    App->>App: Register Selected Agent
```

## Step 3: Understanding Cortex REST APIs

Elementum leverages three primary Snowflake Cortex APIs for agent integration:

### Agent Discovery API

Discovers available agents accessible through your CloudLink.

**Snowflake Documentation**: [Cortex Agents REST API](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-rest-api)

**What Elementum Retrieves:**

* Agent names and identifiers
* Agent capabilities and descriptions
* Input/output schemas
* Required permissions
* Configuration metadata

### Agent Run API

Executes agent tasks and retrieves results.

**Snowflake Documentation**: [Cortex Agents Run](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-run)

**Used For:**

* Invoking agents from automations
* Passing input parameters
* Receiving agent responses
* Monitoring execution status
* Handling errors and timeouts

### Threads API

Manages conversational threads for stateful agent interactions.

**Snowflake Documentation**: [Cortex Agents Threads REST API](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-threads-rest-api)

**Capabilities:**

* Create conversation threads
* Maintain context across interactions
* Retrieve conversation history
* Resume interrupted conversations
* Manage thread lifecycle

<Info>
  **API Authentication**: All API calls use the credentials from the selected Snowflake AI Provider's CloudLink connection, ensuring secure and auditable access to Cortex resources.
</Info>

## Step 4: Integrate Agents into Automations

With your Cortex Agent configured in Intelligence, you can now use it in App automations.

### Using External Agents in Automation Actions

<Steps>
  <Step title="Navigate to Automation Configuration">
    In your App, go to the automation where you want to use the external agent
  </Step>

  <Step title="Add Agent Action">
    Add a new automation action or edit an existing one

    Select **Agent Action** as the action type
  </Step>

  <Step title="Select Your External Agent">
    In the agent configuration:

    **Agent**: Choose the external Cortex Agent you configured in Intelligence

    The agent will be labeled as **External** or **Managed**
  </Step>

  <Step title="Configure Parameters">
    **Input Mapping**: Map automation data to agent input parameters

    * Use field values from the current record
    * Reference previous automation action outputs
    * Include static values or formulas

    **Output Handling**: Configure how to handle agent responses

    * Map agent outputs to record fields
    * Store results for later automation actions
    * Set error handling behavior
  </Step>

  <Step title="Set Execution Options">
    **Timeout**: Set maximum execution time (default: 60 seconds)

    **Retry Policy**: Configure retry behavior for failures

    **Error Handling**: Define what happens if the agent fails

    * Continue automation with default values
    * Halt automation and alert user
    * Escalate to human review
  </Step>

  <Step title="Test Integration">
    Use the automation test mode to verify agent integration

    Monitor execution logs for agent calls and responses
  </Step>
</Steps>

### Example: Data Analysis Automation

**Scenario**: Automatically analyze sales data when a monthly report is requested

```yaml theme={null}
Workflow: Monthly Sales Analysis
Trigger: Report requested
Automations:
  1. Gather Data:
     - Collect sales records for the month
     - Aggregate by region and product
  
  2. External Agent - Analysis:
     Type: External Agent (Cortex)
     Agent: Sales Analysis Agent
     Inputs:
       - sales_data: {aggregated_data}
       - analysis_type: "trend_analysis"
       - time_period: "monthly"
     Outputs:
       - trends: record.analysis_results
       - insights: record.key_insights
       - forecast: record.forecast_data
  
  3. Generate Report:
     - Create formatted report with insights
     - Include visualizations from forecast
  
  4. Distribute:
     - Email report to stakeholders
     - Post summary to Teams channel
```

### Using Agents in Multiple Automations

External agents configured in Intelligence can be used across multiple automations within the same App:

<Accordion title="Automation Example: Anomaly Detection">
  **Trigger**: New transaction record created

  **Conditions**: Transaction amount > \$10,000

  **Actions**:

  1. **Call External Agent**
     * Agent: Fraud Detection Agent (Cortex)
     * Input: Transaction details and customer history
     * Output: Risk score and explanation

  2. **Conditional Logic**
     * If risk\_score > 75: Flag for review and notify security team
     * If risk\_score 50-75: Request additional verification
     * If risk\_score \< 50: Auto-approve transaction

  3. **Log Results**
     * Record analysis in audit log
     * Update transaction status based on outcome
</Accordion>

## Step 5: Monitor and Maintain

### Monitoring Agent Performance

<CardGroup cols={2}>
  <Card title="Automation Logs" icon="list">
    View agent execution logs in automation history

    Monitor:

    * Invocation frequency
    * Response times
    * Success/failure rates
    * Error messages
  </Card>

  <Card title="Intelligence Dashboard" icon="chart-line">
    Track agent usage in Intelligence settings

    View:

    * Active agent connections
    * Last successful execution
    * Configuration changes
    * CloudLink status
  </Card>
</CardGroup>

### Provider Connection Health

Since external agents depend on the Snowflake AI Provider:

* **Monitor Provider Status**: Ensure the provider and its CloudLink remain active
* **Check Connectivity**: Regularly test Snowflake connectivity through the provider
* **Review Permissions**: Verify service account permissions haven't changed
* **Update Credentials**: Rotate provider CloudLink keys according to your security policy

<Tip>
  **Snowflake Monitoring**: Use Snowflake's query history and warehouse monitoring to track Cortex Agent compute costs and performance. This complements Elementum's automation logs.
</Tip>

### Maintenance Tasks

<Tabs>
  <Tab title="Regular Maintenance">
    **Weekly**:

    * Review automation logs for agent errors
    * Monitor agent performance metrics
    * Check for timeout or failure patterns

    **Monthly**:

    * Review agent usage and optimization opportunities
    * Audit permissions and access patterns
    * Test agent functionality after Snowflake updates

    **Quarterly**:

    * Rotate provider CloudLink credentials
    * Review and optimize automation integrations
    * Evaluate new Cortex Agent capabilities
  </Tab>

  <Tab title="Updating Agents">
    When you update agents in Snowflake:

    1. **Test Changes**: Verify agent behavior in Snowflake first
    2. **Refresh Intelligence**: Re-discover agents in Intelligence settings if schemas changed
    3. **Update Automations**: Modify automations if input/output schemas changed
    4. **Test Integrations**: Validate all automations using the updated agent
    5. **Monitor**: Watch for issues after deployment
  </Tab>

  <Tab title="Scaling Considerations">
    As usage grows:

    **Snowflake Side**:

    * Scale warehouse size for agent workloads
    * Consider dedicated warehouses for different agent types
    * Implement resource monitors to control costs

    **Elementum Side**:

    * Monitor automation execution times
    * Implement caching for frequently accessed agent results
    * Use async invocations for long-running agents
    * Configure multiple Snowflake AI Providers for different environments or redundancy
  </Tab>
</Tabs>

## Configuration Best Practices

### Security Best Practices

<CardGroup cols={2}>
  <Card title="Access Control" icon="lock">
    **Minimal Permissions**: Grant only necessary privileges

    **Role Separation**: Use dedicated roles for agent access

    **Audit Logging**: Enable comprehensive audit trails

    **Regular Reviews**: Quarterly access audits
  </Card>

  <Card title="Credential Management" icon="key">
    **Rotation Schedule**: Rotate keys every 90 days

    **Secure Storage**: CloudLink manages credential encryption

    **No Sharing**: Unique credentials per environment

    **Revocation Process**: Document emergency revocation steps
  </Card>
</CardGroup>

### Performance Optimization

1. **Warehouse Sizing**
   * Use appropriately sized warehouses for agent complexity
   * Consider multi-cluster warehouses for concurrent agent calls
   * Enable auto-suspend to minimize costs

2. **Provider Management**
   * Provider connections are reused across multiple agent invocations
   * Monitor provider connection performance metrics
   * Configure appropriate timeout values

3. **Timeout Configuration**
   * Set realistic timeouts based on agent complexity
   * Implement progressive timeout strategies
   * Consider async patterns for very long-running operations

4. **Caching Strategies**
   * Cache agent responses for identical inputs
   * Implement time-based cache invalidation
   * Use Snowflake result caching when appropriate

### Error Handling Patterns

<Accordion title="Retry Logic">
  **Transient Failures**: Implement exponential backoff for temporary issues

  ```
  Attempt 1: Immediate
  Attempt 2: Wait 2 seconds
  Attempt 3: Wait 4 seconds
  Attempt 4: Wait 8 seconds
  Max Attempts: 4
  ```

  **Permanent Failures**: Don't retry for authentication or permission errors

  **Circuit Breaker**: Stop attempting after consecutive failures reach threshold
</Accordion>

<Accordion title="Fallback Strategies">
  **Default Values**: Use sensible defaults when agent unavailable

  **Alternative Agents**: Configure backup agents for critical operations

  **Human Escalation**: Route to human review when automated analysis fails

  **Graceful Degradation**: Continue automation with reduced functionality
</Accordion>

## Troubleshooting

### Discovery Issues

<Accordion title="No Agents Discovered">
  **Error**: "No agents found" when adding external agent

  **Possible Causes**:

  * Snowflake AI Provider not configured or inactive
  * Provider's CloudLink has wrong permissions
  * No Cortex Agents configured in Snowflake
  * Service account lacks USAGE privileges

  **Solutions**:

  1. Verify Snowflake AI Provider is configured in Organization Settings → Providers
  2. Check that provider uses a CloudLink with key-pair authentication
  3. Run `SHOW CORTEX AGENTS` in Snowflake to verify agents exist
  4. Verify service account has USAGE privileges on Cortex
  5. Check database and schema permissions
  6. Test provider connection in Provider settings
</Accordion>

<Accordion title="Provider Authentication Failed">
  **Error**: "Unable to authenticate with Snowflake"

  **Possible Causes**:

  * Provider CloudLink not configured with key-pair authentication
  * Expired or invalid credentials
  * Network connectivity issues
  * Snowflake account unavailable

  **Solutions**:

  1. Verify provider uses CloudLink with key-pair authentication (not password)
  2. Test provider connection in Organization Settings → Providers
  3. Check for expired credentials and refresh provider if needed
  4. Verify network connectivity to Snowflake
  5. Confirm Snowflake account is active and accessible
  6. Review provider configuration and CloudLink settings
</Accordion>

<Accordion title="Permission Denied Errors">
  **Error**: "Access denied to Cortex resources"

  **Possible Causes**:

  * Missing USAGE grant on Cortex
  * Insufficient privileges on agent
  * Role not properly assigned
  * Database or schema access missing

  **Solutions**:

  ```sql theme={null}
  -- Verify current role and grants
  SHOW GRANTS TO ROLE elementum_role;

  -- Grant necessary permissions
  GRANT USAGE ON DATABASE your_database TO ROLE elementum_role;
  GRANT USAGE ON SCHEMA your_database.your_schema TO ROLE elementum_role;
  GRANT USAGE ON CORTEX TO ROLE elementum_role;
  GRANT USAGE ON CORTEX AGENT your_database.your_schema.agent_name 
    TO ROLE elementum_role;
  ```
</Accordion>

### Runtime Issues

<Accordion title="Agent Timeout">
  **Error**: "Agent execution exceeded timeout"

  **Possible Causes**:

  * Agent task too complex for timeout setting
  * Insufficient Snowflake warehouse resources
  * Network latency issues
  * Agent accessing large datasets

  **Solutions**:

  1. Increase timeout value in automation configuration
  2. Scale up Snowflake warehouse for agent workload
  3. Optimize agent queries and data access
  4. Consider splitting complex tasks into multiple automation actions
  5. Use async invocation for long-running operations
</Accordion>

<Accordion title="Agent Returns Unexpected Results">
  **Error**: Agent output doesn't match expected format

  **Possible Causes**:

  * Input parameters incorrect or malformed
  * Agent configuration changed in Snowflake
  * Schema version mismatch
  * Data quality issues in source data

  **Solutions**:

  1. Validate input parameters match agent expectations
  2. Test agent directly in Snowflake with same inputs
  3. Check for recent agent updates or schema changes
  4. Review agent logs in Snowflake for execution details
  5. Verify data quality and completeness
</Accordion>

<Accordion title="High Latency">
  **Error**: Agent responses taking too long

  **Possible Causes**:

  * Undersized Snowflake warehouse
  * Network latency between Elementum and Snowflake
  * Agent querying large datasets inefficiently
  * Cold warehouse startup time

  **Solutions**:

  1. Use larger warehouse for agent operations
  2. Keep warehouse running during peak usage (disable auto-suspend temporarily)
  3. Optimize agent queries and data access patterns
  4. Consider warehouse dedicated to agent workloads
  5. Implement result caching for repeated queries
</Accordion>

## Multi-App Configurations

### Using Agents Across Multiple Apps

Each App configures its own external agents through Intelligence:

* **Configure per App**: Each App that needs Cortex Agents must configure them individually, even if multiple Apps connect to the same Snowflake agents.
* **Provider selection**: Apps can use the same Snowflake AI Provider (shared access) or different providers (isolated access or different Snowflake environments).
* **Independent configuration**: Each App can select different providers, use different agents from the same provider, configure the same agent differently, and define unique timeout and error handling settings.
* **Monitor separately**: Track agent usage and performance per App in each App's Intelligence dashboard.

### Multi-Environment Setup

For organizations with multiple environments (dev, staging, production):

<Steps>
  <Step title="Environment-Specific Providers">
    Configure separate Snowflake AI Providers for each environment

    Each provider uses a CloudLink with environment-specific service accounts
  </Step>

  <Step title="Configure Agents Per Environment">
    In each environment's App, configure external agents through Intelligence

    Select the appropriate provider (dev/staging/prod) to discover agents
  </Step>

  <Step title="Test Thoroughly">
    Test in dev environment before deploying to production

    Validate in staging with production-like data
  </Step>

  <Step title="Deployment Process">
    When deploying configurations:

    * Test agent connectivity in target environment
    * Verify provider configuration is correct for the environment
    * Validate automation configurations
    * Monitor closely after deployment
  </Step>
</Steps>

## Example Use Cases

<AccordionGroup>
  <Accordion title="Use Case 1: Automated Data Quality Checks">
    **Scenario**: Automatically validate data quality when new datasets are loaded

    **Implementation**:

    1. Create Cortex Agent in Snowflake for data profiling and quality analysis
    2. In your Data Management App, configure the agent through Intelligence
    3. Set up automation trigger on data load completion
    4. Agent analyzes dataset and returns quality metrics
    5. Automation creates alerts or blocks further processing based on results

    **Benefits**:

    * Immediate data quality feedback
    * Prevents downstream issues from bad data
    * Reduces manual validation effort
    * Maintains audit trail of quality checks
  </Accordion>

  <Accordion title="Use Case 2: Intelligent Customer Support">
    **Scenario**: L1 support agent with direct access to customer data warehouse

    **Implementation**:

    1. Create Cortex Agent trained on support knowledge base and customer data
    2. Configure agent in Support App through Intelligence
    3. Integrate agent into support automation
    4. Customer inquiry triggers agent to analyze history and suggest resolution
    5. Agent creates ticket with context and recommended actions

    **Benefits**:

    * Faster response times for customers
    * Consistent support quality
    * Reduces escalations to L2 support
    * Data stays secure in Snowflake environment
  </Accordion>

  <Accordion title="Use Case 3: Financial Reporting Automation">
    **Scenario**: Generate executive reports with natural language insights

    **Implementation**:

    1. Create Cortex Agent for financial analysis and narrative generation
    2. Configure agent in Finance App through Intelligence
    3. Schedule monthly report generation automation
    4. Agent analyzes trends, generates insights, and creates narrative
    5. Report distributed automatically with executive summary

    **Benefits**:

    * Consistent reporting schedule
    * Natural language insights for non-technical stakeholders
    * Reduces analyst workload
    * Real-time access to latest data
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Agent tools, deployment, and integrations" icon="diagram-project" href="/ai-agents/agents-tools-and-deployment">
    Understand the technical architecture and A2A protocol
  </Card>

  <Card title="Automation System" icon="robot" href="/workflows/automation-system">
    Learn how to build sophisticated automations with agents
  </Card>

  <Card title="Snowflake Cortex Docs" icon="snowflake" href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents-rest-api">
    Reference Snowflake's official Cortex Agents documentation
  </Card>
</CardGroup>

***

*By integrating Snowflake Cortex Agents through your App's Intelligence configuration, you create a powerful automation ecosystem that combines the flexibility of AI with the security of keeping your data in your own warehouse. This architecture ensures compliance, performance, and scalability for enterprise deployments.*
